Skip to content

armgit / OXR

Public Imported from GitHub
0

An open-source document parsing model with SOTA accuracy and speed, using an RSI loop during post-training.

init

Soul-Code8532b8cb3e2a
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..3363003
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,36 @@
+.git
+AGENTS.md
+CLAUDE.md
+**/AGENTS.md
+**/CLAUDE.md
+**/AGENTS.override.md
+**/GEMINI.md
+**/copilot-instructions.md
+**/[Aa][Gg][Ee][Nn][Tt][Ss].md
+**/[Aa][Gg][Ee][Nn][Tt][Ss].override.md
+**/[Cc][Ll][Aa][Uu][Dd][Ee].md
+**/[Gg][Ee][Mm][Ii][Nn][Ii].md
+docs/overlap-postprocess-validation.md
+.agents
+.codex
+.claude
+.cursor
+.env.*
+tests
+**/tests
+samples
+.venv
+venv
+**/__pycache__
+**/*.py[cod]
+.pytest_cache
+.coverage
+htmlcov
+.env
+config.yaml
+config.local.yaml
+outputs
+**/*.pth
+**/*.safetensors
+services/layout_analyze/models/*
+!services/layout_analyze/models/README.md
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8463cce
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,52 @@
+__pycache__/
+*.py[cod]
+*$py.class
+*.so
+.Python
+env/
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+!oxr/server/demo/lib/
+!oxr/server/demo/lib/**
+lib64/
+parts/
+sdist/
+var/
+wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+.env
+.venv
+venv/
+ENV/
+outputs/
+output/
+.pytest_cache/
+.coverage
+htmlcov/
+.claude/
+.trae/
+uv.lock
+config.yaml
+config.local.yaml
+.playwright-cli/
+.DS_Store
+.superpowers/
+.worktrees/
+
+# Local coding-assistant instructions and private validation records.
+[Aa][Gg][Ee][Nn][Tt][Ss].md
+[Aa][Gg][Ee][Nn][Tt][Ss].override.md
+[Cc][Ll][Aa][Uu][Dd][Ee].md
+[Gg][Ee][Mm][Ii][Nn][Ii].md
+copilot-instructions.md
+.codex/
+.agents/
+.cursor/
+docs/overlap-postprocess-validation.md
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..e69de29
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..2d40af5
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,44 @@
+OXR
+Official source: https://github.com/SoMarkAI/OXR
+
+Third-party source attributions
+
+1. XY-Cut++ (authors' implementation)
+ Paper authors: Shuai Liu, Youmeng Li, Jizeng Wei.
+ Paper: https://arxiv.org/abs/2504.10258
+ oxr/pipeline/_vendor/xycut_plus_plus.py contains a function closure adapted
+ from the authors' implementation at https://github.com/liushuai35/PaddleXrc,
+ commit
+ 7873ab38662e3277091520f4259f090bc197fee4.
+ Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
+ Distributed under the Apache License, Version 2.0.
+ OXR adds an order-only mode with overlap removal disabled; the vendored
+ source retains its upstream copyright and license notices.
+
+2. D-FINE
+ services/layout_analyze contains an inference-only adaptation of
+ https://github.com/Peterande/D-FINE, distributed under the Apache License,
+ Version 2.0. See services/layout_analyze/THIRD_PARTY_NOTICES.md and
+ services/layout_analyze/third_party/D-FINE/LICENSE for attribution and
+ adaptation details.
+
+3. SoMarkDown Viewer
+ The OXR Online Demo adapts the Viewer interface and includes its packaged
+ SoMarkDown renderer (version recorded in demo/vendor/somarkdown/VERSION),
+ styles, and fonts under oxr/server/demo. The upstream license is retained
+ in oxr/server/demo/LICENSE-SoMarkDownViewer; vendor files retain their
+ embedded attribution notices.
+
+4. Demo rendering styles and fonts
+ KaTeX 0.16.9 styles: https://github.com/KaTeX/KaTeX/tree/v0.16.9
+ MIT license: oxr/server/demo/vendor/deps/LICENSE-KaTeX (upstream LICENSE).
+ KaTeX fonts retain their embedded copyright and reserved font names;
+ SIL Open Font License 1.1 and those notices are included in
+ oxr/server/demo/vendor/deps/katex_fonts/OFL.txt.
+ highlight.js 11.9.0 styles: https://github.com/highlightjs/highlight.js/tree/11.9.0
+ BSD 3-Clause license: oxr/server/demo/vendor/deps/LICENSE-highlight.js
+ (upstream LICENSE).
+
+Model weights are not included in this code distribution. Their distribution
+terms are provided separately by the model repositories; this code license
+does not assign a license to those weights.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e69de29
diff --git a/README_CN.md b/README_CN.md
new file mode 100644
index 0000000..e69de29
diff --git a/config.example.yaml b/config.example.yaml
new file mode 100644
index 0000000..0d84ab3
--- /dev/null
+++ b/config.example.yaml
@@ -0,0 +1,49 @@
+server:
+ # Host address the HTTP server binds to.
+ host: 0.0.0.0
+ # Port number the HTTP server listens on.
+ port: 8000
+ # Number of server worker processes to start.
+ workers: 1
+
+layout_analyze_model:
+ # Base URL of the external D-FINE layout service (it receives POST /inference).
+ url: http://127.0.0.1:8081
+ # Pages in each multipart layout request.
+ batch_size: 8
+ # Concurrent D-FINE HTTP attempts.
+ max_concurrency: 2
+ # Seconds allowed for each D-FINE HTTP attempt.
+ timeout: 60
+ # Total whole-batch HTTP attempts, including the initial attempt.
+ retry_times: 2
+ # Keep candidates whose confidence score is at least this value.
+ score_threshold: 0.5
+ # Set true only when the layout service returns blocks in reading order.
+ provides_reading_order: false
+
+oxr_model:
+ # Model identifier used when sending requests to the OXR OpenAI-compatible API.
+ model_name: oxr
+ # Base URL of the OXR OpenAI-compatible model service.
+ url: http://127.0.0.1:8080/v1
+ # Maximum number of tokens the model can generate per request.
+ max_tokens: 8192
+ # Global concurrent recognition and reading-order HTTP attempts.
+ max_concurrency: 16
+ # Seconds allowed for each OXR HTTP attempt.
+ timeout: 120
+ # Total HTTP attempts per OXR request, including the initial attempt.
+ retry_times: 2
+
+pipeline:
+ # Directory used to save extracted image outputs.
+ image_output_dir: outputs
+ # Opt in to all-category cleanup: outer boxes absorb contained boxes first;
+ # any remaining positive-area overlap keeps the higher LA confidence.
+ # Equal confidence keeps the earlier block; missing confidence skips comparison.
+ full_overlap_dedupe: false
+ # Restore confident Picture blocks fully contained in a Table via numbered
+ # blue/white <tit> tokens. Incomplete IDs fall back to the original table image.
+ table_image_placeholders: false
+ table_image_min_score: 0.5
diff --git a/docker/Dockerfile.allinone b/docker/Dockerfile.allinone
new file mode 100644
index 0000000..ce0acc0
--- /dev/null
+++ b/docker/Dockerfile.allinone
@@ -0,0 +1,40 @@
+# Match the publicly available runtime used for model reproduction.
+ARG VLLM_IMAGE=vllm/vllm-openai:v0.25.1@sha256:e4f88a835143cd22aee2397a26ec6bb80b3a4a6fe0c882bcbc63822904766089
+FROM ${VLLM_IMAGE}
+
+# Allow a public package mirror for builds with slow access to PyPI.
+ARG PIP_INDEX_URL=https://pypi.org/simple
+
+ENV PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUNBUFFERED=1 \
+ PIP_NO_CACHE_DIR=1 \
+ MODEL_PATH=/models/oxr-model \
+ OXR_SERVED_MODEL_NAME=oxr \
+ OXR_API_PORT=8000 \
+ VLLM_PORT=8080 \
+ DFINE_PORT=8081 \
+ VLLM_GPU_MEMORY_UTILIZATION=0.70 \
+ VLLM_MAX_MODEL_LEN=16384 \
+ ALLINONE_STARTUP_TIMEOUT=900 \
+ DFINE_DEVICE=cuda \
+ DFINE_CUDA_GRAPH=1 \
+ DFINE_PARALLEL_PREPROCESS=1
+
+WORKDIR /app
+COPY . /app/
+
+# Keep API, LA preprocessing and the model plugin in separate environments.
+# Only the model environment consumes the frozen base inference dependencies.
+RUN python3 -m venv --system-site-packages /opt/vllm-venv \
+ && /opt/vllm-venv/bin/python -m pip install --no-cache-dir 'setuptools>=69' wheel \
+ && python3 -m venv --system-site-packages /opt/oxr-venv \
+ && /opt/oxr-venv/bin/python -m pip install --no-cache-dir \
+ -c /app/docker/requirements.allinone.txt /app \
+ && python3 -m venv --system-site-packages /opt/dfine-venv \
+ && /opt/dfine-venv/bin/python -m pip install --no-cache-dir \
+ -r /app/services/layout_analyze/requirements.txt
+
+EXPOSE 8000
+HEALTHCHECK --interval=30s --timeout=10s --start-period=15m --retries=3 \
+ CMD ["/opt/oxr-venv/bin/python", "/app/docker/allinone_entrypoint.py", "--healthcheck"]
+ENTRYPOINT ["/opt/oxr-venv/bin/python", "/app/docker/allinone_entrypoint.py"]
diff --git a/docker/allinone_entrypoint.py b/docker/allinone_entrypoint.py
new file mode 100644
index 0000000..aa2c477
--- /dev/null
+++ b/docker/allinone_entrypoint.py
@@ -0,0 +1,560 @@
+#!/usr/bin/env python3
+"""Supervise the D-FINE, vLLM, and OXR API processes in one container."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+from dataclasses import dataclass
+import logging
+import os
+from pathlib import Path
+import shlex
+import shutil
+import signal
+import sys
+import tempfile
+from typing import Mapping, Sequence
+
+import httpx
+
+
+LOGGER = logging.getLogger("oxr.allinone")
+APP_ROOT = Path("/app")
+
+
+def _env_int(env: Mapping[str, str], name: str, default: int) -> int:
+ raw_value = env.get(name, str(default))
+ try:
+ value = int(raw_value)
+ except ValueError as exc:
+ raise ValueError(f"{name} must be an integer; got {raw_value!r}") from exc
+ if value <= 0:
+ raise ValueError(f"{name} must be greater than zero; got {value}")
+ return value
+
+
+def _env_port(env: Mapping[str, str], name: str, default: int) -> int:
+ value = _env_int(env, name, default)
+ if value > 65535:
+ raise ValueError(f"{name} must be at most 65535; got {value}")
+ return value
+
+
+def _required(env: Mapping[str, str], name: str) -> str:
+ value = env.get(name, "").strip()
+ if not value:
+ raise ValueError(f"{name} must be set")
+ return value
+
+
+@dataclass(frozen=True)
+class AllInOneConfig:
+ model_name: str
+ served_model_name: str
+ dfine_model_path: str
+ api_host: str
+ api_port: int
+ vllm_port: int
+ dfine_port: int
+ gpu_memory_utilization: float
+ max_model_len: int
+ startup_timeout: int
+ shutdown_timeout: int
+ vllm_python: str
+ oxr_bin: str
+ dfine_python: str
+ vllm_extra_args: tuple[str, ...]
+
+ @classmethod
+ def from_env(cls, env: Mapping[str, str] | None = None) -> "AllInOneConfig":
+ source = os.environ if env is None else env
+ raw_utilization = source.get("VLLM_GPU_MEMORY_UTILIZATION", "0.70")
+ try:
+ gpu_memory_utilization = float(raw_utilization)
+ except ValueError as exc:
+ raise ValueError(
+ "VLLM_GPU_MEMORY_UTILIZATION must be a number between 0 and 1; "
+ f"got {raw_utilization!r}"
+ ) from exc
+ if not 0 < gpu_memory_utilization < 1:
+ raise ValueError(
+ "VLLM_GPU_MEMORY_UTILIZATION must be greater than 0 and less than 1; "
+ f"got {gpu_memory_utilization}"
+ )
+
+ ports = {
+ "OXR_API_PORT": _env_port(source, "OXR_API_PORT", 8000),
+ "VLLM_PORT": _env_port(source, "VLLM_PORT", 8080),
+ "DFINE_PORT": _env_port(source, "DFINE_PORT", 8081),
+ }
+ if len(set(ports.values())) != len(ports):
+ raise ValueError(f"OXR_API_PORT, VLLM_PORT, and DFINE_PORT must be distinct: {ports}")
+
+ model_path = _required(source, "MODEL_PATH")
+ dfine_model_path = source.get(
+ "DFINE_MODEL_PATH", str(Path(model_path) / "layout_analysis" / "last.pth")
+ ).strip()
+ if not dfine_model_path:
+ raise ValueError("DFINE_MODEL_PATH must be set")
+
+ vllm_extra_args = tuple(shlex.split(source.get("VLLM_EXTRA_ARGS", "")))
+ managed_vllm_options = {
+ "--gpu-memory-utilization",
+ "--host",
+ "--max-model-len",
+ "--port",
+ "--served-model-name",
+ "--chat-template",
+ "--dtype",
+ "--model",
+ "--max-num-seqs",
+ "--attention-config",
+ "--attention-backend",
+ "-ac",
+ }
+ conflicts = sorted(
+ argument
+ for argument in vllm_extra_args
+ if argument in managed_vllm_options
+ or any(argument.startswith(f"{option}=") for option in managed_vllm_options)
+ or argument.startswith("--attention-config.")
+ or argument.startswith("-ac.")
+ )
+ if conflicts:
+ raise ValueError(
+ "VLLM_EXTRA_ARGS cannot override managed options: " + ", ".join(conflicts)
+ )
+
+ return cls(
+ model_name=model_path,
+ served_model_name=source.get("OXR_SERVED_MODEL_NAME", "oxr").strip() or "oxr",
+ dfine_model_path=dfine_model_path,
+ api_host=source.get("OXR_API_HOST", "0.0.0.0").strip() or "0.0.0.0",
+ api_port=ports["OXR_API_PORT"],
+ vllm_port=ports["VLLM_PORT"],
+ dfine_port=ports["DFINE_PORT"],
+ gpu_memory_utilization=gpu_memory_utilization,
+ max_model_len=_env_int(source, "VLLM_MAX_MODEL_LEN", 16384),
+ startup_timeout=_env_int(source, "ALLINONE_STARTUP_TIMEOUT", 900),
+ shutdown_timeout=_env_int(source, "ALLINONE_SHUTDOWN_TIMEOUT", 30),
+ vllm_python=source.get("VLLM_PYTHON", "/opt/vllm-venv/bin/python"),
+ oxr_bin=source.get("OXR_BIN", "/opt/oxr-venv/bin/oxr"),
+ dfine_python=source.get("DFINE_PYTHON", "/opt/dfine-venv/bin/python"),
+ vllm_extra_args=vllm_extra_args,
+ )
+
+ @property
+ def dfine_url(self) -> str:
+ return f"http://127.0.0.1:{self.dfine_port}"
+
+ @property
+ def vllm_url(self) -> str:
+ return f"http://127.0.0.1:{self.vllm_port}/v1"
+
+ @property
+ def api_url(self) -> str:
+ return f"http://127.0.0.1:{self.api_port}"
+
+ def dfine_command(self) -> list[str]:
+ return [
+ self.dfine_python,
+ "-m",
+ "uvicorn",
+ "dfine_la.api:app",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(self.dfine_port),
+ "--workers",
+ "1",
+ ]
+
+ def vllm_command(self) -> list[str]:
+ return [
+ self.vllm_python,
+ "-m",
+ "vllm.entrypoints.cli.main",
+ "serve",
+ self.model_name,
+ "--served-model-name",
+ self.served_model_name,
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(self.vllm_port),
+ "--gpu-memory-utilization",
+ str(self.gpu_memory_utilization),
+ "--max-model-len",
+ str(self.max_model_len),
+ "--trust-remote-code",
+ "--chat-template",
+ str(Path(self.model_name) / "chat_template.jinja"),
+ "--dtype",
+ "bfloat16",
+ "--attention-config",
+ '{"backend":"TRITON_ATTN"}',
+ "--max-num-seqs",
+ "16",
+ *self.vllm_extra_args,
+ ]
+
+ def api_command(self) -> list[str]:
+ return [
+ self.oxr_bin,
+ "serve",
+ "--host",
+ self.api_host,
+ "--port",
+ str(self.api_port),
+ "--workers",
+ "1",
+ "--layout-analyze-model-url",
+ self.dfine_url,
+ "--oxr-model-url",
+ self.vllm_url,
+ "--oxr-model-name",
+ self.served_model_name,
+ ]
+
+ def dfine_env(self, base: Mapping[str, str] | None = None) -> dict[str, str]:
+ env = dict(os.environ if base is None else base)
+ env["MODEL_PATH"] = self.dfine_model_path
+ env["MODEL_METADATA_PATH"] = env.get("DFINE_MODEL_METADATA_PATH") or str(
+ Path(self.dfine_model_path).with_name("metadata.json")
+ )
+ env["PORT"] = str(self.dfine_port)
+ dfine_root = str(APP_ROOT / "services" / "layout_analyze")
+ existing_pythonpath = env.get("PYTHONPATH", "")
+ env["PYTHONPATH"] = (
+ f"{dfine_root}{os.pathsep}{existing_pythonpath}"
+ if existing_pythonpath
+ else dfine_root
+ )
+ return env
+
+ def vllm_env(self, base: Mapping[str, str] | None = None) -> dict[str, str]:
+ env = dict(os.environ if base is None else base)
+ env["VLLM_PLUGINS"] = "oxr"
+ return env
+
+ def api_env(self, base: Mapping[str, str] | None = None) -> dict[str, str]:
+ env = dict(os.environ if base is None else base)
+ env["OXR__LAYOUT_ANALYZE_MODEL__URL"] = self.dfine_url
+ env["OXR__OXR_MODEL__URL"] = self.vllm_url
+ env["OXR__OXR_MODEL__MODEL_NAME"] = self.served_model_name
+ return env
+
+
+@dataclass
+class ManagedProcess:
+ name: str
+ process: asyncio.subprocess.Process
+
+
+async def _start_process(
+ name: str,
+ command: Sequence[str],
+ env: Mapping[str, str] | None = None,
+) -> ManagedProcess:
+ LOGGER.info("starting %s", name)
+ process = await asyncio.create_subprocess_exec(
+ *command,
+ env=None if env is None else dict(env),
+ start_new_session=True,
+ )
+ return ManagedProcess(name=name, process=process)
+
+
+def _assert_processes_running(processes: Sequence[ManagedProcess]) -> None:
+ for managed in processes:
+ return_code = managed.process.returncode
+ if return_code is not None:
+ raise RuntimeError(f"{managed.name} exited during startup with code {return_code}")
+
+
+def _validate_response(
+ name: str, response: httpx.Response, served_model_name: str = "oxr",
+) -> None:
+ """A reachable endpoint is not necessarily the expected ready service."""
+ response.raise_for_status()
+ if name == "D-FINE":
+ payload = response.json()
+ if not isinstance(payload, dict) or payload.get("status") != "healthy":
+ raise ValueError("D-FINE did not report healthy status")
+ elif name == "vLLM":
+ payload = response.json()
+ models = payload.get("data") if isinstance(payload, dict) else None
+ if not isinstance(models, list) or not any(
+ isinstance(model, dict) and model.get("id") == served_model_name
+ for model in models
+ ):
+ raise ValueError("vLLM did not advertise the expected model ID")
+
+
+async def _wait_for_http(
+ client: httpx.AsyncClient,
+ name: str,
+ url: str,
+ processes: Sequence[ManagedProcess],
+ stop_requested: asyncio.Event,
+ timeout: int,
+ served_model_name: str = "oxr",
+) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout
+ last_error = "no response"
+ while asyncio.get_running_loop().time() < deadline:
+ _assert_processes_running(processes)
+ if stop_requested.is_set():
+ raise InterruptedError("shutdown requested during startup")
+ try:
+ response = await client.get(url)
+ _validate_response(name, response, served_model_name)
+ _assert_processes_running(processes)
+ if stop_requested.is_set():
+ raise InterruptedError("shutdown requested during startup")
+ LOGGER.info("%s is ready at %s", name, url)
+ return
+ except (httpx.HTTPError, OSError, ValueError) as exc:
+ last_error = str(exc)
+ try:
+ await asyncio.wait_for(stop_requested.wait(), timeout=1.0)
+ except asyncio.TimeoutError:
+ pass
+ raise TimeoutError(f"{name} did not become ready at {url}: {last_error}")
+
+
+async def _shutdown_processes(
+ processes: Sequence[ManagedProcess],
+ timeout: int,
+) -> None:
+ # A dead service leader can leave workers in its process group (and on GPU).
+ # Do not filter groups by the leader's return code.
+ for managed in reversed(processes):
+ LOGGER.info("stopping %s", managed.name)
+ try:
+ os.killpg(managed.process.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+
+ deadline = asyncio.get_running_loop().time() + timeout
+ remaining = list(processes)
+ while remaining and asyncio.get_running_loop().time() < deadline:
+ alive = []
+ for managed in remaining:
+ try:
+ os.killpg(managed.process.pid, 0)
+ except ProcessLookupError:
+ continue
+ alive.append(managed)
+ remaining = alive
+ if remaining:
+ await asyncio.sleep(0.05)
+ for managed in remaining:
+ LOGGER.warning("killing %s process group after shutdown timeout", managed.name)
+ try:
+ os.killpg(managed.process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ await asyncio.gather(*(item.process.wait() for item in processes))
+
+
+def _install_signal_handlers(stop_requested: asyncio.Event) -> None:
+ loop = asyncio.get_running_loop()
+ for signum in (signal.SIGINT, signal.SIGTERM):
+ loop.add_signal_handler(signum, stop_requested.set)
+
+
+def _validate_model_repository(config: AllInOneConfig) -> Path:
+ root = Path(config.model_name)
+ files = [
+ root / name for name in (
+ "config.json", "model.safetensors", "tokenizer.json", "chat_template.jinja",
+ "plugins/vllm/pyproject.toml",
+ )
+ ]
+ files.extend([
+ Path(config.dfine_model_path),
+ Path(config.dfine_env()["MODEL_METADATA_PATH"]),
+ ])
+ for path in files:
+ if not path.is_file() or path.stat().st_size == 0:
+ raise ValueError(f"Missing model repository file: {path}")
+ with path.open("rb") as handle:
+ if handle.read(128).startswith(b"version https://git-lfs.github.com/spec/v1"):
+ raise ValueError(f"Unresolved Git LFS pointer; run git lfs pull: {path}")
+ return root / "plugins" / "vllm"
+
+
+async def _prepare_plugin(
+ config: AllInOneConfig, processes: list[ManagedProcess], stop_requested: asyncio.Event,
+) -> None:
+ plugin = _validate_model_repository(config)
+
+ async def run_checked(name: str, command: Sequence[str]) -> None:
+ managed = await _start_process(name, command, config.vllm_env())
+ processes.append(managed)
+ task = asyncio.create_task(managed.process.wait())
+ stop_task = asyncio.create_task(stop_requested.wait())
+ try:
+ done, _ = await asyncio.wait(
+ [task, stop_task], timeout=config.startup_timeout,
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ if stop_task in done:
+ raise InterruptedError("shutdown requested during plugin preparation")
+ if task not in done:
+ raise TimeoutError(f"{name} timed out")
+ if task.result() != 0:
+ raise RuntimeError(f"{name} failed with code {task.result()}")
+ await _shutdown_processes([managed], 0)
+ processes.remove(managed)
+ finally:
+ for pending in (task, stop_task):
+ if not pending.done():
+ pending.cancel()
+ await asyncio.gather(task, stop_task, return_exceptions=True)
+
+ # Refuse a different runtime; installing the model plugin must not upgrade or
+ # downgrade the benchmark's vLLM/PyTorch/Transformers environment.
+ await run_checked("runtime version check", [config.vllm_python, "-c", (
+ "from importlib.metadata import version; "
+ "expected={'vllm':'0.25.1','torch':'2.11.0+cu130','transformers':'5.13.1'}; "
+ "actual={key:version(key) for key in expected}; "
+ "\nif actual != expected: raise SystemExit('Unsupported model runtime: '+str(actual))"
+ )])
+ # Stage only the small plugin package. pip/setuptools must not write into
+ # the read-only model repository or copy model weights into the image.
+ with tempfile.TemporaryDirectory(prefix="oxr-plugin-") as temporary:
+ staged = Path(temporary) / "plugin"
+ shutil.copytree(plugin, staged, ignore=shutil.ignore_patterns(
+ "__pycache__", "*.pyc", "*.egg-info", "build", "dist",
+ ))
+ await run_checked("OXR plugin installation", [
+ config.vllm_python, "-m", "pip", "install", "--no-deps",
+ "--no-build-isolation", str(staged),
+ ])
+
+
+async def _run(config: AllInOneConfig) -> int:
+ stop_requested = asyncio.Event()
+ _install_signal_handlers(stop_requested)
+ processes: list[ManagedProcess] = []
+
+ try:
+ await _prepare_plugin(config, processes, stop_requested)
+ async with httpx.AsyncClient(timeout=3.0, trust_env=False) as client:
+ dfine = await _start_process(
+ "D-FINE",
+ config.dfine_command(),
+ config.dfine_env(),
+ )
+ processes.append(dfine)
+ await _wait_for_http(
+ client,
+ "D-FINE",
+ f"{config.dfine_url}/health",
+ processes,
+ stop_requested,
+ config.startup_timeout,
+ )
+
+ vllm = await _start_process("vLLM", config.vllm_command(), config.vllm_env())
+ processes.append(vllm)
+ await _wait_for_http(
+ client,
+ "vLLM",
+ f"{config.vllm_url}/models",
+ processes,
+ stop_requested,
+ config.startup_timeout,
+ config.served_model_name,
+ )
+
+ api = await _start_process("OXR API", config.api_command(), config.api_env())
+ processes.append(api)
+ await _wait_for_http(
+ client,
+ "OXR API",
+ f"{config.api_url}/docs",
+ processes,
+ stop_requested,
+ config.startup_timeout,
+ )
+
+ LOGGER.info(
+ "all services are ready; OXR API is listening on %s:%s",
+ config.api_host,
+ config.api_port,
+ )
+ wait_tasks = {
+ asyncio.create_task(item.process.wait()): item
+ for item in processes
+ }
+ stop_task = asyncio.create_task(stop_requested.wait())
+ done, pending = await asyncio.wait(
+ [*wait_tasks, stop_task],
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ for task in pending:
+ task.cancel()
+ await asyncio.gather(*pending, return_exceptions=True)
+
+ if stop_task in done:
+ return 0
+
+ exited_task = next(task for task in done if task in wait_tasks)
+ exited = wait_tasks[exited_task]
+ return_code = exited_task.result()
+ LOGGER.error("%s exited unexpectedly with code %s", exited.name, return_code)
+ return return_code if return_code != 0 else 1
+ except (InterruptedError, KeyboardInterrupt):
+ return 0
+ except Exception:
+ LOGGER.exception("all-in-one startup failed")
+ return 1
+ finally:
+ await _shutdown_processes(processes, config.shutdown_timeout)
+
+
+async def _healthcheck(config: AllInOneConfig) -> int:
+ checks = (
+ ("D-FINE", f"{config.dfine_url}/health"),
+ ("vLLM", f"{config.vllm_url}/models"),
+ ("OXR API", f"{config.api_url}/docs"),
+ )
+ async with httpx.AsyncClient(timeout=3.0, trust_env=False) as client:
+ for name, url in checks:
+ try:
+ response = await client.get(url)
+ _validate_response(name, response, config.served_model_name)
+ except (httpx.HTTPError, OSError, ValueError) as exc:
+ LOGGER.error("%s healthcheck failed at %s: %s", name, url, exc)
+ return 1
+ return 0
+
+
+def _parse_args(argv: Sequence[str]) -> argparse.Namespace:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--healthcheck", action="store_true")
+ return parser.parse_args(argv)
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ logging.basicConfig(
+ level=os.getenv("LOG_LEVEL", "INFO").upper(),
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
+ )
+ args = _parse_args(sys.argv[1:] if argv is None else argv)
+ try:
+ config = AllInOneConfig.from_env()
+ except ValueError as exc:
+ LOGGER.error("invalid all-in-one configuration: %s", exc)
+ return 2
+ if args.healthcheck:
+ return asyncio.run(_healthcheck(config))
+ return asyncio.run(_run(config))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/docker/requirements.allinone.txt b/docker/requirements.allinone.txt
new file mode 100644
index 0000000..f1d70d7
--- /dev/null
+++ b/docker/requirements.allinone.txt
@@ -0,0 +1,13 @@
+# API-side dependencies; model runtime remains isolated and fixed by the base.
+fastapi==0.136.1
+httpx==0.28.1
+numpy==1.26.4
+openai==2.32.0
+opencv-python==4.11.0.86
+pydantic==2.11.10
+pydantic-settings==2.14.0
+python-multipart==0.0.26
+PyYAML==6.0.3
+sopdf==0.2.0
+typer==0.24.1
+uvicorn==0.46.0
diff --git a/oxr/__init__.py b/oxr/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/oxr/cli/__init__.py b/oxr/cli/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/oxr/cli/cmd_serve.py b/oxr/cli/cmd_serve.py
new file mode 100644
index 0000000..27cab33
--- /dev/null
+++ b/oxr/cli/cmd_serve.py
@@ -0,0 +1,199 @@
+import os
+from typing import Optional
+
+import typer
+import uvicorn
+
+
+LEGACY_OPTION_MIGRATIONS = {
+ "--model-url": "--oxr-model-url",
+ "--model-name": "--oxr-model-name",
+ "--max-tokens": "--oxr-model-max-tokens",
+ "--layout-batch-size": "--layout-analyze-model-batch-size",
+ "--max-layout-concurrency": "--layout-analyze-model-max-concurrency",
+ "--max-recognition-concurrency": "--oxr-model-max-concurrency",
+}
+
+
+def _ensure_supported_workers(workers: int) -> None:
+ if workers != 1:
+ raise typer.BadParameter(
+ "Only --workers 1 is supported because async task state is stored in process memory.",
+ param_hint="--workers",
+ )
+
+
+def _reject_legacy_options(options: dict[str, object]) -> None:
+ for legacy_option, value in options.items():
+ if value is not None:
+ replacement = LEGACY_OPTION_MIGRATIONS[legacy_option]
+ raise typer.BadParameter(
+ f"{legacy_option} is no longer supported; use {replacement}.",
+ param_hint=legacy_option,
+ )
+
+
+def serve(
+ config: Optional[str] = typer.Option(None, "--config", help="Path to config.yaml"),
+ full_overlap_dedupe: Optional[bool] = typer.Option(
+ None,
+ "--full-overlap-dedupe/--no-full-overlap-dedupe",
+ help="Across all categories, keep outer boxes and suppress any overlap by confidence.",
+ ),
+ table_image_placeholders: Optional[bool] = typer.Option(
+ None, "--table-image-placeholders/--no-table-image-placeholders",
+ help="Restore pictures inside tables with numbered TIT placeholders.",
+ ),
+ table_image_min_score: Optional[float] = typer.Option(
+ None, "--table-image-min-score", help="Minimum LA confidence for table pictures.",
+ ),
+ host: Optional[str] = typer.Option(None, "--host"),
+ port: Optional[int] = typer.Option(None, "--port"),
+ layout_analyze_model_url: Optional[str] = typer.Option(None, "--layout-analyze-model-url"),
+ layout_analyze_model_batch_size: Optional[int] = typer.Option(None, "--layout-analyze-model-batch-size"),
+ layout_analyze_model_max_concurrency: Optional[int] = typer.Option(None, "--layout-analyze-model-max-concurrency"),
+ layout_analyze_model_timeout: Optional[int] = typer.Option(None, "--layout-analyze-model-timeout"),
+ layout_analyze_model_retry_times: Optional[int] = typer.Option(None, "--layout-analyze-model-retry-times"),
+ layout_analyze_model_score_threshold: Optional[float] = typer.Option(
+ None,
+ "--layout-analyze-model-score-threshold",
+ ),
+ layout_analyze_model_nms_iou_threshold: Optional[float] = typer.Option(
+ None,
+ "--layout-analyze-model-nms-iou-threshold",
+ ),
+ layout_analyze_model_provides_reading_order: Optional[bool] = typer.Option(
+ None,
+ "--layout-analyze-model-provides-reading-order/--no-layout-analyze-model-provides-reading-order",
+ ),
+ oxr_model_url: Optional[str] = typer.Option(None, "--oxr-model-url"),
+ oxr_model_name: Optional[str] = typer.Option(None, "--oxr-model-name"),
+ oxr_model_max_tokens: Optional[int] = typer.Option(None, "--oxr-model-max-tokens"),
+ oxr_model_max_concurrency: Optional[int] = typer.Option(None, "--oxr-model-max-concurrency"),
+ oxr_model_timeout: Optional[int] = typer.Option(None, "--oxr-model-timeout"),
+ oxr_model_retry_times: Optional[int] = typer.Option(None, "--oxr-model-retry-times"),
+ legacy_model_url: Optional[str] = typer.Option(None, "--model-url", hidden=True),
+ legacy_model_name: Optional[str] = typer.Option(None, "--model-name", hidden=True),
+ legacy_max_tokens: Optional[str] = typer.Option(None, "--max-tokens", hidden=True),
+ legacy_layout_batch_size: Optional[str] = typer.Option(
+ None,
+ "--layout-batch-size",
+ hidden=True,
+ ),
+ legacy_max_layout_concurrency: Optional[str] = typer.Option(
+ None,
+ "--max-layout-concurrency",
+ hidden=True,
+ ),
+ legacy_max_recognition_concurrency: Optional[str] = typer.Option(
+ None,
+ "--max-recognition-concurrency",
+ hidden=True,
+ ),
+ workers: Optional[int] = typer.Option(None, "--workers"),
+):
+ _reject_legacy_options(
+ {
+ "--model-url": legacy_model_url,
+ "--model-name": legacy_model_name,
+ "--max-tokens": legacy_max_tokens,
+ "--layout-batch-size": legacy_layout_batch_size,
+ "--max-layout-concurrency": legacy_max_layout_concurrency,
+ "--max-recognition-concurrency": legacy_max_recognition_concurrency,
+ }
+ )
+
+ from oxr.config.settings import Settings, settings
+
+ if config:
+ loaded = Settings.load_from_yaml(config)
+ settings.server = loaded.server
+ settings.layout_analyze_model = loaded.layout_analyze_model
+ settings.oxr_model = loaded.oxr_model
+ settings.pipeline = loaded.pipeline
+
+ if host is not None:
+ settings.server.host = host
+ if full_overlap_dedupe is not None:
+ settings.pipeline.full_overlap_dedupe = full_overlap_dedupe
+ if table_image_placeholders is not None:
+ settings.pipeline.table_image_placeholders = table_image_placeholders
+ if table_image_min_score is not None:
+ settings.pipeline.table_image_min_score = table_image_min_score
+ if port is not None:
+ settings.server.port = port
+ if workers is not None:
+ settings.server.workers = workers
+
+ layout = settings.layout_analyze_model
+ if layout_analyze_model_url is not None:
+ layout.url = layout_analyze_model_url
+ if layout_analyze_model_batch_size is not None:
+ layout.batch_size = layout_analyze_model_batch_size
+ if layout_analyze_model_max_concurrency is not None:
+ layout.max_concurrency = layout_analyze_model_max_concurrency
+ if layout_analyze_model_timeout is not None:
+ layout.timeout = layout_analyze_model_timeout
+ if layout_analyze_model_retry_times is not None:
+ layout.retry_times = layout_analyze_model_retry_times
+ if layout_analyze_model_score_threshold is not None:
+ layout.score_threshold = layout_analyze_model_score_threshold
+ if layout_analyze_model_nms_iou_threshold is not None:
+ layout.nms_iou_threshold = layout_analyze_model_nms_iou_threshold
+ if layout_analyze_model_provides_reading_order is not None:
+ layout.provides_reading_order = layout_analyze_model_provides_reading_order
+
+ oxr = settings.oxr_model
+ if oxr_model_url is not None:
+ oxr.url = oxr_model_url
+ if oxr_model_name is not None:
+ oxr.model_name = oxr_model_name
+ if oxr_model_max_tokens is not None:
+ oxr.max_tokens = oxr_model_max_tokens
+ if oxr_model_max_concurrency is not None:
+ oxr.max_concurrency = oxr_model_max_concurrency
+ if oxr_model_timeout is not None:
+ oxr.timeout = oxr_model_timeout
+ if oxr_model_retry_times is not None:
+ oxr.retry_times = oxr_model_retry_times
+
+ _ensure_supported_workers(settings.server.workers)
+ settings.validate_for_server()
+
+ os.environ["OXR__SERVER__HOST"] = str(settings.server.host)
+ os.environ["OXR__PIPELINE__FULL_OVERLAP_DEDUPE"] = str(
+ settings.pipeline.full_overlap_dedupe
+ ).lower()
+ os.environ["OXR__PIPELINE__TABLE_IMAGE_PLACEHOLDERS"] = str(
+ settings.pipeline.table_image_placeholders
+ ).lower()
+ os.environ["OXR__PIPELINE__TABLE_IMAGE_MIN_SCORE"] = str(settings.pipeline.table_image_min_score)
+ os.environ["OXR__SERVER__PORT"] = str(settings.server.port)
+ os.environ["OXR__SERVER__WORKERS"] = str(settings.server.workers)
+ os.environ["OXR__LAYOUT_ANALYZE_MODEL__URL"] = str(layout.url)
+ os.environ["OXR__LAYOUT_ANALYZE_MODEL__BATCH_SIZE"] = str(layout.batch_size)
+ os.environ["OXR__LAYOUT_ANALYZE_MODEL__MAX_CONCURRENCY"] = str(layout.max_concurrency)
+ os.environ["OXR__LAYOUT_ANALYZE_MODEL__TIMEOUT"] = str(layout.timeout)
+ os.environ["OXR__LAYOUT_ANALYZE_MODEL__RETRY_TIMES"] = str(layout.retry_times)
+ os.environ["OXR__LAYOUT_ANALYZE_MODEL__SCORE_THRESHOLD"] = str(layout.score_threshold)
+ if layout.nms_iou_threshold is None:
+ os.environ.pop("OXR__LAYOUT_ANALYZE_MODEL__NMS_IOU_THRESHOLD", None)
+ else:
+ os.environ["OXR__LAYOUT_ANALYZE_MODEL__NMS_IOU_THRESHOLD"] = str(
+ layout.nms_iou_threshold
+ )
+ os.environ["OXR__LAYOUT_ANALYZE_MODEL__PROVIDES_READING_ORDER"] = str(layout.provides_reading_order).lower()
+ os.environ["OXR__OXR_MODEL__URL"] = str(oxr.url)
+ os.environ["OXR__OXR_MODEL__MODEL_NAME"] = oxr.model_name
+ os.environ["OXR__OXR_MODEL__MAX_TOKENS"] = str(oxr.max_tokens)
+ os.environ["OXR__OXR_MODEL__MAX_CONCURRENCY"] = str(oxr.max_concurrency)
+ os.environ["OXR__OXR_MODEL__TIMEOUT"] = str(oxr.timeout)
+ os.environ["OXR__OXR_MODEL__RETRY_TIMES"] = str(oxr.retry_times)
+
+ print(f"Starting OXR server at {settings.server.host}:{settings.server.port}")
+ uvicorn.run(
+ "oxr.server.app:app",
+ host=settings.server.host,
+ port=settings.server.port,
+ workers=settings.server.workers,
+ )
diff --git a/oxr/cli/main.py b/oxr/cli/main.py
new file mode 100644
index 0000000..d8be71e
--- /dev/null
+++ b/oxr/cli/main.py
@@ -0,0 +1,16 @@
+import typer
+from oxr.cli.cmd_serve import serve
+
+app = typer.Typer(help="OXR: Optical Everything Recognition")
+
+
+def main():
+ # Keep the explicit `serve` subcommand when it is the only command.
+ pass
+
+
+app.command(name="serve", help="Start the OXR server with its Online Demo at /demo")(serve)
+
+if __name__ == "__main__":
+ app()
diff --git a/oxr/config/__init__.py b/oxr/config/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/oxr/config/settings.py b/oxr/config/settings.py
new file mode 100644
index 0000000..4c1c176
--- /dev/null
+++ b/oxr/config/settings.py
@@ -0,0 +1,123 @@
+import os
+from typing import Any, Optional
+from urllib.parse import urlparse
+
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+from pydantic_settings import BaseSettings, SettingsConfigDict
+import yaml
+
+
+def _parse_env_bool(value: Optional[str], default: bool = False) -> bool:
+ if value is None:
+ return default
+ return value.strip().lower() in {"true", "1", "yes", "on"}
+
+
+def _validate_http_url(value: Optional[str]) -> Optional[str]:
+ if value is None:
+ return value
+ parsed = urlparse(value)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ raise ValueError("must be an absolute http:// or https:// URL")
+ return value
+
+
+class ServerConfig(BaseModel):
+ model_config = ConfigDict(validate_assignment=True)
+
+ host: str = "0.0.0.0"
+ port: int = Field(default=8000, gt=0, le=65535)
+ workers: int = Field(default=1, gt=0)
+
+
+class LayoutAnalyzeModelConfig(BaseModel):
+ model_config = ConfigDict(validate_assignment=True)
+
+ url: Optional[str] = None
+ batch_size: int = Field(default=8, gt=0)
+ max_concurrency: int = Field(default=2, gt=0)
+ timeout: int = Field(default=60, gt=0)
+ retry_times: int = Field(default=2, gt=0)
+ score_threshold: float = Field(default=0.5, ge=0.0, le=1.0)
+ nms_iou_threshold: Optional[float] = Field(default=0.6, ge=0.0, le=1.0)
+ provides_reading_order: bool = False
+
+ _validate_url = field_validator("url")(_validate_http_url)
+
+
+class OXRModelConfig(BaseModel):
+ model_config = ConfigDict(validate_assignment=True)
+
+ url: Optional[str] = None
+ model_name: str = "oxr"
+ max_tokens: int = Field(default=8192, gt=0)
+ max_concurrency: int = Field(default=16, gt=0)
+ timeout: int = Field(default=120, gt=0)
+ retry_times: int = Field(default=2, gt=0)
+
+ _validate_url = field_validator("url")(_validate_http_url)
+
+
+class PipelineConfig(BaseModel):
+ model_config = ConfigDict(validate_assignment=True, extra="forbid")
+
+ image_output_dir: str = "outputs"
+ full_overlap_dedupe: bool = False
+ table_image_placeholders: bool = False
+ table_image_min_score: float = Field(default=0.5, ge=0.0, le=1.0)
+
+
+class Settings(BaseSettings):
+ debug: bool = Field(default_factory=lambda: _parse_env_bool(os.getenv("DEBUG"), False))
+ server: ServerConfig = Field(default_factory=ServerConfig)
+ layout_analyze_model: LayoutAnalyzeModelConfig = Field(default_factory=LayoutAnalyzeModelConfig)
+ oxr_model: OXRModelConfig = Field(default_factory=OXRModelConfig)
+ pipeline: PipelineConfig = Field(default_factory=PipelineConfig)
+
+ model_config = SettingsConfigDict(
+ env_prefix="OXR__",
+ env_nested_delimiter="__",
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def reject_legacy_model_configuration(cls, data: Any) -> Any:
+ if isinstance(data, dict) and "model" in data:
+ raise ValueError(
+ "The legacy 'model' configuration is no longer supported; "
+ "migrate it to 'layout_analyze_model' and 'oxr_model'."
+ )
+
+ legacy_environment = sorted(
+ name
+ for name in os.environ
+ if name.upper().startswith("OXR_MODEL__") or name.upper().startswith("OXR__MODEL__")
+ )
+ if legacy_environment:
+ raise ValueError(
+ "legacy model configuration environment variables are not supported "
+ f"({', '.join(legacy_environment)}); migrate to "
+ "OXR__LAYOUT_ANALYZE_MODEL__* and OXR__OXR_MODEL__*."
+ )
+ return data
+
+ def validate_for_server(self) -> None:
+ missing = []
+ if not self.layout_analyze_model.url:
+ missing.append("layout_analyze_model.url")
+ if not self.oxr_model.url:
+ missing.append("oxr_model.url")
+ if missing:
+ raise ValueError(
+ "Both model URLs are required to start the server: " + ", ".join(missing)
+ )
+
+ @classmethod
+ def load_from_yaml(cls, yaml_path: str) -> "Settings":
+ with open(yaml_path, "r", encoding="utf-8") as f:
+ data = yaml.safe_load(f) or {}
+ return cls(**data)
+
+
+settings = Settings()
diff --git a/oxr/model/__init__.py b/oxr/model/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/oxr/model/client.py b/oxr/model/client.py
new file mode 100644
index 0000000..31df2f8
--- /dev/null
+++ b/oxr/model/client.py
@@ -0,0 +1,242 @@
+import asyncio
+import base64
+import logging
+from typing import Any, Dict, Optional
+
+import cv2
+import numpy as np
+from openai import AsyncOpenAI, DefaultAsyncHttpxClient
+
+from oxr.config.settings import OXRModelConfig, settings
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_MODEL_OPTIONS = {
+ "temperature": 0.0,
+ "top_p": 1.0,
+ "repetition_penalty": 1.0,
+}
+
+
+class ModelOutput(str):
+ """String-compatible model output with completion metadata attached."""
+
+ finish_reason: str
+ usage: Any
+
+ def __new__(
+ cls,
+ content: str,
+ *,
+ finish_reason: str = "unknown",
+ usage: Any = None,
+ ) -> "ModelOutput":
+ instance = super().__new__(cls, content)
+ instance.finish_reason = finish_reason
+ instance.usage = usage
+ return instance
+
+
+def resolve_model_options(model_options: Optional[Dict[str, Any]] = None) -> Dict[str, float]:
+ resolved = dict(DEFAULT_MODEL_OPTIONS)
+ if model_options:
+ resolved.update({
+ key: float(value)
+ for key, value in model_options.items()
+ if key in resolved and value is not None
+ })
+ return resolved
+
+
+class OXRModelClient:
+ """Persistent OpenAI-compatible client used only for OXR requests."""
+
+ def __init__(self, config: Optional[OXRModelConfig] = None):
+ self._config = config
+ self._client: Optional[AsyncOpenAI] = None
+ self._request_loop: Optional[asyncio.AbstractEventLoop] = None
+ self._request_limit: Optional[int] = None
+ self._request_semaphore: Optional[asyncio.Semaphore] = None
+
+ @property
+ def config(self) -> OXRModelConfig:
+ return self._config or settings.oxr_model
+
+ @property
+ def client(self) -> Optional[AsyncOpenAI]:
+ if self._client is None and self.config.url:
+ self._client = AsyncOpenAI(
+ base_url=self.config.url,
+ api_key="EMPTY",
+ max_retries=0,
+ http_client=DefaultAsyncHttpxClient(trust_env=False),
+ )
+ return self._client
+
+ def get_request_semaphore(self) -> asyncio.Semaphore:
+ """Return the process client's shared limiter for the current event loop."""
+ loop = asyncio.get_running_loop()
+ limit = self.config.max_concurrency
+ if (
+ self._request_loop is not loop
+ or self._request_limit != limit
+ or self._request_semaphore is None
+ ):
+ self._request_loop = loop
+ self._request_limit = limit
+ self._request_semaphore = asyncio.Semaphore(limit)
+ assert self._request_semaphore is not None
+ return self._request_semaphore
+
+ async def aclose(self) -> None:
+ try:
+ if self._client is not None:
+ await self._client.close()
+ finally:
+ self._client = None
+ self._request_loop = None
+ self._request_limit = None
+ self._request_semaphore = None
+
+ def _encode_image(self, image: np.ndarray) -> str:
+ success, buffer = cv2.imencode(".png", image)
+ if not success:
+ raise ValueError("Unable to encode image as PNG.")
+ return base64.b64encode(buffer).decode("utf-8")
+
+ def _image_to_data_url(self, image: np.ndarray) -> str:
+ return f"data:image/png;base64,{self._encode_image(image)}"
+
+ async def _call_vision_model(
+ self,
+ prompt: str,
+ image: np.ndarray,
+ timeout: int,
+ model_options: Optional[Dict[str, Any]] = None,
+ max_tokens: Optional[int] = None,
+ ) -> str:
+ if not self.client:
+ raise RuntimeError("OXR model URL is not configured.")
+ if image is None:
+ raise ValueError("An image is required for vision model calls.")
+
+ content = [
+ {
+ "type": "image_url",
+ "image_url": {"url": self._image_to_data_url(image)},
+ },
+ {"type": "text", "text": prompt},
+ ]
+ resolved_options = resolve_model_options(model_options)
+
+ response = await asyncio.wait_for(
+ self.client.chat.completions.create(
+ model=self.config.model_name,
+ messages=[{"role": "user", "content": content}],
+ timeout=timeout,
+ temperature=resolved_options["temperature"],
+ top_p=resolved_options["top_p"],
+ max_tokens=max_tokens if max_tokens is not None else self.config.max_tokens,
+ extra_body={
+ "repetition_penalty": resolved_options["repetition_penalty"],
+ },
+ ),
+ timeout=timeout,
+ )
+ choice = response.choices[0]
+ return ModelOutput(
+ choice.message.content or "",
+ finish_reason=getattr(choice, "finish_reason", None) or "unknown",
+ usage=getattr(response, "usage", None),
+ )
+
+ async def request_reading_order(
+ self,
+ prompt: str,
+ image: np.ndarray,
+ max_tokens: int,
+ ) -> str:
+ """Submit a deterministic OXR reading-order request with a prepared prompt."""
+ return await self._call_vision_model(
+ prompt=prompt,
+ image=image,
+ timeout=self.config.timeout,
+ model_options=None,
+ max_tokens=max_tokens,
+ )
+
+ async def recognize_text(self, image: np.ndarray, model_options: Optional[Dict[str, Any]] = None) -> str:
+ from oxr.model.prompts import PROMPT_TEXT_RECOGNITION
+ return await self._call_vision_model(
+ prompt=PROMPT_TEXT_RECOGNITION,
+ image=image,
+ timeout=self.config.timeout,
+ model_options=model_options,
+ )
+
+ async def recognize_formula(self, image: np.ndarray, model_options: Optional[Dict[str, Any]] = None) -> str:
+ from oxr.model.prompts import PROMPT_FORMULA_RECOGNITION
+ return await self._call_vision_model(
+ prompt=PROMPT_FORMULA_RECOGNITION,
+ image=image,
+ timeout=self.config.timeout,
+ model_options=model_options,
+ )
+
+ async def recognize_table(self, image: np.ndarray, model_options: Optional[Dict[str, Any]] = None) -> str:
+ from oxr.model.prompts import PROMPT_TABLE_RECOGNITION
+ return await self._call_vision_model(
+ prompt=PROMPT_TABLE_RECOGNITION,
+ image=image,
+ timeout=self.config.timeout,
+ model_options=model_options,
+ )
+
+ async def recognize_code(self, image: np.ndarray, model_options: Optional[Dict[str, Any]] = None) -> str:
+ from oxr.model.prompts import PROMPT_CODE_RECOGNITION
+ return await self._call_vision_model(
+ prompt=PROMPT_CODE_RECOGNITION,
+ image=image,
+ timeout=self.config.timeout,
+ model_options=model_options,
+ )
+
+ async def analyze_layout(self, image: np.ndarray, model_options: Optional[Dict[str, Any]] = None) -> str:
+ """Run the diagnostic OXR layout prompt outside the document pipeline."""
+ from oxr.model.prompts import PROMPT_LAYOUT_ANALYSIS
+ return await self._call_vision_model(
+ prompt=PROMPT_LAYOUT_ANALYSIS,
+ image=image,
+ timeout=self.config.timeout,
+ model_options=model_options,
+ )
+
+ async def recognize_whole_page(
+ self,
+ image: np.ndarray,
+ model_options: Optional[Dict[str, Any]] = None,
+ ) -> str:
+ from oxr.model.prompts import PROMPT_WHOLE_PAGE_RECOGNITION
+ return await self._call_vision_model(
+ prompt=PROMPT_WHOLE_PAGE_RECOGNITION,
+ image=image,
+ timeout=self.config.timeout,
+ model_options=model_options,
+ )
+
+ async def recognize_chemical_structure(
+ self,
+ image: np.ndarray,
+ model_options: Optional[Dict[str, Any]] = None,
+ ) -> str:
+ from oxr.model.prompts import PROMPT_CHEMICAL_STRUCTURE_RECOGNITION
+ return await self._call_vision_model(
+ prompt=PROMPT_CHEMICAL_STRUCTURE_RECOGNITION,
+ image=image,
+ timeout=self.config.timeout,
+ model_options=model_options,
+ )
+
+
+ModelClient = OXRModelClient
+model_client = OXRModelClient()
diff --git a/oxr/model/layout_client.py b/oxr/model/layout_client.py
new file mode 100644
index 0000000..a03337e
--- /dev/null
+++ b/oxr/model/layout_client.py
@@ -0,0 +1,62 @@
+from typing import Optional, Sequence
+
+import cv2
+import httpx
+import numpy as np
+
+from oxr.config.settings import LayoutAnalyzeModelConfig, settings
+
+
+class LayoutAnalyzeClient:
+ """Persistent HTTP client for the D-FINE layout-analysis service."""
+
+ def __init__(
+ self,
+ config: Optional[LayoutAnalyzeModelConfig] = None,
+ *,
+ http_client: Optional[httpx.AsyncClient] = None,
+ ):
+ self._config = config
+ self._client = http_client
+
+ @property
+ def config(self) -> LayoutAnalyzeModelConfig:
+ return self._config or settings.layout_analyze_model
+
+ @property
+ def client(self) -> httpx.AsyncClient:
+ if self._client is None:
+ if not self.config.url:
+ raise RuntimeError("Layout analysis model URL is not configured.")
+ self._client = httpx.AsyncClient(base_url=self.config.url, trust_env=False)
+ return self._client
+
+ def encode_images(self, images: Sequence[np.ndarray]) -> list[bytes]:
+ encoded_images: list[bytes] = []
+ for image in images:
+ success, encoded = cv2.imencode(".png", image)
+ if not success:
+ raise ValueError("Unable to encode image as PNG.")
+ encoded_images.append(encoded.tobytes())
+ return encoded_images
+
+ async def request_batch(self, encoded_images: Sequence[bytes]) -> object:
+ files = [
+ ("images", (f"page-{index}.png", image, "application/octet-stream"))
+ for index, image in enumerate(encoded_images)
+ ]
+ base_url = str(self.config.url).rstrip("/")
+ if base_url.endswith("/v1/layout/analyze"):
+ base_url = base_url[: -len("/v1/layout/analyze")]
+ endpoint = base_url if base_url.endswith("/inference") else f"{base_url}/inference"
+ response = await self.client.post(endpoint, files=files, timeout=self.config.timeout)
+ response.raise_for_status()
+ return response.json()
+
+ async def aclose(self) -> None:
+ if self._client is not None:
+ await self._client.aclose()
+ self._client = None
+
+
+layout_client = LayoutAnalyzeClient()
diff --git a/oxr/model/prompts.py b/oxr/model/prompts.py
new file mode 100644
index 0000000..92aa1dd
--- /dev/null
+++ b/oxr/model/prompts.py
@@ -0,0 +1,98 @@
+import math
+from collections.abc import Mapping, Sequence
+from numbers import Real
+
+
+PROMPT_TEXT_RECOGNITION = """Recognize the content of the image."""
+
+PROMPT_FORMULA_RECOGNITION = """Recognize the formula of the image into KaTex format."""
+
+PROMPT_TABLE_RECOGNITION = """Recognize the table of the image into html format."""
+
+PROMPT_CODE_RECOGNITION = """Recognize the code of the image into markdown code format."""
+
+PROMPT_LAYOUT_ANALYSIS = """Detect the layout of the input image, layout categories include [Caption,Footnote,Formula,Text,Page-footer,Page-header,Picture,Title,Table,Stamp,Chemical Structure,Code Block]. Box format is [x1,y1,x2,y2] and output box with reading order."""
+
+PROMPT_WHOLE_PAGE_RECOGNITION = """Recognize the whole page content of the image."""
+
+PROMPT_CHEMICAL_STRUCTURE_RECOGNITION = """Recognize the chemical structure of the image into SMILES."""
+
+PROMPT_READING_ORDER = """
+Given the detected layout boxes below, output the reading order as a whitespace-separated permutation of 0-based box IDs only.
+
+Boxes:
+{boxes}
+
+Output only the box IDs."""
+
+
+def _validate_coordinate(value: object, *, field: str) -> float:
+ if isinstance(value, bool) or not isinstance(value, Real) or not math.isfinite(value):
+ raise ValueError(f"{field} must contain only finite numbers")
+ return float(value)
+
+
+def _format_bbox(
+ bbox: Sequence[object],
+ *,
+ bbox_type: str,
+ image_size: tuple[int, int],
+) -> str:
+ if len(bbox) != 4:
+ raise ValueError("each reading-order bbox must contain exactly four coordinates")
+
+ width, height = image_size
+ if width <= 0 or height <= 0:
+ raise ValueError("image dimensions must be positive")
+
+ if bbox_type == "real":
+ scale_x, scale_y = 1000 / width, 1000 / height
+ elif bbox_type == "norm1":
+ scale_x = scale_y = 1000
+ else:
+ raise ValueError("objects.bbox_type must be 'real' or 'norm1'")
+
+ coordinates = [
+ int(round(_validate_coordinate(value, field="objects.bbox") * scale))
+ for value, scale in zip(bbox, (scale_x, scale_y, scale_x, scale_y))
+ ]
+ return (
+ f"<|box_start|>({coordinates[0]},{coordinates[1]}),"
+ f"({coordinates[2]},{coordinates[3]})<|box_end|>"
+ )
+
+
+def build_reading_order_prompt(
+ objects: Mapping[str, object],
+ *,
+ image_size: tuple[int, int],
+) -> str:
+ """Render ms-swift grounding objects into the reading-order prompt."""
+ if not isinstance(objects, Mapping):
+ raise ValueError("reading_order requires an objects JSON object")
+
+ refs = objects.get("ref")
+ bboxes = objects.get("bbox")
+ if not isinstance(refs, Sequence) or isinstance(refs, (str, bytes)):
+ raise ValueError("objects.ref must be a list")
+ if not isinstance(bboxes, Sequence) or isinstance(bboxes, (str, bytes)):
+ raise ValueError("objects.bbox must be a list")
+ if len(refs) != len(bboxes):
+ raise ValueError("objects.ref and objects.bbox must have the same length")
+
+ bbox_type = objects.get("bbox_type") or "real"
+ if not isinstance(bbox_type, str):
+ raise ValueError("objects.bbox_type must be 'real' or 'norm1'")
+
+ lines = []
+ for index, (ref, bbox) in enumerate(zip(refs, bboxes)):
+ if not isinstance(ref, str):
+ raise ValueError("objects.ref must contain only strings")
+ if not isinstance(bbox, Sequence) or isinstance(bbox, (str, bytes)):
+ raise ValueError("objects.bbox must contain coordinate lists")
+ lines.append(
+ f"{index} | <|object_ref_start|>{ref}<|object_ref_end|> | "
+ f"{_format_bbox(bbox, bbox_type=bbox_type, image_size=image_size)}"
+ )
+
+ return PROMPT_READING_ORDER.format(boxes="\n".join(lines))
diff --git a/oxr/pipeline/__init__.py b/oxr/pipeline/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/oxr/pipeline/_vendor/__init__.py b/oxr/pipeline/_vendor/__init__.py
new file mode 100644
index 0000000..00b95d6
--- /dev/null
+++ b/oxr/pipeline/_vendor/__init__.py
@@ -0,0 +1 @@
+"""Pinned third-party algorithm implementations used by the OXR pipeline."""
diff --git a/oxr/pipeline/_vendor/xycut_plus_plus.py b/oxr/pipeline/_vendor/xycut_plus_plus.py
new file mode 100644
index 0000000..9b5a697
--- /dev/null
+++ b/oxr/pipeline/_vendor/xycut_plus_plus.py
@@ -0,0 +1,2088 @@
+# Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Vendored function closure from the XY-Cut++ authors' implementation.
+
+Paper authors: Shuai Liu, Youmeng Li, Jizeng Wei
+Paper: https://arxiv.org/abs/2504.10258
+Source repository: https://github.com/liushuai35/PaddleXrc
+Source commit: 7873ab38662e3277091520f4259f090bc197fee4
+Source path: paddlex/inference/pipelines/layout_parsing/utils.py
+Source SHA-256: 9681d0b80b7738a2e6febc163bb91cbc1c12275a0c3aa2621be6c91b37033189
+
+Only the transitive function closure needed by get_layout_ordering is vendored.
+
+OXR extension: get_layout_ordering accepts remove_overlaps=False so the
+order-only adapter can preserve every input block. The default retains the
+upstream overlap-removal behavior.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import numpy as np
+
+UPSTREAM_COMMIT = "7873ab38662e3277091520f4259f090bc197fee4"
+UPSTREAM_SOURCE_SHA256 = "9681d0b80b7738a2e6febc163bb91cbc1c12275a0c3aa2621be6c91b37033189"
+
+
+def _calculate_overlap_area_div_minbox_area_ratio(
+ bbox1: Union[list, tuple],
+ bbox2: Union[list, tuple],
+) -> float:
+ """
+ Calculate the ratio of the overlap area between bbox1 and bbox2
+ to the area of the smaller bounding box.
+
+ Args:
+ bbox1 (list or tuple): Coordinates of the first bounding box [x_min, y_min, x_max, y_max].
+ bbox2 (list or tuple): Coordinates of the second bounding box [x_min, y_min, x_max, y_max].
+
+ Returns:
+ float: The ratio of the overlap area to the area of the smaller bounding box.
+ """
+ bbox1 = list(map(int, bbox1))
+ bbox2 = list(map(int, bbox2))
+
+ x_left = max(bbox1[0], bbox2[0])
+ y_top = max(bbox1[1], bbox2[1])
+ x_right = min(bbox1[2], bbox2[2])
+ y_bottom = min(bbox1[3], bbox2[3])
+
+ if x_right <= x_left or y_bottom <= y_top:
+ return 0.0
+
+ intersection_area = (x_right - x_left) * (y_bottom - y_top)
+ area_bbox1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
+ area_bbox2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
+ min_box_area = min(area_bbox1, area_bbox2)
+
+ if min_box_area <= 0:
+ return 0.0
+
+ return intersection_area / min_box_area
+
+
+def _projection_by_bboxes(boxes: np.ndarray, axis: int) -> np.ndarray:
+ """
+ Generate a 1D projection histogram from bounding boxes along a specified axis.
+
+ Args:
+ boxes: A (N, 4) array of bounding boxes defined by [x_min, y_min, x_max, y_max].
+ axis: Axis for projection; 0 for horizontal (x-axis), 1 for vertical (y-axis).
+
+ Returns:
+ A 1D numpy array representing the projection histogram based on bounding box intervals.
+ """
+ assert axis in [0, 1]
+ max_length = np.max(boxes[:, axis::2])
+ projection = np.zeros(max_length, dtype=int)
+
+ # Increment projection histogram over the interval defined by each bounding box
+ for start, end in boxes[:, axis::2]:
+ projection[start:end] += 1
+
+ return projection
+
+
+def _split_projection_profile(arr_values: np.ndarray, min_value: float, min_gap: float):
+ """
+ Split the projection profile into segments based on specified thresholds.
+
+ Args:
+ arr_values: 1D array representing the projection profile.
+ min_value: Minimum value threshold to consider a profile segment significant.
+ min_gap: Minimum gap width to consider a separation between segments.
+
+ Returns:
+ A tuple of start and end indices for each segment that meets the criteria.
+ """
+ # Identify indices where the projection exceeds the minimum value
+ significant_indices = np.where(arr_values > min_value)[0]
+ if not len(significant_indices):
+ return
+
+ # Calculate gaps between significant indices
+ index_diffs = significant_indices[1:] - significant_indices[:-1]
+ gap_indices = np.where(index_diffs > min_gap)[0]
+
+ # Determine start and end indices of segments
+ segment_starts = np.insert(
+ significant_indices[gap_indices + 1],
+ 0,
+ significant_indices[0],
+ )
+ segment_ends = np.append(
+ significant_indices[gap_indices],
+ significant_indices[-1] + 1,
+ )
+
+ return segment_starts, segment_ends
+
+
+def _recursive_yx_cut(
+ boxes: np.ndarray,
+ indices: List[int],
+ res: List[int],
+ segment_ids: List[int],
+ current_id: int,
+ min_gap: int = 1,
+):
+ """
+ Recursively project and segment bounding boxes, starting with Y-axis and followed by X-axis.
+
+ Args:
+ boxes: A (N, 4) array representing bounding boxes.
+ indices: List of indices indicating the original position of boxes.
+ res: List to store indices of the final segmented bounding boxes.
+ min_gap (int): Minimum gap width to consider a separation between segments on the X-axis. Defaults to 1.
+
+ Returns:
+ None: This function modifies the `res` list in place.
+ """
+ assert len(boxes) == len(
+ indices
+ ), "The length of boxes and indices must be the same."
+
+ # Sort by y_min for Y-axis projection
+ y_sorted_indices = boxes[:, 1].argsort()
+ y_sorted_boxes = boxes[y_sorted_indices]
+ y_sorted_indices = np.array(indices)[y_sorted_indices]
+
+ # Perform Y-axis projection
+ y_projection = _projection_by_bboxes(boxes=y_sorted_boxes, axis=1)
+ y_intervals = _split_projection_profile(y_projection, 0, 1)
+
+ if not y_intervals:
+ for idx in indices:
+ segment_ids.append(current_id)
+ # current_id += 1
+ res.extend(indices)
+ return
+
+ # Process each segment defined by Y-axis projection
+ for y_start, y_end in zip(*y_intervals):
+ # Select boxes within the current y interval
+ y_interval_indices = (y_start <= y_sorted_boxes[:, 1]) & (
+ y_sorted_boxes[:, 1] < y_end
+ )
+ y_boxes_chunk = y_sorted_boxes[y_interval_indices]
+ y_indices_chunk = y_sorted_indices[y_interval_indices]
+
+ # Sort by x_min for X-axis projection
+ x_sorted_indices = y_boxes_chunk[:, 0].argsort()
+ x_sorted_boxes_chunk = y_boxes_chunk[x_sorted_indices]
+ x_sorted_indices_chunk = y_indices_chunk[x_sorted_indices]
+
+ # Perform X-axis projection
+ x_projection = _projection_by_bboxes(boxes=x_sorted_boxes_chunk, axis=0)
+ x_intervals = _split_projection_profile(x_projection, 0, min_gap)
+
+ if not x_intervals:
+ for idx in x_sorted_indices_chunk:
+ segment_ids.append(current_id)
+ current_id += 1
+ res.extend(x_sorted_indices_chunk)
+ continue
+
+ # If X-axis cannot be further segmented, add current indices to results
+ if len(x_intervals[0]) == 1:
+ for idx in x_sorted_indices_chunk:
+ segment_ids.append(current_id)
+ current_id += 1
+ res.extend(x_sorted_indices_chunk)
+ continue
+
+ # Recursively process each segment defined by X-axis projection
+ for x_start, x_end in zip(*x_intervals):
+ x_interval_indices = (x_start <= x_sorted_boxes_chunk[:, 0]) & (
+ x_sorted_boxes_chunk[:, 0] < x_end
+ )
+ _recursive_yx_cut(
+ x_sorted_boxes_chunk[x_interval_indices],
+ x_sorted_indices_chunk[x_interval_indices],
+ res,
+ segment_ids,
+ current_id,
+ )
+ current_id += 1
+
+
+def _recursive_xy_cut(
+ boxes: np.ndarray,
+ indices: List[int],
+ res: List[int],
+ segment_ids: List[int],
+ current_id: int,
+ min_gap: int = 1,
+):
+ """
+ Recursively performs X-axis projection followed by Y-axis projection to segment bounding boxes.
+
+ Args:
+ boxes: A (N, 4) array representing bounding boxes with [x_min, y_min, x_max, y_max].
+ indices: A list of indices representing the position of boxes in the original data.
+ res: A list to store indices of bounding boxes that meet the criteria.
+ min_gap (int): Minimum gap width to consider a separation between segments on the X-axis. Defaults to 1.
+
+ Returns:
+ None: This function modifies the `res` list in place.
+ """
+ # Ensure boxes and indices have the same length
+ assert len(boxes) == len(
+ indices
+ ), "The length of boxes and indices must be the same."
+
+ # Sort by x_min to prepare for X-axis projection
+ x_sorted_indices = boxes[:, 0].argsort()
+ x_sorted_boxes = boxes[x_sorted_indices]
+ x_sorted_indices = np.array(indices)[x_sorted_indices]
+
+ # Perform X-axis projection
+ x_projection = _projection_by_bboxes(boxes=x_sorted_boxes, axis=0)
+ x_intervals = _split_projection_profile(x_projection, 0, 1)
+
+ if not x_intervals:
+ for idx in indices:
+ segment_ids.append(current_id)
+ res.extend(indices)
+ return
+
+ # Process each segment defined by X-axis projection
+ for x_start, x_end in zip(*x_intervals):
+ # Select boxes within the current x interval
+ x_interval_indices = (x_start <= x_sorted_boxes[:, 0]) & (
+ x_sorted_boxes[:, 0] < x_end
+ )
+ x_boxes_chunk = x_sorted_boxes[x_interval_indices]
+ x_indices_chunk = x_sorted_indices[x_interval_indices]
+
+ # Sort selected boxes by y_min to prepare for Y-axis projection
+ y_sorted_indices = x_boxes_chunk[:, 1].argsort()
+ y_sorted_boxes_chunk = x_boxes_chunk[y_sorted_indices]
+ y_sorted_indices_chunk = x_indices_chunk[y_sorted_indices]
+
+ # Perform Y-axis projection
+ y_projection = _projection_by_bboxes(boxes=y_sorted_boxes_chunk, axis=1)
+ y_intervals = _split_projection_profile(y_projection, 0, min_gap)
+
+ if not y_intervals:
+ for idx in y_sorted_indices_chunk:
+ segment_ids.append(current_id)
+ current_id += 1
+ res.extend(y_sorted_indices_chunk)
+ continue
+
+ # If Y-axis cannot be further segmented, add current indices to results
+ if len(y_intervals[0]) == 1:
+ for idx in y_sorted_indices_chunk:
+ segment_ids.append(current_id)
+ current_id += 1
+ res.extend(y_sorted_indices_chunk)
+ continue
+
+ # Recursively process each segment defined by Y-axis projection
+ for y_start, y_end in zip(*y_intervals):
+ y_interval_indices = (y_start <= y_sorted_boxes_chunk[:, 1]) & (
+ y_sorted_boxes_chunk[:, 1] < y_end
+ )
+ _recursive_xy_cut(
+ y_sorted_boxes_chunk[y_interval_indices],
+ y_sorted_indices_chunk[y_interval_indices],
+ res,
+ segment_ids,
+ current_id,
+ )
+ current_id += 1
+
+
+def sort_by_xycut(
+ block_bboxes: Union[np.ndarray, List[List[int]]],
+ direction: int = 0,
+ min_gap: int = 1,
+) -> List[int]:
+ """
+ Sort bounding boxes using recursive XY cut method based on the specified direction.
+
+ Args:
+ block_bboxes (Union[np.ndarray, List[List[int]]]): An array or list of bounding boxes,
+ where each box is represented as
+ [x_min, y_min, x_max, y_max].
+ direction (int): Direction for the initial cut. Use 1 for Y-axis first and 0 for X-axis first.
+ Defaults to 0.
+ min_gap (int): Minimum gap width to consider a separation between segments. Defaults to 1.
+
+ Returns:
+ List[int]: A list of indices representing the order of sorted bounding boxes.
+ """
+ block_bboxes = np.asarray(block_bboxes).astype(int)
+ res = []
+ segment_ids = []
+ current_id = 0
+ if direction == 1:
+ _recursive_yx_cut(
+ block_bboxes,
+ np.arange(len(block_bboxes)).tolist(),
+ res,
+ segment_ids,
+ current_id,
+ min_gap,
+ )
+ else:
+ _recursive_xy_cut(
+ block_bboxes,
+ np.arange(len(block_bboxes)).tolist(),
+ res,
+ segment_ids,
+ current_id,
+ min_gap,
+ )
+ return res, segment_ids
+
+
+def _get_minbox_if_overlap_by_ratio(
+ bbox1: Union[List[int], Tuple[int, int, int, int]],
+ bbox2: Union[List[int], Tuple[int, int, int, int]],
+ ratio: float,
+ smaller: bool = True,
+) -> Optional[Union[List[int], Tuple[int, int, int, int]]]:
+ """
+ Determine if the overlap area between two bounding boxes exceeds a given ratio
+ and return the smaller (or larger) bounding box based on the `smaller` flag.
+
+ Args:
+ bbox1 (Union[List[int], Tuple[int, int, int, int]]): Coordinates of the first bounding box [x_min, y_min, x_max, y_max].
+ bbox2 (Union[List[int], Tuple[int, int, int, int]]): Coordinates of the second bounding box [x_min, y_min, x_max, y_max].
+ ratio (float): The overlap ratio threshold.
+ smaller (bool): If True, return the smaller bounding box; otherwise, return the larger one.
+
+ Returns:
+ Optional[Union[List[int], Tuple[int, int, int, int]]]:
+ The selected bounding box or None if the overlap ratio is not exceeded.
+ """
+ # Calculate the areas of both bounding boxes
+ area1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
+ area2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
+ # Calculate the overlap ratio using a helper function
+ overlap_ratio = _calculate_overlap_area_div_minbox_area_ratio(bbox1, bbox2)
+ # Check if the overlap ratio exceeds the threshold
+ if overlap_ratio > ratio:
+ if (area1 <= area2 and smaller) or (area1 >= area2 and not smaller):
+ return 1
+ else:
+ return 2
+ return None
+
+
+def _remove_overlap_blocks(
+ blocks: List[Dict[str, List[int]]],
+ threshold: float = 0.65,
+ smaller: bool = True,
+) -> Tuple[List[Dict[str, List[int]]], List[Dict[str, List[int]]]]:
+ """
+ Remove overlapping blocks based on a specified overlap ratio threshold.
+
+ Args:
+ blocks (List[Dict[str, List[int]]]): List of block dictionaries, each containing a 'block_bbox' key.
+ threshold (float): Ratio threshold to determine significant overlap.
+ smaller (bool): If True, the smaller block in overlap is removed.
+
+ Returns:
+ Tuple[List[Dict[str, List[int]]], List[Dict[str, List[int]]]]:
+ A tuple containing the updated list of blocks and a list of dropped blocks.
+ """
+ dropped_blocks = []
+ dropped_indexes = set()
+
+ # Iterate over each pair of blocks to find overlaps
+ for i, block1 in enumerate(blocks):
+ for j in range(i + 1, len(blocks)):
+ block2 = blocks[j]
+ # Skip blocks that are already marked for removal
+ if i in dropped_indexes or j in dropped_indexes:
+ continue
+ # Check for overlap and determine which block to remove
+ overlap_box_index = _get_minbox_if_overlap_by_ratio(
+ block1["block_bbox"],
+ block2["block_bbox"],
+ threshold,
+ smaller=smaller,
+ )
+ if overlap_box_index is not None:
+ # Determine which block to remove based on overlap_box_index
+ if overlap_box_index == 1:
+ drop_index = i
+ else:
+ drop_index = j
+ dropped_indexes.add(drop_index)
+
+ # Remove marked blocks from the original list
+ for index in sorted(dropped_indexes, reverse=True):
+ dropped_blocks.append(blocks[index])
+ del blocks[index]
+
+ return blocks, dropped_blocks
+
+
+def _get_text_median_width(
+ blocks: List[Dict[str, any]], is_horizontal=True
+) -> Tuple[float, int, float]:
+ """
+ Calculate the median width of blocks labeled as "text".
+
+ Args:
+ blocks (List[Dict[str, any]]): List of block dictionaries, each containing a 'block_bbox' and 'label'.
+
+ Returns:
+ float: The median width of text blocks, or infinity if no text blocks are found.
+ int: The count of text blocks within 10% of the median width.
+ float: The page length of text blocks.
+ """
+ if is_horizontal:
+ widths = [
+ block["block_bbox"][2] - block["block_bbox"][0]
+ for block in blocks
+ if block.get("block_label") == "text"
+ ]
+ page_max = max([block["block_bbox"][2] for block in blocks] + [0])
+ page_min = min([block["block_bbox"][0] for block in blocks] + [0])
+ else:
+ widths = [
+ block["block_bbox"][3] - block["block_bbox"][1]
+ for block in blocks
+ if block.get("block_label")
+ in ["text", "formula", "algorithm", "reference", "content", "abstract"]
+ ]
+ page_max = max([block["block_bbox"][3] for block in blocks] + [0])
+ page_min = min([block["block_bbox"][1] for block in blocks] + [0])
+
+ if len(widths) == 0:
+ return float("inf"), 0, 0
+
+ page_length = page_max - page_min
+ k = np.median(widths)
+ differences = np.abs(widths - k)
+ k_01 = k * 0.4
+ count = np.sum(differences < k_01)
+ return k if widths else float("inf"), count, page_length
+
+
+def _get_layout_property(
+ blocks: List[Dict[str, any]],
+ median_width: float,
+ no_mask_labels: List[str],
+ threshold: float = 0.8,
+ # other_layout_threshold: float = 0.4,
+) -> Tuple[List[Dict[str, any]], bool]:
+ """
+ Determine the layout (single or double column) of text blocks.
+
+ Args:
+ blocks (List[Dict[str, any]]): List of block dictionaries containing 'label' and 'block_bbox'.
+ median_width (float): Median width of text blocks.
+ no_mask_labels (List[str]): Labels of blocks to be considered for layout analysis.
+ threshold (float): Threshold for determining layout overlap.
+
+ Returns:
+ Tuple[List[Dict[str, any]], bool]: Updated list of blocks with layout information and a boolean
+ indicating if the double layout area is greater than the single layout area.
+ """
+ blocks.sort(
+ key=lambda x: (
+ x["block_bbox"][0],
+ (x["block_bbox"][2] - x["block_bbox"][0]),
+ ),
+ )
+ check_single_layout = {}
+ page_min_x, page_max_x = float("inf"), 0
+ double_label_area = 0
+ single_label_area = 0
+
+ for i, block in enumerate(blocks):
+ page_min_x = min(page_min_x, block["block_bbox"][0])
+ page_max_x = max(page_max_x, block["block_bbox"][2])
+ page_width = page_max_x - page_min_x
+
+ for i, block in enumerate(blocks):
+ if block["block_label"] not in no_mask_labels:
+ continue
+
+ x_min_i, _, x_max_i, _ = block["block_bbox"]
+ layout_length = x_max_i - x_min_i
+ (
+ cover_count,
+ cover_with_threshold_count,
+ other_layout_threshold_count,
+ ) = (0, 0, 0)
+ match_block_with_threshold_indexes = []
+
+ has_left_text = False
+ has_right_text = False
+ x1, y1, x2, y2 = block["block_bbox"]
+ for j, block2 in enumerate(blocks):
+ if i == j or block2["block_label"] != "text":
+ continue
+ bbox2 = block2["block_bbox"]
+ x1_2, y1_2, x2_2, y2_2 = bbox2
+ if x2_2 <= x1 and not (y2_2 <= y1 or y1_2 >= y2):
+ has_left_text = True
+ if x1_2 >= x2 and not (y2_2 <= y1 or y1_2 >= y2):
+ has_right_text = True
+ if has_left_text or has_right_text:
+ break
+ no_text_on_sides = not (has_left_text or has_right_text)
+ no_text_on_sides = True
+
+ for j, other_block in enumerate(blocks):
+ if i == j or other_block["block_label"] not in no_mask_labels:
+ continue
+
+ x_min_j, _, x_max_j, _ = other_block["block_bbox"]
+ x_match_min, x_match_max = max(
+ x_min_i,
+ x_min_j,
+ ), min(x_max_i, x_max_j)
+ match_block_iou = (x_match_max - x_match_min) / (x_max_j - x_min_j)
+ # max_iou = _get_projection_iou(block["block_bbox"],other_block["block_bbox"])
+
+ if match_block_iou > 0:
+ cover_count += 1
+ if match_block_iou > threshold:
+ cover_with_threshold_count += 1
+ match_block_with_threshold_indexes.append(
+ (j, match_block_iou),
+ )
+ # elif max_iou > other_layout_threshold: # centered text
+ # other_layout_threshold_count += 1
+
+ x_min_i = x_match_max
+ if x_min_i >= x_max_i:
+ break
+
+ if ((layout_length > median_width * 1.3) and cover_count >= 2) or (
+ layout_length > 0.6 * page_width
+ ):
+ # ) or (layout_length > 0.6 * page_width and no_text_on_sides):
+ # if (
+ # layout_length > median_width * 1.3 and cover_count >= 2
+ # ):
+ # if layout_length > median_width * 1.3 and (cover_with_threshold_count >= 2):
+ block["layout"] = "double"
+ double_label_area += (block["block_bbox"][2] - block["block_bbox"][0]) * (
+ block["block_bbox"][3] - block["block_bbox"][1]
+ )
+ # elif layout_length < median_width* 0.5 and cover_count >= 2:
+ # # elif other_layout_threshold_count >= 2:
+ # block["layout"] = "other"
+ else:
+ block["layout"] = "single"
+ check_single_layout[i] = match_block_with_threshold_indexes
+
+ # Check single-layout block
+ for i, single_layout in check_single_layout.items():
+ if single_layout:
+ index, match_iou = single_layout[-1]
+ if match_iou > 0.9 and blocks[index]["layout"] == "double":
+ blocks[i]["layout"] = "double"
+ double_label_area += (
+ blocks[i]["block_bbox"][2] - blocks[i]["block_bbox"][0]
+ ) * (blocks[i]["block_bbox"][3] - blocks[i]["block_bbox"][1])
+ else:
+ single_label_area += (
+ blocks[i]["block_bbox"][2] - blocks[i]["block_bbox"][0]
+ ) * (blocks[i]["block_bbox"][3] - blocks[i]["block_bbox"][1])
+
+ return blocks, (double_label_area > single_label_area)
+
+
+def _get_bbox_direction(input_bbox: List[float], ratio: float = 1.0) -> bool:
+ """
+ Determine if a bounding box is horizontal or vertical.
+
+ Args:
+ input_bbox (List[float]): Bounding box [x_min, y_min, x_max, y_max].
+ ratio (float): Ratio for determining orientation. Default is 1.0.
+
+ Returns:
+ bool: True if the bounding box is considered horizontal, False if vertical.
+ """
+ width = input_bbox[2] - input_bbox[0]
+ height = input_bbox[3] - input_bbox[1]
+ return width * ratio >= height
+
+
+def _get_projection_iou(
+ input_bbox: List[float],
+ match_bbox: List[float],
+ is_horizontal: bool = True,
+) -> float:
+ """
+ Calculate the IoU of lines between two bounding boxes.
+
+ Args:
+ input_bbox (List[float]): First bounding box [x_min, y_min, x_max, y_max].
+ match_bbox (List[float]): Second bounding box [x_min, y_min, x_max, y_max].
+ is_horizontal (bool): Whether to compare horizontally or vertically.
+
+ Returns:
+ float: Line IoU. Returns 0 if there is no overlap.
+ """
+ if is_horizontal:
+ x_match_min = max(input_bbox[0], match_bbox[0])
+ x_match_max = min(input_bbox[2], match_bbox[2])
+ overlap = max(0, x_match_max - x_match_min)
+ input_width = min(input_bbox[2] - input_bbox[0], match_bbox[2] - match_bbox[0])
+ else:
+ y_match_min = max(input_bbox[1], match_bbox[1])
+ y_match_max = min(input_bbox[3], match_bbox[3])
+ overlap = max(0, y_match_max - y_match_min)
+ input_width = min(input_bbox[3] - input_bbox[1], match_bbox[3] - match_bbox[1])
+
+ return overlap / input_width if input_width > 0 else 0.0
+
+
+def _get_pre_cut(
+ boxes: np.ndarray, indices: List[int], direction=0, min_gap=1.0
+): # direction 0 x;1 y
+ sorted_indices = boxes[:, direction].argsort()
+ sorted_boxes = boxes[sorted_indices]
+ sorted_indices = np.array(indices)[sorted_indices]
+
+ # Perform X-axis projection
+ projection = _projection_by_bboxes(boxes=sorted_boxes, axis=direction)
+ intervals = _split_projection_profile(projection, 0, 1)
+
+ if not intervals:
+ return []
+
+ # Process each segment defined by axis projection
+ last_end = -1
+ res = []
+ interval_list = []
+ for start, end in zip(*intervals):
+ if last_end != -1 and start - last_end >= min_gap:
+ res.append((last_end + start) // 2)
+ interval_list.append(start - last_end)
+ last_end = end
+ return res, np.median(interval_list) if len(interval_list) else 0.0
+
+
+def _get_sub_category(
+ blocks: List[Dict[str, Any]],
+ title_labels: List[str],
+ min_gap_x=10,
+ min_gap_y=10,
+ is_only_x=False,
+) -> Tuple[List[Dict[str, Any]], List[float]]:
+ """
+ Determine the layout of title and text blocks and collect pre_cuts.
+
+ Args:
+ blocks (List[Dict[str, Any]]): List of block dictionaries.
+ title_labels (List[str]): List of labels considered as titles.
+
+ Returns:
+ List[Dict[str, Any]]: Updated list of blocks with title-text layout information.
+ Dict[float]: Dict of pre_cuts coordinates.
+ """
+ if len(blocks) == 0:
+ return blocks, {}
+
+ sub_title_labels = ["paragraph_title"]
+ vision_labels = ["image", "table", "chart", "figure"]
+ vision_title_labels = ["figure_title", "chart_title", "table_title"]
+ all_labels = title_labels + sub_title_labels + vision_labels + vision_title_labels
+ special_pre_cut_labels = sub_title_labels
+
+ # single doc title is irregular,pre cut not applicable
+ num_doc_title = 0
+ for block in blocks:
+ if block["block_label"] == "doc_title":
+ num_doc_title += 1
+ if num_doc_title == 2:
+ special_pre_cut_labels = title_labels + sub_title_labels
+ break
+
+ min_x = min(block["block_bbox"][0] for block in blocks)
+ min_y = min(block["block_bbox"][1] for block in blocks)
+ max_x = max(block["block_bbox"][2] for block in blocks)
+ max_y = max(block["block_bbox"][3] for block in blocks)
+ region_bbox = (min_x, min_y, max_x, max_y)
+ region_x_center = (region_bbox[0] + region_bbox[2]) / 2
+ region_y_center = (region_bbox[1] + region_bbox[3]) / 2
+ region_width = region_bbox[2] - region_bbox[0]
+ region_height = region_bbox[3] - region_bbox[1]
+
+ bboxes = np.array([list(map(int, block["block_bbox"])) for block in blocks])
+ pre_cuts = {"tran": False}
+
+ x_pre_cuts, interval_len_x = _get_pre_cut(
+ boxes=bboxes, indices=list(range(len(blocks))), direction=0, min_gap=min_gap_x
+ )
+ y_pre_cuts, interval_len_y = _get_pre_cut(
+ boxes=bboxes, indices=list(range(len(blocks))), direction=1, min_gap=70
+ )
+
+ if is_only_x == False:
+ if interval_len_x * 2 < interval_len_y:
+ pre_cuts["tran"] = True
+ pre_cuts["y"] = y_pre_cuts
+
+ # if y_pre_cuts != [] and is_only_x==False:
+ # pre_cuts["y"] = y_pre_cuts
+
+ if x_pre_cuts != [] and len(blocks) > min_gap_y:
+ pre_cuts["x"] = x_pre_cuts
+
+ for i, block1 in enumerate(blocks):
+ block1.setdefault("title_text", [])
+ block1.setdefault("sub_title", [])
+ block1.setdefault("vision_footnote", [])
+ block1.setdefault("sub_label", block1["block_label"])
+
+ if block1["block_label"] not in all_labels:
+ continue
+
+ bbox1 = block1["block_bbox"]
+ x1, y1, x2, y2 = bbox1
+ is_horizontal_1 = _get_bbox_direction(block1["block_bbox"])
+ left_up_title_text_distance = float("inf")
+ left_up_title_text_index = -1
+ left_up_title_text_direction = None
+ right_down_title_text_distance = float("inf")
+ right_down_title_text_index = -1
+ right_down_title_text_direction = None
+
+ # pre-cuts
+ # Condition 1: Length is greater than half of the layout region
+ if is_horizontal_1:
+ block_length = x2 - x1
+ required_length = region_width / 2
+ else:
+ block_length = y2 - y1
+ required_length = region_height / 2
+ if block1["block_label"] in special_pre_cut_labels:
+ length_condition = True
+ else:
+ length_condition = block_length > required_length
+
+ # Condition 2: Centered check (must be within ±20 in both horizontal and vertical directions)
+ block_x_center = (x1 + x2) / 2
+ block_y_center = (y1 + y2) / 2
+ tolerance_len = block_length // 5
+ if block1["block_label"] in special_pre_cut_labels:
+ tolerance_len = block_length // 10
+ if is_horizontal_1:
+ is_centered = abs(block_x_center - region_x_center) <= tolerance_len
+ else:
+ is_centered = abs(block_y_center - region_y_center) <= tolerance_len
+ # Condition 3: Check for surrounding text
+ has_left_text = False
+ has_right_text = False
+ has_above_text = False
+ has_below_text = False
+ for block2 in blocks:
+ if (
+ block2["block_label"]
+ not in ["text", "formula", "content", "abstract", "reference"]
+ + title_labels
+ + sub_title_labels
+ + vision_title_labels
+ ):
+ continue
+ bbox2 = block2["block_bbox"]
+ x1_2, y1_2, x2_2, y2_2 = bbox2
+ if is_horizontal_1:
+ if x2_2 <= x1 and not (y2_2 <= y1 or y1_2 >= y2):
+ has_left_text = True
+ if x1_2 >= x2 and not (y2_2 <= y1 or y1_2 >= y2):
+ has_right_text = True
+ else:
+ if y2_2 <= y1 and not (x2_2 <= x1 or x1_2 >= x2):
+ has_above_text = True
+ if y1_2 >= y2 and not (x2_2 <= x1 or x1_2 >= x2):
+ has_below_text = True
+
+ if (is_horizontal_1 and has_left_text and has_right_text) or (
+ not is_horizontal_1 and has_above_text and has_below_text
+ ):
+ break
+
+ no_text_on_sides = (
+ not (has_left_text or has_right_text)
+ if is_horizontal_1
+ else not (has_above_text or has_below_text)
+ )
+
+ # Add coordinates if all conditions are met
+ if is_centered and length_condition and no_text_on_sides:
+ if is_horizontal_1:
+ pre_cuts.setdefault("y", []).append(y1)
+ else:
+ pre_cuts.setdefault("x", []).append(x1)
+
+ block_iou_threshold = 0.1
+ if block1["block_label"] in sub_title_labels:
+ block_iou_threshold = 0.5
+ match_iou_flag_left_up = False
+ match_iou_flag_right_down = False
+
+ for j, block2 in enumerate(blocks):
+ if i == j:
+ continue
+
+ bbox2 = block2["block_bbox"]
+ x1_prime, y1_prime, x2_prime, y2_prime = bbox2
+ is_horizontal_2 = _get_bbox_direction(bbox2)
+ match_block_iou = _get_projection_iou(
+ bbox2,
+ bbox1,
+ is_horizontal_1,
+ )
+
+ def distance_(is_horizontal, is_left_up):
+ if match_block_iou > 0:
+ if is_horizontal:
+ if is_left_up:
+ return (y1 - y2_prime + 2) // 5 + x1_prime / 5000
+ else:
+ return (y1_prime - y2 + 2) // 5 + x1_prime / 5000
+
+ else:
+ if is_left_up:
+ return (x1 - x2_prime + 2) // 5 + y1_prime / 5000
+ else:
+ return (x1_prime - x2 + 2) // 5 + y1_prime / 5000
+ else:
+ return float("inf")
+
+ if is_horizontal_1:
+ # if match_block_iou >= block_iou_threshold:
+ left_up_distance = distance_(True, True)
+ right_down_distance = distance_(True, False)
+ if y2_prime <= y1 and left_up_distance <= left_up_title_text_distance:
+ left_up_title_text_index = j
+ left_up_title_text_distance = left_up_distance
+ left_up_title_text_direction = is_horizontal_2
+ if match_block_iou < block_iou_threshold:
+ match_iou_flag_left_up = False
+ else:
+ match_iou_flag_left_up = True
+ elif (
+ y1_prime > y2
+ and right_down_distance < right_down_title_text_distance
+ ):
+ right_down_title_text_distance = right_down_distance
+ right_down_title_text_index = j
+ right_down_title_text_direction = is_horizontal_2
+ if match_block_iou < block_iou_threshold:
+ match_iou_flag_right_down = False
+ else:
+ match_iou_flag_right_down = True
+
+ else:
+ # if match_block_iou >= block_iou_threshold:
+ left_up_distance = distance_(False, True)
+ right_down_distance = distance_(False, False)
+ if x2_prime <= x1 and left_up_distance <= left_up_title_text_distance:
+ left_up_title_text_distance = left_up_distance
+ left_up_title_text_index = j
+ left_up_title_text_direction = is_horizontal_2
+ if match_block_iou < block_iou_threshold:
+ match_iou_flag_left_up = False
+ else:
+ match_iou_flag_left_up = True
+ elif (
+ x1_prime > x2
+ and right_down_distance < right_down_title_text_distance
+ ):
+ right_down_title_text_distance = right_down_distance
+ right_down_title_text_index = j
+ right_down_title_text_direction = is_horizontal_2
+ if match_block_iou < block_iou_threshold:
+ match_iou_flag_right_down = False
+ else:
+ match_iou_flag_right_down = True
+
+ height = bbox1[3] - bbox1[1]
+ width = bbox1[2] - bbox1[0]
+ title_text_weight = [0.8, 0.8]
+
+ title_text, sub_title, vision_footnote = [], [], []
+
+ def get_sub_category_(
+ title_text_direction,
+ title_text_index,
+ label,
+ is_left_up=True,
+ ):
+ direction_ = [1, 3] if is_left_up else [2, 4]
+ if (
+ title_text_direction == is_horizontal_1
+ and title_text_index != -1
+ and (label == "text" or label == "paragraph_title")
+ ):
+ bbox2 = blocks[title_text_index]["block_bbox"]
+ if is_horizontal_1:
+ height1 = bbox2[3] - bbox2[1]
+ width1 = bbox2[2] - bbox2[0]
+ if label == "text":
+ if (
+ _nearest_edge_distance(bbox1, bbox2)[0] <= 15
+ and block1["block_label"] in vision_labels
+ and width1 < width
+ and height1 < 0.5 * height
+ ):
+ blocks[title_text_index]["sub_label"] = "vision_footnote"
+ vision_footnote.append(bbox2)
+ elif (
+ height1 < height * title_text_weight[0]
+ and (width1 < width or width1 > 1.5 * width)
+ and block1["block_label"] in title_labels
+ ):
+ blocks[title_text_index]["sub_label"] = "title_text"
+ title_text.append((direction_[0], bbox2))
+ elif (
+ label == "paragraph_title"
+ and block1["block_label"] in sub_title_labels
+ ):
+ sub_title.append(bbox2)
+ else:
+ height1 = bbox2[3] - bbox2[1]
+ width1 = bbox2[2] - bbox2[0]
+ if label == "text":
+ if (
+ _nearest_edge_distance(bbox1, bbox2)[0] <= 15
+ and block1["block_label"] in vision_labels
+ and height1 < height
+ and width1 < 0.5 * width
+ ):
+ blocks[title_text_index]["sub_label"] = "vision_footnote"
+ vision_footnote.append(bbox2)
+ elif (
+ width1 < width * title_text_weight[1]
+ and block1["block_label"] in title_labels
+ ):
+ blocks[title_text_index]["sub_label"] = "title_text"
+ title_text.append((direction_[1], bbox2))
+ elif (
+ label == "paragraph_title"
+ and block1["block_label"] in sub_title_labels
+ ):
+ sub_title.append(bbox2)
+
+ if match_iou_flag_right_down == False:
+ right_down_title_text_index = -1
+ if match_iou_flag_left_up == False:
+ left_up_title_text_index = -1
+
+ if (
+ is_horizontal_1
+ and abs(left_up_title_text_distance - right_down_title_text_distance) * 5
+ > height
+ ) or (
+ not is_horizontal_1
+ and abs(left_up_title_text_distance - right_down_title_text_distance) * 5
+ > width
+ ):
+ if left_up_title_text_distance < right_down_title_text_distance:
+ get_sub_category_(
+ left_up_title_text_direction,
+ left_up_title_text_index,
+ blocks[left_up_title_text_index]["block_label"],
+ True,
+ )
+ else:
+ get_sub_category_(
+ right_down_title_text_direction,
+ right_down_title_text_index,
+ blocks[right_down_title_text_index]["block_label"],
+ False,
+ )
+ else:
+ get_sub_category_(
+ left_up_title_text_direction,
+ left_up_title_text_index,
+ blocks[left_up_title_text_index]["block_label"],
+ True,
+ )
+ get_sub_category_(
+ right_down_title_text_direction,
+ right_down_title_text_index,
+ blocks[right_down_title_text_index]["block_label"],
+ False,
+ )
+
+ if block1["block_label"] in title_labels:
+ if blocks[i].get("title_text") == []:
+ blocks[i]["title_text"] = title_text
+
+ if block1["block_label"] in sub_title_labels:
+ if blocks[i].get("sub_title") == []:
+ blocks[i]["sub_title"] = sub_title
+
+ if block1["block_label"] in vision_labels:
+ if blocks[i].get("vision_footnote") == []:
+ blocks[i]["vision_footnote"] = vision_footnote
+
+ return blocks, pre_cuts
+
+
+def _projection_index_xy(blocks):
+ blocks.sort(key=lambda x: (x["index"], x["block_bbox"][1], x["block_bbox"][0]))
+
+ sorted_blocks = []
+ i = 0
+ while i < len(blocks):
+ block1 = blocks[i]
+ mid_blocks = [block1]
+ for j in range(i + 1, len(blocks)):
+ block2 = blocks[j]
+ if block1["index"] != block2["index"]:
+ break
+ iou = _get_projection_iou(
+ block1["block_bbox"], block2["block_bbox"], is_horizontal=False
+ )
+ if iou > 0.5:
+ mid_blocks.append(block2)
+ else:
+ break
+ mid_blocks.sort(key=lambda x: x["block_bbox"][0])
+ sorted_blocks.extend(mid_blocks)
+ i += len(mid_blocks)
+ return sorted_blocks
+
+
+def _projection_xy(bboxes, segment_ids, is_horizontal=False):
+ """
+ Sort and group bounding boxes based on their projection along the x or y axis.
+
+ :param bboxes: List of bounding boxes, each represented as [x1, y1, x2, y2].
+ :param is_horizontal: Boolean indicating whether to project horizontally (True) or vertically (False).
+ :return: Sorted and grouped bounding boxes.
+ """
+ # Determine the axis for sorting
+ axis = 1 if is_horizontal else 0
+
+ # Initial sort based on the chosen axis
+ # sorted_bboxes = sorted(bboxes, key=lambda x: (x[(axis + 1)%2], x[axis]))
+ bboxes_with_ids = list(zip(bboxes, segment_ids))
+ bboxes_with_ids.sort(key=lambda x: (x[1], x[0][1], x[0][0]))
+
+ # Initialize the final list of sorted and grouped bounding boxes
+ final_sorted_bboxes = []
+
+ # Initialize the visited array
+ visited = [False] * len(bboxes_with_ids)
+
+ # Group by segment_id
+ for i in range(len(bboxes_with_ids)):
+ if visited[i]:
+ continue
+
+ current_id = bboxes_with_ids[i][1]
+ mid_bboxes_with_ids = [bboxes_with_ids[i]]
+ visited[i] = True
+
+ # Collect all bboxes with the same segment_id and IoU > 0.4
+ for j in range(i + 1, len(bboxes_with_ids)):
+ if visited[j] or bboxes_with_ids[j][1] != current_id:
+ continue
+
+ bbox1 = mid_bboxes_with_ids[-1][0]
+ bbox2 = bboxes_with_ids[j][0]
+ iou = _get_projection_iou(bbox1, bbox2, is_horizontal=is_horizontal)
+ if iou > 0.5:
+ mid_bboxes_with_ids.append(bboxes_with_ids[j])
+ visited[j] = True
+
+ # Sort the collected bboxes within the same segment_id based on the projection axis
+ mid_bboxes_with_ids.sort(key=lambda x: (x[0][axis], x[0][(axis + 1) % 2]))
+
+ # Add the sorted bboxes to the final list
+ final_sorted_bboxes.extend([x[0] for x in mid_bboxes_with_ids])
+
+ return final_sorted_bboxes
+
+
+def get_layout_ordering(
+ parsing_res_list: List[Dict[str, Any]],
+ no_mask_labels: List[str] = [],
+ is_only_xycut=False,
+ is_add_mgs=True,
+ is_add_cmm=True,
+ is_use_adaptive_scheme=True,
+ is_add_pre_cut=True,
+ is_single_stage=False,
+ min_gap_x=-1,
+ min_gap_y=-1,
+ is_only_x=False,
+ remove_overlaps=True,
+) -> List[Dict[str, Any]]:
+ """
+ Process layout parsing results to remove overlapping bounding boxes
+ and assign an ordering index based on their positions.
+
+ Modifies:
+ The 'parsing_res_list' list by adding an 'index' to each block.
+
+ Args:
+ parsing_res_list (List[Dict[str, Any]]): List of block dictionaries with 'block_bbox' and 'block_label'.
+ no_mask_labels (List[str]): Labels for which overlapping removal is not performed.
+ remove_overlaps (bool): Whether to apply the upstream overlap-removal
+ heuristic before ordering. Defaults to True.
+ """
+ title_text_labels = ["doc_title"]
+ title_labels = ["doc_title", "paragraph_title"]
+ vision_labels = ["image", "table", "seal", "chart", "figure"]
+ vision_title_labels = ["table_title", "chart_title", "figure_title"]
+
+ if remove_overlaps:
+ parsing_res_list, _ = _remove_overlap_blocks(
+ parsing_res_list,
+ threshold=0.5,
+ smaller=True,
+ )
+ parsing_res_list, pre_cuts = _get_sub_category(
+ parsing_res_list,
+ title_text_labels,
+ min_gap_x=min_gap_x,
+ min_gap_y=min_gap_y,
+ is_only_x=is_only_x,
+ )
+
+ if is_only_xycut == True:
+ doc_flag = False
+
+ projection_direction_page = False
+ median_height, small_height_num, page_height = _get_text_median_width(
+ parsing_res_list, is_horizontal=False
+ )
+ if median_height < 0.05 * page_height and small_height_num > 45:
+ pre_cuts = {"x": []}
+ projection_direction_page = True
+
+ if is_only_xycut or is_add_mgs == False or is_add_pre_cut == False:
+ parsing_res_by_pre_cuts_list = [parsing_res_list]
+ else:
+ parsing_res_by_pre_cuts_list = [parsing_res_list]
+ if len(pre_cuts) > 1:
+ block_bboxes = [block["block_bbox"] for block in parsing_res_list]
+ if pre_cuts["tran"]:
+ axes_order = ["y", "x"]
+ else:
+ axes_order = ["x", "y"]
+ # print(pre_cuts)
+ # print(axes_order)
+ for axis in axes_order:
+ if axis in pre_cuts:
+ axis_index = 1 if axis == "y" else 0
+
+ max_val = max(bbox[axis_index + 2] for bbox in block_bboxes)
+
+ intervals = []
+ prev = 0
+ for cut in sorted(pre_cuts[axis]):
+ intervals.append((prev, cut))
+ prev = cut
+ intervals.append((prev, max_val))
+
+ new_parsing_res_by_pre_cuts_list = []
+
+ for parsing_res_group in parsing_res_by_pre_cuts_list:
+ for start, end in intervals:
+ parsing_res_by_current_interval = []
+ parsing_res_group_bboxes = [
+ block["block_bbox"] for block in parsing_res_group
+ ]
+ for idx, bbox in enumerate(parsing_res_group_bboxes):
+ if (bbox[axis_index] >= start) and (
+ bbox[axis_index] < end
+ ):
+ parsing_res_by_current_interval.append(
+ parsing_res_group[idx]
+ )
+ new_parsing_res_by_pre_cuts_list.append(
+ parsing_res_by_current_interval
+ )
+
+ parsing_res_by_pre_cuts_list = new_parsing_res_by_pre_cuts_list
+
+ final_parsing_res_list = []
+ num_index = 0
+ num_sub_index = 0
+ page_first_doc_title = False
+ for sub_page_idx, parsing_res_by_pre_cuts in enumerate(
+ parsing_res_by_pre_cuts_list
+ ):
+ # print("input", [block["block_bbox"] for block in parsing_res_by_pre_cuts])
+ # use mask
+ if is_only_xycut == False:
+ doc_flag = False
+ median_width, _, _ = _get_text_median_width(parsing_res_by_pre_cuts)
+ parsing_res_by_pre_cuts, projection_direction = _get_layout_property(
+ parsing_res_by_pre_cuts,
+ median_width,
+ no_mask_labels=no_mask_labels,
+ threshold=0.3,
+ )
+ projection_direction = projection_direction or projection_direction_page
+
+ for block in parsing_res_by_pre_cuts:
+ block["block_bbox"] = list(map(int, block["block_bbox"]))
+ if block["block_label"] == "doc_title":
+ page_first_doc_title = True
+
+ # Convert bounding boxes to float and remove overlaps
+ (
+ double_text_blocks,
+ other_text_blocks,
+ title_text_blocks,
+ title_blocks,
+ vision_blocks,
+ vision_title_blocks,
+ vision_footnote_blocks,
+ other_blocks,
+ ) = ([], [], [], [], [], [], [], [])
+
+ drop_indexes = []
+
+ parsing_res_by_pre_cuts.sort(key=lambda x: int(x["block_bbox"][1]))
+ first_label_flag = True
+
+ for index, block in enumerate(parsing_res_by_pre_cuts):
+ label = block["sub_label"]
+ block["block_bbox"] = list(map(int, block["block_bbox"]))
+
+ # use mask and add mgs
+ if is_add_mgs:
+
+ # if page_first_doc_title == False and (first_label_flag and label == "paragraph_title"):
+ # block["sub_label"] = "doc_title"
+
+ if label == "doc_title":
+ doc_flag = True
+
+ if label in no_mask_labels:
+ if block["layout"] == "double":
+ double_text_blocks.append(block)
+ drop_indexes.append(index)
+ # elif block["layout"] == "other":
+ # other_text_blocks.append(block)
+ # drop_indexes.append(index)
+ first_label_flag = False
+ elif label == "title_text":
+ title_text_blocks.append(block)
+ drop_indexes.append(index)
+ first_label_flag = False
+ elif label == "vision_footnote":
+ vision_footnote_blocks.append(block)
+ drop_indexes.append(index)
+ first_label_flag = False
+ elif label in vision_title_labels:
+ vision_title_blocks.append(block)
+ drop_indexes.append(index)
+ first_label_flag = False
+ elif label in title_labels:
+ title_blocks.append(block)
+ drop_indexes.append(index)
+ first_label_flag = False
+ elif label in vision_labels:
+ vision_blocks.append(block)
+ drop_indexes.append(index)
+ first_label_flag = False
+ else:
+ other_blocks.append(block)
+ drop_indexes.append(index)
+ # use mask and no mgs
+ else:
+ if label not in no_mask_labels:
+ other_blocks.append(block)
+ drop_indexes.append(index)
+
+ # keep single_layout text
+ for index in sorted(drop_indexes, reverse=True):
+ del parsing_res_by_pre_cuts[index]
+
+ # use mask and use mgs
+ if is_add_mgs:
+ if len(parsing_res_by_pre_cuts) > 0:
+ # single text label
+ if is_use_adaptive_scheme and (
+ len(double_text_blocks) > len(parsing_res_by_pre_cuts)
+ or projection_direction
+ ):
+ parsing_res_by_pre_cuts.extend(
+ title_blocks + double_text_blocks
+ )
+ title_blocks = []
+ double_text_blocks = []
+ block_bboxes = [
+ block["block_bbox"] for block in parsing_res_by_pre_cuts
+ ]
+ # block_bboxes.sort(
+ # key=lambda x: (
+ # x[0] // max(20, median_width),
+ # x[1],
+ # ),
+ # )
+ block_bboxes = np.array(block_bboxes)
+ # print("sort by yx")
+ sorted_indices, segment_ids = sort_by_xycut(
+ block_bboxes, direction=1, min_gap=1
+ )
+ else:
+ block_bboxes = [
+ block["block_bbox"] for block in parsing_res_by_pre_cuts
+ ]
+ # block_bboxes.sort(key=lambda x: (x[0] // 20, x[1]))
+ block_bboxes = np.array(block_bboxes)
+ # print("sort by xy")
+ sorted_indices, segment_ids = sort_by_xycut(
+ block_bboxes, direction=0, min_gap=1
+ )
+ # get index
+ sorted_boxes = block_bboxes[sorted_indices].tolist()
+ # print("sorte bboxes", sorted_boxes, segment_ids)
+
+ # projection ordering
+ sorted_boxes = _projection_xy(sorted_boxes, segment_ids)
+
+ # print(sorted_boxes)
+ for block in parsing_res_by_pre_cuts:
+ block["index"] = (
+ num_index + sorted_boxes.index(block["block_bbox"]) + 1
+ )
+ block["sub_index"] = (
+ num_sub_index + sorted_boxes.index(block["block_bbox"]) + 1
+ )
+
+ # use mask and no mgs
+ else:
+ block_bboxes = [
+ block["block_bbox"] for block in parsing_res_by_pre_cuts
+ ]
+ block_bboxes.sort(
+ key=lambda x: (
+ x[0] // max(20, median_width),
+ x[1],
+ ),
+ )
+ block_bboxes = np.array(block_bboxes)
+ sorted_indices, segment_ids = sort_by_xycut(
+ block_bboxes, direction=1, min_gap=1
+ )
+ # get index
+ sorted_boxes = block_bboxes[sorted_indices].tolist()
+ for block in parsing_res_by_pre_cuts:
+ block["index"] = (
+ num_index + sorted_boxes.index(block["block_bbox"]) + 1
+ )
+ block["sub_index"] = (
+ num_sub_index + sorted_boxes.index(block["block_bbox"]) + 1
+ )
+
+ def nearest_match_(
+ input_blocks, distance_type="manhattan", is_add_index=True
+ ):
+ for block in input_blocks:
+ bbox = block["block_bbox"]
+ min_distance = float("inf")
+ min_distance_config = [
+ [float("inf"), float("inf")],
+ float("inf"),
+ float("inf"),
+ ] # for double text
+ nearest_gt_index = 0
+ for match_block in parsing_res_by_pre_cuts:
+ match_bbox = match_block["block_bbox"]
+ if distance_type == "nearest_iou_edge_distance":
+ distance, min_distance_config = _nearest_iou_edge_distance(
+ bbox,
+ match_bbox,
+ block["sub_label"],
+ vision_labels=vision_labels,
+ no_mask_labels=no_mask_labels,
+ median_width=median_width,
+ title_labels=title_labels,
+ title_text=block["title_text"],
+ sub_title=block["sub_title"],
+ min_distance_config=min_distance_config,
+ tolerance_len=10,
+ )
+ elif distance_type == "title_text":
+ if (
+ match_block["block_label"]
+ in title_labels + ["abstract"]
+ and match_block["title_text"] != []
+ ):
+ iou_left_up = (
+ _calculate_overlap_area_div_minbox_area_ratio(
+ bbox,
+ match_block["title_text"][0][1],
+ )
+ )
+ iou_right_down = (
+ _calculate_overlap_area_div_minbox_area_ratio(
+ bbox,
+ match_block["title_text"][-1][1],
+ )
+ )
+ iou = 1 - max(iou_left_up, iou_right_down)
+ distance = _manhattan_distance(bbox, match_bbox) * iou
+ else:
+ distance = float("inf")
+ elif distance_type == "manhattan":
+ distance = _manhattan_distance(bbox, match_bbox)
+ elif distance_type == "vision_footnote":
+ if (
+ match_block["block_label"] in vision_labels
+ and match_block["vision_footnote"] != []
+ ):
+ iou_left_up = (
+ _calculate_overlap_area_div_minbox_area_ratio(
+ bbox,
+ match_block["vision_footnote"][0],
+ )
+ )
+ iou_right_down = (
+ _calculate_overlap_area_div_minbox_area_ratio(
+ bbox,
+ match_block["vision_footnote"][-1],
+ )
+ )
+ iou = 1 - max(iou_left_up, iou_right_down)
+ distance = _manhattan_distance(bbox, match_bbox) * iou
+ else:
+ distance = float("inf")
+ elif distance_type == "vision_body":
+ if (
+ match_block["block_label"] in vision_title_labels
+ and block["vision_footnote"] != []
+ ):
+ iou_left_up = (
+ _calculate_overlap_area_div_minbox_area_ratio(
+ match_bbox,
+ block["vision_footnote"][0],
+ )
+ )
+ iou_right_down = (
+ _calculate_overlap_area_div_minbox_area_ratio(
+ match_bbox,
+ block["vision_footnote"][-1],
+ )
+ )
+ iou = 1 - max(iou_left_up, iou_right_down)
+ distance = _manhattan_distance(bbox, match_bbox) * iou
+ else:
+ distance = float("inf")
+ else:
+ raise NotImplementedError
+
+ if distance < min_distance:
+ min_distance = distance
+ if is_add_index:
+ nearest_gt_index = match_block.get("index", 999)
+ else:
+ nearest_gt_index = match_block.get("sub_index", 999)
+
+ if is_add_index:
+ block["index"] = nearest_gt_index
+ else:
+ block["sub_index"] = nearest_gt_index
+
+ parsing_res_by_pre_cuts.append(block)
+
+ if is_add_cmm and is_single_stage == False:
+ # label:double layout text
+ double_text_blocks.sort(
+ key=lambda x: (
+ x["block_bbox"][1] // 10,
+ x["block_bbox"][0] // median_width,
+ x["block_bbox"][1] ** 2 + x["block_bbox"][0] ** 2,
+ ),
+ )
+ nearest_match_(
+ double_text_blocks,
+ distance_type="nearest_iou_edge_distance",
+ )
+ # parsing_res_by_pre_cuts.sort(
+ # key=lambda x: (
+ # x["index"],
+ # x["block_bbox"][1],
+ # x["block_bbox"][0],
+ # ),
+ # )
+ parsing_res_by_pre_cuts = _projection_index_xy(parsing_res_by_pre_cuts)
+
+ for idx, block in enumerate(parsing_res_by_pre_cuts):
+ block["index"] = num_index + idx + 1
+ block["sub_index"] = num_sub_index + idx + 1
+
+ # label:doc_title , paragraph_title
+ title_blocks.sort(
+ key=lambda x: (
+ x["block_bbox"][1],
+ x["block_bbox"][0] // median_width,
+ x["block_bbox"][1] ** 2 + x["block_bbox"][0] ** 2,
+ ),
+ )
+
+ nearest_match_(title_blocks, distance_type="nearest_iou_edge_distance")
+
+ if doc_flag:
+ text_sort_labels = ["doc_title"]
+ text_label_priority = {
+ label: priority
+ for priority, label in enumerate(text_sort_labels)
+ }
+ doc_titles = []
+ for i, block in enumerate(parsing_res_by_pre_cuts):
+ if block["block_label"] == "doc_title":
+ doc_titles.append(
+ (
+ i,
+ block["block_bbox"][1],
+ block["block_bbox"][0],
+ ),
+ )
+ doc_titles.sort(key=lambda x: (x[1], x[2]))
+ first_doc_title_index = doc_titles[0][0]
+ parsing_res_by_pre_cuts[first_doc_title_index]["index"] = 1
+ parsing_res_by_pre_cuts.sort(
+ key=lambda x: (
+ x["index"],
+ text_label_priority.get(x["block_label"], 9999),
+ x["block_bbox"][1],
+ x["block_bbox"][0],
+ ),
+ )
+ # parsing_res_by_pre_cuts = _projection_index_xy(
+ # parsing_res_by_pre_cuts
+ # )
+ else:
+ parsing_res_by_pre_cuts = _projection_index_xy(
+ parsing_res_by_pre_cuts
+ )
+
+ for idx, block in enumerate(parsing_res_by_pre_cuts):
+ block["index"] = num_index + idx + 1
+ block["sub_index"] = num_sub_index + idx + 1
+
+ # label:other layout text
+ # other_text_blocks.sort(
+ # key=lambda x: (
+ # x["block_bbox"][1] // 10,
+ # x["block_bbox"][0] // median_width,
+ # x["block_bbox"][1] ** 2 + x["block_bbox"][0] ** 2,
+ # ),
+ # )
+ # nearest_match_(
+ # other_text_blocks,
+ # distance_type="nearest_iou_edge_distance",
+ # )
+ # # parsing_res_by_pre_cuts.sort(
+ # # key=lambda x: (
+ # # x["index"],
+ # # x["block_bbox"][1],
+ # # x["block_bbox"][0],
+ # # ),
+ # # )
+ # parsing_res_by_pre_cuts = custom_sort_key(parsing_res_by_pre_cuts)
+
+ # for idx, block in enumerate(parsing_res_by_pre_cuts):
+ # block["index"] = num_index + idx + 1
+ # block["sub_index"] = num_sub_index + idx + 1
+
+ # label:title-text
+ nearest_match_(title_text_blocks, distance_type="title_text")
+
+ def hor_tb_and_ver_lr(x, label):
+ input_bbox = x["block_bbox"]
+ is_horizontal = _get_bbox_direction(input_bbox)
+
+ if is_horizontal:
+ return input_bbox[1]
+ else:
+ return -1 if label == "doc_title" else input_bbox[0]
+
+ parsing_res_by_pre_cuts.sort(
+ key=lambda x: (
+ x["index"],
+ hor_tb_and_ver_lr(x, x["block_label"]),
+ ),
+ )
+
+ for idx, block in enumerate(parsing_res_by_pre_cuts):
+ block["index"] = num_index + idx + 1
+ block["sub_index"] = num_sub_index + idx + 1
+
+ # label:image,figure,chart,seal
+ nearest_match_(
+ vision_blocks,
+ distance_type="nearest_iou_edge_distance",
+ is_add_index=False,
+ )
+ parsing_res_by_pre_cuts.sort(
+ key=lambda x: (
+ x["sub_index"],
+ x["block_bbox"][1],
+ x["block_bbox"][0],
+ ),
+ )
+
+ for idx, block in enumerate(parsing_res_by_pre_cuts):
+ block["sub_index"] = num_sub_index + idx + 1
+
+ # label:image,figure,chart,seal title
+ nearest_match_(
+ vision_title_blocks,
+ distance_type="nearest_iou_edge_distance",
+ is_add_index=False,
+ )
+ parsing_res_by_pre_cuts.sort(
+ key=lambda x: (
+ x["sub_index"],
+ x["block_bbox"][1],
+ x["block_bbox"][0],
+ ),
+ )
+
+ for idx, block in enumerate(parsing_res_by_pre_cuts):
+ block["sub_index"] = num_sub_index + idx + 1
+
+ # label:vision footnote
+ nearest_match_(
+ vision_footnote_blocks,
+ distance_type="vision_footnote",
+ is_add_index=False,
+ )
+ text_label_priority = {"vision_footnote": 9999}
+ parsing_res_by_pre_cuts.sort(
+ key=lambda x: (
+ x["sub_index"],
+ text_label_priority.get(x["sub_label"], 0),
+ x["block_bbox"][1],
+ x["block_bbox"][0],
+ ),
+ )
+
+ for idx, block in enumerate(parsing_res_by_pre_cuts):
+ block["sub_index"] = num_sub_index + idx + 1
+
+ # label:header、footnote、header_image...
+ nearest_match_(
+ other_blocks, distance_type="manhattan", is_add_index=False
+ )
+
+ # use mask and (mgs) and (no cmm or is_single_stage=True)
+ else:
+ if is_add_mgs:
+ all_blocks = double_text_blocks + title_text_blocks + title_blocks
+ else:
+ all_blocks = other_blocks
+
+ if is_add_cmm and is_single_stage:
+ nearest_match_(
+ all_blocks,
+ distance_type="nearest_iou_edge_distance",
+ is_add_index=True,
+ )
+ else:
+ nearest_match_(
+ all_blocks,
+ distance_type="manhattan",
+ is_add_index=True,
+ )
+
+ parsing_res_by_pre_cuts.sort(
+ key=lambda x: (
+ x["index"],
+ x["block_bbox"][1],
+ x["block_bbox"][0],
+ ),
+ )
+
+ for idx, block in enumerate(parsing_res_by_pre_cuts):
+ block["index"] = num_index + idx + 1
+ block["sub_index"] = num_sub_index + idx + 1
+
+ # only xycut:baseline
+ else:
+ if len(parsing_res_by_pre_cuts) > 0:
+ block_bboxes = [
+ block["block_bbox"] for block in parsing_res_by_pre_cuts
+ ]
+ block_bboxes = np.array(block_bboxes)
+ sorted_indices, segment_ids = sort_by_xycut(
+ block_bboxes, direction=1, min_gap=1
+ )
+
+ sorted_boxes = block_bboxes[sorted_indices].tolist()
+
+ for block in parsing_res_by_pre_cuts:
+ block["index"] = (
+ num_index + sorted_boxes.index(block["block_bbox"]) + 1
+ )
+ block["sub_index"] = (
+ num_sub_index + sorted_boxes.index(block["block_bbox"]) + 1
+ )
+
+ if page_first_doc_title == False and doc_flag:
+ page_first_doc_title = True
+ if pre_cuts.get("x") != None and sub_page_idx != 0:
+ init_idx = 0
+ parsing_res_by_pre_cuts.sort(key=lambda x: x.get("index", 999))
+ for i in range(
+ min(len(parsing_res_by_pre_cuts), 3)
+ ): # doc title,title_text,title_text
+ if parsing_res_by_pre_cuts[i]["sub_label"] in [
+ "doc_title",
+ "title_text",
+ ]:
+ parsing_res_by_pre_cuts[i]["index"] = init_idx
+ parsing_res_by_pre_cuts[i]["sub_index"] = init_idx
+ init_idx += 0.01
+
+ # add all parsing result
+ final_parsing_res_list.extend(parsing_res_by_pre_cuts)
+
+ # update num index
+ num_sub_index += len(parsing_res_by_pre_cuts)
+ for parsing_res in parsing_res_by_pre_cuts:
+ if parsing_res.get("index"):
+ num_index += 1
+
+ final_parsing_res_list.sort(key=lambda x: (x["sub_index"]))
+ index = 1
+ for idx, block in enumerate(final_parsing_res_list):
+ if block.get("index"):
+ block["index"] = index
+ index += 1
+ block["sub_index"] = idx + 1
+
+ parsing_res_list = [
+ {
+ "block_label": parsing_res["block_label"],
+ "block_content": parsing_res["block_content"],
+ "block_bbox": parsing_res["block_bbox"],
+ "block_image": parsing_res.get("block_image", None),
+ "seg_start_flag": parsing_res["seg_start_flag"],
+ "seg_end_flag": parsing_res["seg_end_flag"],
+ "sub_label": parsing_res["sub_label"],
+ "sub_index": parsing_res["sub_index"],
+ "index": parsing_res.get("index", None),
+ }
+ for parsing_res in final_parsing_res_list
+ ]
+
+ return parsing_res_list
+
+
+def _manhattan_distance(
+ point1: Tuple[float, float],
+ point2: Tuple[float, float],
+ weight_x: float = 1.0,
+ weight_y: float = 1.0,
+) -> float:
+ """
+ Calculate the weighted Manhattan distance between two points.
+
+ Args:
+ point1 (Tuple[float, float]): The first point as (x, y).
+ point2 (Tuple[float, float]): The second point as (x, y).
+ weight_x (float): The weight for the x-axis distance. Default is 1.0.
+ weight_y (float): The weight for the y-axis distance. Default is 1.0.
+
+ Returns:
+ float: The weighted Manhattan distance between the two points.
+ """
+ return weight_x * abs(point1[0] - point2[0]) + weight_y * abs(point1[1] - point2[1])
+
+
+def _nearest_edge_distance(
+ input_bbox: List[int],
+ match_bbox: List[int],
+ weight: List[float] = [1.0, 1.0, 1.0, 1.0],
+ label: str = "text",
+ no_mask_labels: List[str] = [],
+ min_edge_distance_config: List[float] = [],
+ tolerance_len: float = 10.0,
+) -> Tuple[float, List[float]]:
+ """
+ Calculate the nearest edge distance between two bounding boxes, considering directional weights.
+
+ Args:
+ input_bbox (list): The bounding box coordinates [x1, y1, x2, y2] of the input object.
+ match_bbox (list): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
+ weight (list, optional): Directional weights for the edge distances [left, right, up, down]. Defaults to [1, 1, 1, 1].
+ label (str, optional): The label/type of the object in the bounding box (e.g., 'text'). Defaults to 'text'.
+ no_mask_labels (list, optional): Labels for which no masking is applied when calculating edge distances. Defaults to an empty list.
+ min_edge_distance_config (list, optional): Configuration for minimum edge distances [min_edge_distance_x, min_edge_distance_y].
+ Defaults to [float('inf'), float('inf')].
+ tolerance_len (float, optional): The tolerance length for adjusting edge distances. Defaults to 10.
+
+ Returns:
+ Tuple[float, List[float]]: A tuple containing:
+ - The calculated minimum edge distance between the bounding boxes.
+ - A list with the minimum edge distances in the x and y directions.
+ """
+ match_bbox_iou = _calculate_overlap_area_div_minbox_area_ratio(
+ input_bbox,
+ match_bbox,
+ )
+ if match_bbox_iou > 0 and label not in no_mask_labels:
+ return 0, [0, 0]
+
+ if not min_edge_distance_config:
+ min_edge_distance_config = [float("inf"), float("inf")]
+ min_edge_distance_x, min_edge_distance_y = min_edge_distance_config
+
+ x1, y1, x2, y2 = input_bbox
+ x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
+
+ direction_num = 0
+ distance_x = float("inf")
+ distance_y = float("inf")
+ distance = [float("inf")] * 4
+
+ # input_bbox is to the left of match_bbox
+ if x2 <= x1_prime:
+ direction_num += 1
+ distance[0] = x1_prime - x2
+ if abs(distance[0] - min_edge_distance_x) <= tolerance_len:
+ distance_x = min_edge_distance_x * weight[0]
+ else:
+ distance_x = distance[0] * weight[0]
+ # input_bbox is to the right of match_bbox
+ elif x1 >= x2_prime:
+ direction_num += 1
+ distance[1] = x1 - x2_prime
+ if abs(distance[1] - min_edge_distance_x) <= tolerance_len:
+ distance_x = min_edge_distance_x * weight[1]
+ else:
+ distance_x = distance[1] * weight[1]
+ elif match_bbox_iou > 0:
+ distance[0] = 0
+ distance_x = 0
+
+ # input_bbox is above match_bbox
+ if y2 <= y1_prime:
+ direction_num += 1
+ distance[2] = y1_prime - y2
+ if abs(distance[2] - min_edge_distance_y) <= tolerance_len:
+ distance_y = min_edge_distance_y * weight[2]
+ else:
+ distance_y = distance[2] * weight[2]
+ if label in no_mask_labels:
+ distance_y = max(0.1, distance_y) * 10 # for abstract
+ # input_bbox is below match_bbox
+ elif y1 >= y2_prime:
+ direction_num += 1
+ distance[3] = y1 - y2_prime
+ if abs(distance[3] - min_edge_distance_y) <= tolerance_len:
+ distance_y = min_edge_distance_y * weight[3]
+ else:
+ distance_y = distance[3] * weight[3]
+ elif match_bbox_iou > 0:
+ distance[2] = 0
+ distance_y = 0
+
+ if direction_num == 2:
+ return (distance_x + distance_y), [
+ min(distance[0], distance[1]),
+ min(distance[2], distance[3]),
+ ]
+ else:
+ return min(distance_x, distance_y), [
+ min(distance[0], distance[1]),
+ min(distance[2], distance[3]),
+ ]
+
+
+def _get_weights(label, horizontal):
+ """Define weights based on the label and orientation."""
+ if label == "doc_title":
+ return (
+ [1, 0.1, 0.1, 1] if horizontal else [0.2, 0.1, 1, 1]
+ ) # left-down , right-left
+ elif label in [
+ "paragraph_title",
+ "table_title",
+ "abstract",
+ "image",
+ "seal",
+ "chart",
+ "figure",
+ ]:
+ return [1, 1, 0.1, 1] # down
+ else:
+ return [1, 1, 1, 0.1]
+
+
+def _nearest_iou_edge_distance(
+ input_bbox: List[int],
+ match_bbox: List[int],
+ label: str,
+ vision_labels: List[str],
+ no_mask_labels: List[str],
+ median_width: int = -1,
+ title_labels: List[str] = [],
+ title_text: List[Tuple[int, List[int]]] = [],
+ sub_title: List[List[int]] = [],
+ min_distance_config: List[float] = [],
+ tolerance_len: float = 10.0,
+) -> Tuple[float, List[float]]:
+ """
+ Calculate the nearest IOU edge distance between two bounding boxes, considering label types, title adjustments, and minimum distance configurations.
+ This function computes the edge distance between two bounding boxes while considering their overlap (IOU) and various adjustments based on label types,
+ title text, and subtitle information. It also applies minimum distance configurations and tolerance adjustments.
+
+ Args:
+ input_bbox (List[int]): The bounding box coordinates [x1, y1, x2, y2] of the input object.
+ match_bbox (List[int]): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
+ label (str): The label/type of the object in the bounding box (e.g., 'image', 'text', etc.).
+ vision_labels (List[str]): List of labels for vision-related objects (e.g., images, icons).
+ no_mask_labels (List[str]): Labels for which no masking is applied when calculating edge distances.
+ median_width (int, optional): The median width for title dispersion calculation. Defaults to -1.
+ title_labels (List[str], optional): Labels that indicate the object is a title. Defaults to an empty list.
+ title_text (List[Tuple[int, List[int]]], optional): Text content associated with title labels, in the format [(position_indicator, [x1, y1, x2, y2]), ...].
+ sub_title (List[List[int]], optional): List of subtitle bounding boxes to adjust the input_bbox. Defaults to an empty list.
+ min_distance_config (List[float], optional): Configuration for minimum distances [min_edge_distance_config, up_edge_distances_config, total_distance].
+ tolerance_len (float, optional): The tolerance length for adjusting edge distances. Defaults to 10.0.
+
+ Returns:
+ Tuple[float, List[float]]: A tuple containing:
+ - The calculated distance considering IOU and adjustments.
+ - The updated minimum distance configuration.
+ """
+
+ x1, y1, x2, y2 = input_bbox
+ x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
+
+ min_edge_distance_config, up_edge_distances_config, total_distance = (
+ min_distance_config
+ )
+
+ iou_distance = 0
+
+ if label in vision_labels:
+ horizontal1 = horizontal2 = True
+ else:
+ horizontal1 = _get_bbox_direction(input_bbox)
+ horizontal2 = _get_bbox_direction(match_bbox, 3)
+
+ if (
+ horizontal1 != horizontal2
+ or _get_projection_iou(input_bbox, match_bbox, horizontal1) < 0.01
+ ):
+ iou_distance = 1
+
+ if label == "doc_title":
+ # Calculate distance for titles
+ disperse = max(1, median_width)
+ tolerance_len = max(tolerance_len, disperse)
+
+ # Adjust input_bbox based on sub_title
+ if sub_title:
+ for sub in sub_title:
+ x1_, y1_, x2_, y2_ = sub
+ x1, y1, x2, y2 = (
+ min(x1, x1_),
+ min(y1, y1_),
+ min(x2, x2_),
+ max(y2, y2_),
+ )
+ input_bbox = [x1, y1, x2, y2]
+
+ if title_text:
+ for sub in title_text:
+ x1_, y1_, x2_, y2_ = sub[1]
+ if horizontal1:
+ x1, y1, x2, y2 = (
+ min(x1, x1_),
+ min(y1, y1_),
+ min(x2, x2_),
+ max(y2, y2_),
+ )
+ else:
+ x1, y1, x2, y2 = (
+ min(x1, x1_),
+ min(y1, y1_),
+ max(x2, x2_),
+ min(y2, y2_),
+ )
+ input_bbox = [x1, y1, x2, y2]
+
+ # Calculate edge distance
+ weight = _get_weights(label, horizontal1)
+ # static weight
+ # weight = [1.,1.,1.,1.]
+ if label == "abstract":
+ tolerance_len *= 2
+
+ edge_distance, edge_distance_config = _nearest_edge_distance(
+ input_bbox,
+ match_bbox,
+ weight,
+ label=label,
+ no_mask_labels=no_mask_labels,
+ min_edge_distance_config=min_edge_distance_config,
+ tolerance_len=tolerance_len,
+ )
+
+ # Weights for combining distances
+ iou_edge_weight = [10**8, 10**4, 1, 0.0001]
+ # static weight
+ # iou_edge_weight = [1**6,1**3,1.,1**-3]
+
+ # Calculate up and left edge distances
+ up_edge_distance = y1_prime
+ left_edge_distance = x1_prime
+ if (
+ label in no_mask_labels or label in title_labels or label in vision_labels
+ ) and y1 > y2_prime:
+ up_edge_distance = -y2_prime
+ left_edge_distance = -x2_prime
+
+ min_up_edge_distance = up_edge_distances_config
+ if abs(min_up_edge_distance - up_edge_distance) <= tolerance_len:
+ up_edge_distance = min_up_edge_distance
+
+ # Calculate total distance
+ distance = (
+ iou_distance * iou_edge_weight[0]
+ + edge_distance * iou_edge_weight[1]
+ + up_edge_distance * iou_edge_weight[2]
+ + left_edge_distance * iou_edge_weight[3]
+ )
+ # distance = iou_distance
+ # distance = edge_distance
+ # distance = up_edge_distance
+ # distance = left_edge_distance
+
+ # Update minimum distance configuration if a smaller distance is found
+ if total_distance > distance:
+ edge_distance_config = [
+ edge_distance_config[0],
+ edge_distance_config[1],
+ ]
+ min_distance_config = [
+ edge_distance_config,
+ up_edge_distance,
+ distance,
+ ]
+
+ return distance, min_distance_config
diff --git a/oxr/pipeline/assembler.py b/oxr/pipeline/assembler.py
new file mode 100644
index 0000000..87fa26a
--- /dev/null
+++ b/oxr/pipeline/assembler.py
@@ -0,0 +1,16 @@
+from typing import List
+from oxr.pipeline.models import Block
+from oxr.pipeline.postprocess.assembly_postprocess import blocks_to_markdown
+from oxr.pipeline.postprocess.formula_postprocess import space_markdown_math
+
+def assemble_markdown(pages_blocks: List[List[Block]]) -> str:
+ """Assemble all recognized blocks across all pages into a final markdown document."""
+ full_md = []
+
+ for page_num, blocks in enumerate(pages_blocks):
+ # We can add page separators or just concatenate.
+ # For now, just concatenate
+ page_md = blocks_to_markdown(blocks)
+ full_md.append(page_md)
+
+ return space_markdown_math("\n\n".join(full_md))
diff --git a/oxr/pipeline/concurrency.py b/oxr/pipeline/concurrency.py
new file mode 100644
index 0000000..81d34a9
--- /dev/null
+++ b/oxr/pipeline/concurrency.py
@@ -0,0 +1,16 @@
+import asyncio
+from collections.abc import Awaitable
+from typing import Any
+
+
+async def gather_cancel_on_error(*awaitables: Awaitable[Any]) -> list[Any]:
+ """Gather awaitables, cancelling and draining every sibling after a failure."""
+ tasks = [asyncio.ensure_future(awaitable) for awaitable in awaitables]
+ try:
+ return list(await asyncio.gather(*tasks))
+ except BaseException:
+ for task in tasks:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ raise
diff --git a/oxr/pipeline/errors.py b/oxr/pipeline/errors.py
new file mode 100644
index 0000000..69c2804
--- /dev/null
+++ b/oxr/pipeline/errors.py
@@ -0,0 +1,29 @@
+class PipelineError(RuntimeError):
+ def __init__(
+ self, message: str, status_code: int = 500, *, public_message: str | None = None,
+ ):
+ super().__init__(message)
+ self.status_code = status_code
+ # Only fixed, application-owned messages may be marked public.
+ self.public_message = public_message
+
+
+def get_public_error_message(error: Exception) -> str:
+ """Keep backend exception details out of public responses and job records."""
+ if isinstance(error, PipelineError) and error.public_message:
+ return error.public_message
+ return "Unable to process this document. Please try again later."
+
+
+def get_error_status_code(error: Exception, default: int = 500) -> int:
+ status_code = getattr(error, "status_code", None)
+ if isinstance(status_code, int):
+ return status_code
+ return default
+
+
+def format_error_message(error: Exception, fallback: str = "Unknown error") -> str:
+ message = str(error).strip()
+ if message:
+ return message
+ return fallback
diff --git a/oxr/pipeline/image_assets.py b/oxr/pipeline/image_assets.py
new file mode 100644
index 0000000..fbdec05
--- /dev/null
+++ b/oxr/pipeline/image_assets.py
@@ -0,0 +1,27 @@
+"""Request-scoped image output for the online demo; ordinary API output is unchanged."""
+
+from contextvars import ContextVar
+from dataclasses import dataclass
+from pathlib import Path
+from uuid import uuid4
+
+import cv2
+import numpy as np
+
+
+@dataclass(frozen=True)
+class ImageAssets:
+ directory: Path
+ url_prefix: str
+
+ def save(self, image: np.ndarray) -> str:
+ self.directory.mkdir(parents=True, exist_ok=True)
+ name = f"block-{uuid4().hex}.png"
+ ok, encoded = cv2.imencode(".png", image)
+ if not ok:
+ raise ValueError("Unable to encode an output image.")
+ (self.directory / name).write_bytes(encoded.tobytes())
+ return self.url_prefix.rstrip("/") + "/" + name
+
+
+image_assets: ContextVar[ImageAssets | None] = ContextVar("oxr_image_assets", default=None)
diff --git a/oxr/pipeline/layout.py b/oxr/pipeline/layout.py
new file mode 100644
index 0000000..2f09717
--- /dev/null
+++ b/oxr/pipeline/layout.py
@@ -0,0 +1,93 @@
+import asyncio
+from typing import Any, Dict, List, Optional, Sequence
+
+import numpy as np
+
+from oxr.config.settings import LayoutAnalyzeModelConfig, settings
+from oxr.model.layout_client import LayoutAnalyzeClient, layout_client
+from oxr.pipeline.concurrency import gather_cancel_on_error
+from oxr.pipeline.errors import PipelineError, format_error_message, get_error_status_code
+from oxr.pipeline.models import Block
+from oxr.pipeline.postprocess.layout_postprocess import parse_layout_batch
+
+
+async def process_layout_batch(
+ encoded_images: Sequence[bytes],
+ image_sizes: Sequence[tuple[int, int]],
+ sem: asyncio.Semaphore,
+ batch_index: int,
+ *,
+ client: LayoutAnalyzeClient,
+ config: LayoutAnalyzeModelConfig,
+) -> list[list[Block]]:
+ """Request one layout batch, retrying the entire batch when it fails."""
+ for attempt in range(config.retry_times):
+ try:
+ # Only the upstream HTTP attempt is scarce. Parsing and backoff do
+ # not occupy a layout-service permit.
+ async with sem:
+ payload = await client.request_batch(encoded_images)
+ return parse_layout_batch(
+ payload,
+ image_sizes,
+ config.score_threshold,
+ config.nms_iou_threshold,
+ )
+ except Exception as error:
+ if attempt == config.retry_times - 1:
+ message = format_error_message(error, f"Timeout after {config.timeout}s")
+ if isinstance(error, TimeoutError) and not str(error).strip():
+ message = f"Timeout after {config.timeout}s"
+ raise PipelineError(
+ f"Layout analysis failed for batch {batch_index} after "
+ f"{config.retry_times} attempts: {message}",
+ status_code=get_error_status_code(error, default=503),
+ ) from error
+ await asyncio.sleep(1)
+
+
+async def analyze_layouts(
+ images: List[np.ndarray],
+ model_options: Optional[Dict[str, Any]] = None,
+ *,
+ client: Optional[LayoutAnalyzeClient] = None,
+ config: Optional[LayoutAnalyzeModelConfig] = None,
+) -> List[List[Block]]:
+ """Analyze page layouts in concurrent, order-preserving service batches."""
+ del model_options # LayoutAnalyzeClient has a fixed structured API.
+ if not images:
+ return []
+
+ resolved_config = config or (client.config if client is not None else settings.layout_analyze_model)
+ owns_client = client is None and config is not None
+ resolved_client = client or (
+ LayoutAnalyzeClient(resolved_config) if owns_client else layout_client
+ )
+ encoded_images = resolved_client.encode_images(images)
+ image_sizes = [(int(image.shape[1]), int(image.shape[0])) for image in images]
+ batches = [
+ (
+ encoded_images[start : start + resolved_config.batch_size],
+ image_sizes[start : start + resolved_config.batch_size],
+ )
+ for start in range(0, len(images), resolved_config.batch_size)
+ ]
+ sem = asyncio.Semaphore(resolved_config.max_concurrency)
+ try:
+ batch_results = await gather_cancel_on_error(
+ *(
+ process_layout_batch(
+ batch,
+ sizes,
+ sem,
+ batch_index,
+ client=resolved_client,
+ config=resolved_config,
+ )
+ for batch_index, (batch, sizes) in enumerate(batches)
+ )
+ )
+ return [page for batch in batch_results for page in batch]
+ finally:
+ if owns_client:
+ await resolved_client.aclose()
diff --git a/oxr/pipeline/models.py b/oxr/pipeline/models.py
new file mode 100644
index 0000000..1db2e12
--- /dev/null
+++ b/oxr/pipeline/models.py
@@ -0,0 +1,34 @@
+from enum import Enum
+from dataclasses import dataclass
+
+class BlockType(str, Enum):
+ TEXT = "Text"
+ TITLE = "Title"
+ CAPTION = "Caption"
+ FOOTNOTE = "Footnote"
+ FORMULA = "Formula"
+ TABLE = "Table"
+ PICTURE = "Picture"
+ PAGE_HEADER = "Page-header"
+ PAGE_FOOTER = "Page-footer"
+ STAMP = "Stamp"
+ CHEMICAL_STRUCTURE = "Chemical Structure"
+ CODE_BLOCK = "Code Block"
+
+class ContentFormat(str, Enum):
+ TEXT = "text"
+ HTML = "html" # Table
+ LATEX = "latex" # Formula
+ MARKDOWN = "markdown"
+
+@dataclass
+class Block:
+ idx: int
+ type: BlockType
+ bbox: list[float] # [x1, y1, x2, y2] pixel coordinates
+ content: str # recognition 结果
+ format: ContentFormat
+ text_before: str = ""
+ text_after: str = ""
+ generated_role: str = ""
+ layout_score: float | None = None
diff --git a/oxr/pipeline/orchestrator.py b/oxr/pipeline/orchestrator.py
new file mode 100644
index 0000000..28790af
--- /dev/null
+++ b/oxr/pipeline/orchestrator.py
@@ -0,0 +1,301 @@
+from copy import deepcopy
+import asyncio
+import os
+import time
+import cv2
+import numpy as np
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+from oxr.config.settings import settings
+from oxr.model.client import model_client
+from oxr.utils.pdf import pdf_to_images
+from oxr.pipeline.layout import analyze_layouts
+from oxr.pipeline.concurrency import gather_cancel_on_error
+from oxr.pipeline.errors import PipelineError
+from oxr.pipeline.reading_order import resolve_reading_orders
+from oxr.pipeline.recognition import recognize_pages
+from oxr.pipeline.assembler import assemble_markdown
+from oxr.pipeline.models import Block, BlockType
+from oxr.pipeline.image_assets import ImageAssets, image_assets
+from oxr.pipeline.postprocess.assembly_postprocess import blocks_to_markdown_with_ranges
+from oxr.pipeline.postprocess.formula_postprocess import (
+ FORMULA_NUMBERING_ROLE, expand_formula_numbering_blocks, space_markdown_math,
+)
+from oxr.pipeline.postprocess.json_postprocess import serialize_final_blocks
+from oxr.pipeline.postprocess.cross_category_dedupe import (
+ dedupe_systematic_cross_category_blocks,
+)
+from oxr.pipeline.postprocess.overlap_dedupe import (
+ dedupe_visual_parents,
+ dedupe_complete_text,
+)
+from oxr.pipeline.postprocess.exact_text_dedupe import dedupe_exact_textual_blocks
+from oxr.pipeline.postprocess.full_overlap_dedupe import dedupe_full_overlaps
+from oxr.pipeline.postprocess.table_images import TABLE_IMAGE_ROLE
+
+
+INVALID_DOCUMENT_MESSAGE = "Unable to decode document into valid page images."
+
+# Internal processing policy; not configurable through YAML or environment.
+_SYSTEMATIC_CROSS_CATEGORY_DEDUPE = True
+_VISUAL_PARENT_DEDUPE = True
+_COMPLETE_TEXT_DEDUPE = True
+
+
+def _dedupe_full_page(raw: list[Block] | None, blocks: list[Block], image: np.ndarray) -> list[Block]:
+ """Keep final content witnesses for geometry and visual-coverage cleanup."""
+ if not _VISUAL_PARENT_DEDUPE or raw is None:
+ return dedupe_full_overlaps(blocks, image)
+ visual = dedupe_visual_parents(raw, blocks, image, allow_mixed_children=True)
+ final = dedupe_full_overlaps(visual, image)
+ # A visual parent's coverage proof is valid only while all witnesses survive
+ # subsequent cleanup. Recheck it and restore the original parent if needed.
+ visual_ids = {id(block) for block in visual}
+ final_ids = {id(block) for block in final}
+ recheck = [block for block in blocks if id(block) not in visual_ids or id(block) in final_ids]
+ return dedupe_visual_parents(raw, recheck, image, allow_mixed_children=True)
+
+
+def _decode_document_images(file_bytes: bytes, file_name: str) -> list[np.ndarray]:
+ ext = os.path.splitext(file_name)[1].lower()
+ try:
+ if ext == ".pdf":
+ images = pdf_to_images(file_bytes)
+ else:
+ np_arr = np.frombuffer(file_bytes, np.uint8)
+ images = [cv2.imdecode(np_arr, cv2.IMREAD_COLOR)]
+ except Exception as error:
+ raise PipelineError(
+ INVALID_DOCUMENT_MESSAGE, public_message=INVALID_DOCUMENT_MESSAGE,
+ ) from error
+
+ if not images or any(
+ not isinstance(image, np.ndarray)
+ or image.ndim not in {2, 3}
+ or image.size == 0
+ or image.shape[0] == 0
+ or image.shape[1] == 0
+ for image in images
+ ):
+ raise PipelineError(INVALID_DOCUMENT_MESSAGE, public_message=INVALID_DOCUMENT_MESSAGE)
+ return images
+
+
+async def process_document(
+ file_bytes: bytes,
+ file_name: str,
+ output_formats: list[str],
+ keep_header_footer: bool = False,
+ model_options: Optional[Dict[str, Any]] = None,
+ element_formats: Optional[Dict[str, str]] = None,
+) -> Dict[str, Any]:
+ start_time = time.perf_counter()
+ images = await asyncio.to_thread(_decode_document_images, file_bytes, file_name)
+ return await process_decoded_document(
+ images, file_name, output_formats, keep_header_footer,
+ model_options, element_formats, started_at=start_time,
+ )
+
+
+async def process_decoded_document(
+ images: list[np.ndarray],
+ file_name: str,
+ output_formats: list[str],
+ keep_header_footer: bool = False,
+ model_options: Optional[Dict[str, Any]] = None,
+ element_formats: Optional[Dict[str, str]] = None,
+ *,
+ demo: bool = False,
+ asset_dir: Optional[Path] = None,
+ asset_url_prefix: str = "",
+ started_at: Optional[float] = None,
+) -> Dict[str, Any]:
+ """Recognize already-decoded pages, optionally collecting demo source maps."""
+ assets = ImageAssets(Path(asset_dir), asset_url_prefix) if asset_dir is not None else None
+ token = image_assets.set(assets)
+ try:
+ return await _process_decoded_document(
+ images, file_name, output_formats, keep_header_footer,
+ model_options, element_formats, demo, started_at,
+ )
+ finally:
+ image_assets.reset(token)
+
+
+async def _process_decoded_document(
+ images, file_name, output_formats, keep_header_footer,
+ model_options, element_formats, demo, started_at,
+):
+ start_time = started_at if started_at is not None else time.perf_counter()
+ full_overlap_dedupe = settings.pipeline.full_overlap_dedupe
+ ext = os.path.splitext(file_name)[1].lower()
+ page_num = len(images)
+ decode_end_time = time.perf_counter()
+
+ # 2. Phase 1: Layout Analysis
+ pages_blocks = await analyze_layouts(images, model_options)
+ layout_end_time = time.perf_counter()
+ raw_pages_blocks = (
+ deepcopy(pages_blocks) if _VISUAL_PARENT_DEDUPE else None
+ )
+
+ filtered_types = {BlockType.PAGE_HEADER, BlockType.PAGE_FOOTER}
+ # Demo retains these detections for overlays only, outside recognition and RO.
+ demo_page_margins = [
+ [deepcopy(block) for block in blocks if block.type in filtered_types]
+ for blocks in pages_blocks
+ ] if demo else None
+ if demo or not keep_header_footer:
+ pages_blocks = [
+ [block for block in blocks if block.type not in filtered_types]
+ for blocks in pages_blocks
+ ]
+
+ # 3. Phase 2: Reading order and recognition share the OXR service budget.
+ semaphore = model_client.get_request_semaphore()
+ recognition_args = (
+ pages_blocks,
+ images,
+ file_name,
+ semaphore,
+ model_options,
+ element_formats,
+ )
+ if settings.layout_analyze_model.provides_reading_order:
+ pages_blocks = await recognize_pages(*recognition_args)
+ else:
+ reading_order_task = asyncio.create_task(
+ resolve_reading_orders(pages_blocks, images, semaphore)
+ )
+ recognition_task = asyncio.create_task(recognize_pages(*recognition_args))
+ reading_orders, pages_blocks = await gather_cancel_on_error(
+ reading_order_task,
+ recognition_task,
+ )
+ pages_blocks = [
+ [blocks[local_id] for local_id in order]
+ for blocks, order in zip(pages_blocks, reading_orders)
+ ]
+ recognition_end_time = time.perf_counter()
+
+ # Table pictures have already been restored (or retained in the raster
+ # fallback). Remove their top-level duplicates only after applying RO.
+ pages_blocks = [
+ [block for block in blocks if block.generated_role != TABLE_IMAGE_ROLE]
+ for blocks in pages_blocks
+ ]
+
+ if _SYSTEMATIC_CROSS_CATEGORY_DEDUPE and not full_overlap_dedupe:
+ pages_blocks = [
+ dedupe_systematic_cross_category_blocks(blocks)
+ for blocks in pages_blocks
+ ]
+ pages_blocks = [expand_formula_numbering_blocks(blocks) for blocks in pages_blocks]
+
+ # Cleanup only final blocks; recognition crops and RO inputs stay intact.
+ if full_overlap_dedupe:
+ pages_blocks = [
+ _dedupe_full_page(raw, blocks, image)
+ for raw, blocks, image in zip(
+ raw_pages_blocks or [None] * len(pages_blocks), pages_blocks, images,
+ )
+ ]
+ else:
+ if _VISUAL_PARENT_DEDUPE:
+ pages_blocks = [
+ dedupe_visual_parents(raw, blocks, image)
+ for raw, blocks, image in zip(raw_pages_blocks, pages_blocks, images)
+ ]
+ if _COMPLETE_TEXT_DEDUPE:
+ pages_blocks = [dedupe_complete_text(blocks) for blocks in pages_blocks]
+ pages_blocks = [dedupe_exact_textual_blocks(blocks) for blocks in pages_blocks]
+
+ # 4. Phase 3: Assembly & Output Formatting
+ outputs = {}
+
+ if "json" in output_formats:
+ json_pages = []
+ for i, blocks in enumerate(pages_blocks):
+ h, w = images[i].shape[:2]
+ serialized_blocks, numbering_notes = serialize_final_blocks(blocks)
+ page_data = {
+ "page_num": i,
+ "page_size": {"w": w, "h": h},
+ "merge_content_from_pre_page": False, # Basic placeholder
+ "blocks": serialized_blocks,
+ }
+ if numbering_notes:
+ page_data["unattached_formula_numbering"] = numbering_notes
+ json_pages.append(page_data)
+ outputs["json"] = {"pages": json_pages}
+
+ if "markdown" in output_formats:
+ outputs["markdown"] = assemble_markdown(pages_blocks)
+
+ end_time = time.perf_counter()
+
+ metadata = {
+ "page_num": page_num,
+ "file_type": ext,
+ "processing_time_ms": int((end_time - start_time) * 1000)
+ }
+
+ if settings.debug:
+ block_counts: Dict[str, int] = {}
+ blocks_per_page = []
+ for blocks in pages_blocks:
+ regions = [block for block in blocks if block.generated_role != FORMULA_NUMBERING_ROLE]
+ blocks_per_page.append(len(regions))
+ for block in regions:
+ block_counts[block.type.value] = block_counts.get(block.type.value, 0) + 1
+
+ metadata["debug_timing"] = {
+ "decode_time_ms": int((decode_end_time - start_time) * 1000),
+ "layout_time_ms": int((layout_end_time - decode_end_time) * 1000),
+ "recognition_time_ms": int((recognition_end_time - layout_end_time) * 1000),
+ "assembly_time_ms": int((end_time - recognition_end_time) * 1000),
+ }
+ metadata["debug_stats"] = {
+ "total_blocks": sum(blocks_per_page),
+ "blocks_per_page": blocks_per_page,
+ "block_type_counts": dict(sorted(block_counts.items())),
+ }
+
+ result = {
+ "file_name": file_name,
+ "outputs": outputs,
+ "metadata": metadata
+ }
+
+ if demo:
+ demo_pages = []
+ for i, blocks in enumerate(pages_blocks):
+ markdown, ranges = blocks_to_markdown_with_ranges(blocks)
+ # The math postprocessor adds spaces only; source line ranges remain valid.
+ markdown = space_markdown_math(markdown)
+ serialized_blocks, numbering_notes = serialize_final_blocks(blocks, ranges)
+ h, w = images[i].shape[:2]
+ # Formula expansion reindexes content blocks. Give overlay-only boxes
+ # separate IDs after those final indices without changing source maps.
+ margin_start_idx = max((b.idx for b in blocks), default=-1) + 1
+ margin_blocks = [
+ {
+ "idx": margin_start_idx + offset,
+ "type": b.type.value, "bbox": b.bbox,
+ "content": "", "format": b.format.value,
+ "start_line": None, "end_line": None,
+ }
+ for offset, b in enumerate(demo_page_margins[i])
+ ]
+ demo_page = {
+ "page_num": i,
+ "page_size": {"w": w, "h": h},
+ "markdown": markdown,
+ "blocks": sorted(serialized_blocks, key=lambda b: b["idx"]) + margin_blocks,
+ }
+ if numbering_notes:
+ demo_page["unattached_formula_numbering"] = numbering_notes
+ demo_pages.append(demo_page)
+ result["demo_pages"] = demo_pages
+ return result
diff --git a/oxr/pipeline/postprocess/__init__.py b/oxr/pipeline/postprocess/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/oxr/pipeline/postprocess/assembly_postprocess.py b/oxr/pipeline/postprocess/assembly_postprocess.py
new file mode 100644
index 0000000..6327bb9
--- /dev/null
+++ b/oxr/pipeline/postprocess/assembly_postprocess.py
@@ -0,0 +1,70 @@
+from typing import List
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.formula_postprocess import clean_formula_markdown_delimiters
+
+FORMULA_NUMBERING_ROLE = "formula_numbering"
+
+
+def _is_formula_numbering(block: Block) -> bool:
+ return getattr(block, "generated_role", "") == FORMULA_NUMBERING_ROLE
+
+
+def _use_tight_separator(previous: Block, current: Block) -> bool:
+ return (
+ previous.type == BlockType.FORMULA and _is_formula_numbering(current)
+ ) or (
+ _is_formula_numbering(previous) and current.type == BlockType.FORMULA
+ )
+
+
+def _block_to_markdown_part(block: Block, content: str) -> str:
+ if block.type == BlockType.TITLE:
+ return f"# {content}\n"
+ if block.type == BlockType.FORMULA:
+ return f"$$\n{clean_formula_markdown_delimiters(content)}\n$$\n"
+ if block.type in (
+ BlockType.TABLE,
+ BlockType.PICTURE,
+ BlockType.CODE_BLOCK,
+ BlockType.CHEMICAL_STRUCTURE,
+ ):
+ return f"{content}\n"
+ if block.type in (BlockType.PAGE_HEADER, BlockType.PAGE_FOOTER):
+ return f"*{content}*\n"
+ if block.type == BlockType.CAPTION:
+ return f"*{content}*\n"
+ if block.type == BlockType.FOOTNOTE:
+ return f"[^{block.idx}]: {content}\n"
+ return f"{content}\n"
+
+
+def blocks_to_markdown(blocks: List[Block]) -> str:
+ """Convert a list of blocks to a single markdown string."""
+ return blocks_to_markdown_with_ranges(blocks)[0]
+
+
+def blocks_to_markdown_with_ranges(blocks: List[Block]) -> tuple[str, dict[int, tuple[int, int]]]:
+ """Assemble once, retaining zero-based, end-exclusive source line ranges."""
+ md_parts = []
+ emitted_blocks = []
+ ranges = {}
+ line = 0
+
+ # Sort blocks by index just in case
+ sorted_blocks = sorted(blocks, key=lambda b: b.idx)
+
+ for block in sorted_blocks:
+ content = block.content.strip()
+ if not content:
+ continue
+
+ part = _block_to_markdown_part(block, content)
+ if md_parts and not _use_tight_separator(emitted_blocks[-1], block):
+ md_parts.append("\n")
+ line += 1
+ md_parts.append(part)
+ ranges[block.idx] = (line, line + part.count("\n"))
+ line += part.count("\n")
+ emitted_blocks.append(block)
+
+ return "".join(md_parts), ranges
diff --git a/oxr/pipeline/postprocess/chemical_structure_postprocess.py b/oxr/pipeline/postprocess/chemical_structure_postprocess.py
new file mode 100644
index 0000000..8d5aa37
--- /dev/null
+++ b/oxr/pipeline/postprocess/chemical_structure_postprocess.py
@@ -0,0 +1,35 @@
+import re
+
+from oxr.pipeline.models import Block, ContentFormat
+
+
+def _strip_wrappers(text: str) -> str:
+ text = text.strip()
+ match = re.search(r"```(?:[^\n`]*)\n(.*?)\n```", text, re.DOTALL)
+ if match:
+ text = match.group(1).strip()
+
+ math_wrappers = [
+ (r"^\$\$(.*)\$\$$", re.DOTALL),
+ (r"^\$(.*)\$$", re.DOTALL),
+ (r"^\\\[(.*)\\\]$", re.DOTALL),
+ (r"^\\\((.*)\\\)$", re.DOTALL),
+ ]
+ for pattern, flags in math_wrappers:
+ match = re.match(pattern, text, flags)
+ if match:
+ text = match.group(1).strip()
+
+ match = re.match(r"^\\smiles\{(.*)\}$", text, re.DOTALL)
+ if match:
+ text = match.group(1).strip()
+
+ return text
+
+
+def postprocess_chemical_structure(block: Block, raw_text: str) -> Block:
+ """Convert chemical structure recognition output to SoMarkDown SMILES syntax."""
+ smiles = _strip_wrappers(raw_text)
+ block.content = f"$\\smiles{{{smiles}}}$" if smiles else ""
+ block.format = ContentFormat.MARKDOWN
+ return block
diff --git a/oxr/pipeline/postprocess/code_postprocess.py b/oxr/pipeline/postprocess/code_postprocess.py
new file mode 100644
index 0000000..f62ddeb
--- /dev/null
+++ b/oxr/pipeline/postprocess/code_postprocess.py
@@ -0,0 +1,15 @@
+import re
+
+from oxr.pipeline.models import Block, ContentFormat
+
+
+def postprocess_code(block: Block, raw_text: str) -> Block:
+ """Clean code recognition output while preserving markdown code formatting."""
+ text = raw_text.strip()
+ match = re.search(r"```(?:[^\n`]*)\n(.*?)\n```", text, re.DOTALL)
+ if match:
+ text = match.group(1).strip()
+
+ block.content = f"```\n{text}\n```" if text else ""
+ block.format = ContentFormat.MARKDOWN
+ return block
diff --git a/oxr/pipeline/postprocess/cross_category_dedupe.py b/oxr/pipeline/postprocess/cross_category_dedupe.py
new file mode 100644
index 0000000..96524ec
--- /dev/null
+++ b/oxr/pipeline/postprocess/cross_category_dedupe.py
@@ -0,0 +1,76 @@
+"""Remove systematic exact Text/Formula duplicates from one page."""
+
+import re
+from collections import defaultdict
+
+from oxr.pipeline.models import Block, BlockType
+
+
+_CROSS_CATEGORY_TYPES = frozenset({BlockType.TEXT, BlockType.FORMULA})
+_OUTER_MATH_WRAPPERS = (("$$", "$$"), ("$", "$"), (r"\[", r"\]"), (r"\(", r"\)"))
+_MIN_DUPLICATE_GROUPS = 2
+_MIN_DUPLICATE_PERCENT = 10
+
+
+def normalize_cross_category_content(content: str) -> str:
+ """Normalize one outer math wrapper and whitespace."""
+ normalized = content.strip()
+ for opening, closing in _OUTER_MATH_WRAPPERS:
+ if (
+ normalized.startswith(opening)
+ and normalized.endswith(closing)
+ and len(normalized) >= len(opening) + len(closing)
+ ):
+ normalized = normalized[len(opening) : -len(closing)].strip()
+ break
+ return re.sub(r"\s+", "", normalized)
+
+
+def _layout_score(block: Block) -> float:
+ return block.layout_score if block.layout_score is not None else 0.0
+
+
+def dedupe_systematic_cross_category_blocks(blocks: list[Block]) -> list[Block]:
+ """Remove dense exact Text/Formula duplicates while preserving page order."""
+ groups: dict[tuple[float, ...], list[int]] = defaultdict(list)
+ for position, block in enumerate(blocks):
+ if block.type in _CROSS_CATEGORY_TYPES:
+ groups[tuple(block.bbox)].append(position)
+
+ remove: set[int] = set()
+ duplicate_group_count = 0
+ for positions in groups.values():
+ if {blocks[position].type for position in positions} != _CROSS_CATEGORY_TYPES:
+ continue
+
+ by_content: dict[str, list[int]] = defaultdict(list)
+ for position in positions:
+ normalized = normalize_cross_category_content(blocks[position].content)
+ if normalized:
+ by_content[normalized].append(position)
+
+ for matching_positions in by_content.values():
+ if len(matching_positions) < 2:
+ continue
+ if {
+ blocks[position].type for position in matching_positions
+ } != _CROSS_CATEGORY_TYPES:
+ continue
+
+ kept_position = max(
+ matching_positions,
+ key=lambda position: (_layout_score(blocks[position]), -position),
+ )
+ remove.update(
+ position for position in matching_positions if position != kept_position
+ )
+ duplicate_group_count += 1
+
+ content_count = sum(block.type in _CROSS_CATEGORY_TYPES for block in blocks)
+ systematic = (
+ duplicate_group_count >= _MIN_DUPLICATE_GROUPS
+ and len(remove) * 100 >= content_count * _MIN_DUPLICATE_PERCENT
+ )
+ if not remove or not systematic:
+ return blocks
+ return [block for position, block in enumerate(blocks) if position not in remove]
diff --git a/oxr/pipeline/postprocess/exact_text_dedupe.py b/oxr/pipeline/postprocess/exact_text_dedupe.py
new file mode 100644
index 0000000..62c5979
--- /dev/null
+++ b/oxr/pipeline/postprocess/exact_text_dedupe.py
@@ -0,0 +1,58 @@
+"""Remove exact cross-category duplicates of recognized textual blocks."""
+
+import math
+from collections import defaultdict
+
+from oxr.pipeline.models import Block, BlockType
+
+
+_TEXTUAL_TYPES = frozenset({BlockType.TEXT, BlockType.CAPTION, BlockType.TITLE})
+
+
+def dedupe_exact_textual_blocks(blocks: list[Block]) -> list[Block]:
+ """Keep the highest-confidence block without changing its fields or order.
+
+ Require identical geometry, original text and assembly fields, one block
+ per category, and finite confidence for every member of the group.
+ """
+ groups: dict[tuple[object, ...], list[int]] = defaultdict(list)
+ for position, block in enumerate(blocks):
+ if block.type not in _TEXTUAL_TYPES:
+ continue
+ if not isinstance(block.content, str) or not block.content.strip():
+ continue
+ box = block.bbox
+ if not isinstance(box, (list, tuple)) or len(box) != 4:
+ continue
+ if any(not isinstance(value, (int, float)) or not math.isfinite(value) for value in box):
+ continue
+ if box[2] <= box[0] or box[3] <= box[1]:
+ continue
+ key = (
+ tuple(box), block.content, block.format,
+ block.text_before, block.text_after, block.generated_role,
+ )
+ groups[key].append(position)
+
+ removed: set[int] = set()
+ for positions in groups.values():
+ categories = {blocks[position].type for position in positions}
+ if len(categories) < 2 or len(categories) != len(positions):
+ continue
+ scores = [blocks[position].layout_score for position in positions]
+ if any(
+ not isinstance(score, (int, float))
+ or isinstance(score, bool)
+ or not math.isfinite(score)
+ for score in scores
+ ):
+ continue
+ winner = max(
+ positions,
+ key=lambda position: (blocks[position].layout_score, -position),
+ )
+ removed.update(position for position in positions if position != winner)
+
+ if not removed:
+ return blocks
+ return [block for position, block in enumerate(blocks) if position not in removed]
diff --git a/oxr/pipeline/postprocess/formula_postprocess.py b/oxr/pipeline/postprocess/formula_postprocess.py
new file mode 100644
index 0000000..29124e7
--- /dev/null
+++ b/oxr/pipeline/postprocess/formula_postprocess.py
@@ -0,0 +1,486 @@
+import re
+
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+
+FORMULA_NUMBERING_ROLE = "formula_numbering"
+_TEXT_COMMANDS = {
+ "text",
+ "textrm",
+ "textnormal",
+ "textbf",
+ "textit",
+ "mbox",
+ "hbox",
+ "verb",
+}
+_LATEX_COMMAND = re.compile(r"\\(?:[A-Za-z]+|.)", re.DOTALL)
+_MARKDOWN_CODE = re.compile(r"(?P<ticks>`+)[\s\S]*?(?P=ticks)|~~~[\s\S]*?~~~")
+_HTML_COMMENT = re.compile(r"<!--[\s\S]*?(?:-->|\Z)")
+_HTML_TAG = re.compile(
+ r"</?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*)?/?>"
+ r"|<![A-Z][^>]*(?:>|\Z)|<\?[^>]*(?:>|\Z)"
+)
+_HTML_ENTITY_TAG = re.compile(
+ r"&(?:lt|#0*60|#x0*3c);/?[A-Za-z][\s\S]*?"
+ r"&(?:gt|#0*62|#x0*3e);",
+ re.IGNORECASE,
+)
+
+
+def _protected_markup(text: str, index: int) -> re.Match[str] | None:
+ return (
+ _HTML_COMMENT.match(text, index)
+ or _HTML_TAG.match(text, index)
+ or _HTML_ENTITY_TAG.match(text, index)
+ )
+
+
+def _valid_math_open(text: str, index: int, width: int) -> bool:
+ if width == 2:
+ return not text.startswith("$$$", index)
+ end = index + 1
+ return end < len(text) and not text[end].isspace() and text[end] != "$"
+
+
+def _valid_math_close(text: str, index: int, width: int) -> bool:
+ if width == 2:
+ return index > 0 and not text.startswith("$$$", index)
+ return index > 0 and not text[index - 1].isspace() and not text.startswith("$$", index)
+
+
+def space_latex_row_breaks(latex: str) -> str:
+ """Separate LaTeX row breaks from an adjacent parenthesis or group brace."""
+ result: list[str] = []
+ index = 0
+ while index < len(latex):
+ if latex[index] == "%":
+ end = latex.find("\n", index)
+ end = len(latex) if end < 0 else end
+ result.append(latex[index:end])
+ index = end
+ continue
+
+ match = _LATEX_COMMAND.match(latex, index)
+ if not match:
+ result.append(latex[index])
+ index += 1
+ continue
+
+ command = match.group()
+ end = match.end()
+ if command[1:] in _TEXT_COMMANDS:
+ cursor = end
+ while cursor < len(latex) and latex[cursor].isspace():
+ cursor += 1
+ if cursor < len(latex) and latex[cursor] == "{":
+ depth = 1
+ cursor += 1
+ while cursor < len(latex) and depth:
+ escaped = _LATEX_COMMAND.match(latex, cursor)
+ if escaped:
+ cursor = escaped.end()
+ continue
+ if latex[cursor] == "{":
+ depth += 1
+ elif latex[cursor] == "}":
+ depth -= 1
+ cursor += 1
+ if depth:
+ return latex
+ end = cursor
+
+ result.append(latex[index:end])
+ if command == r"\\" and end < len(latex) and latex[end] in "(){}":
+ result.append(" ")
+ index = end
+
+ return "".join(result)
+
+
+def space_markdown_math(markdown: str) -> str:
+ """Apply row-break spacing only inside complete dollar-delimited math."""
+ result: list[str] = []
+ index = 0
+ while index < len(markdown):
+ code = _MARKDOWN_CODE.match(markdown, index)
+ if code:
+ result.append(code.group())
+ index = code.end()
+ continue
+ html = _protected_markup(markdown, index)
+ if html:
+ result.append(html.group())
+ index = html.end()
+ continue
+ if markdown[index] != "$" or _is_escaped(markdown, index):
+ result.append(markdown[index])
+ index += 1
+ continue
+
+ width = 2 if markdown.startswith("$$", index) else 1
+ if not _valid_math_open(markdown, index, width):
+ result.append(markdown[index : index + width])
+ index += width
+ continue
+
+ cursor = index + width
+ end = None
+ while cursor < len(markdown):
+ if _MARKDOWN_CODE.match(markdown, cursor) or _protected_markup(markdown, cursor):
+ break
+ if markdown[cursor] == "$" and not _is_escaped(markdown, cursor):
+ found_width = 2 if markdown.startswith("$$", cursor) else 1
+ if (
+ found_width == width
+ and _valid_math_close(markdown, cursor, width)
+ ):
+ end = cursor
+ break
+ cursor += 1
+
+ if end is None:
+ result.append(markdown[index : index + width])
+ index += width
+ continue
+
+ delimiter = "$" * width
+ result.append(
+ delimiter
+ + space_latex_row_breaks(markdown[index + width : end])
+ + delimiter
+ )
+ index = end + width
+
+ return "".join(result)
+
+
+def _parse_braced_group(text: str, open_index: int) -> tuple[str, int] | None:
+ if open_index >= len(text) or text[open_index] != "{":
+ return None
+
+ depth = 1
+ index = open_index + 1
+ while index < len(text):
+ char = text[index]
+ if char == "\\":
+ index += 2
+ continue
+ if char == "{":
+ depth += 1
+ elif char == "}":
+ depth -= 1
+ if depth == 0:
+ return text[open_index + 1:index], index + 1
+ index += 1
+
+ return None
+
+
+def _has_command_boundary(text: str, index: int) -> bool:
+ return index >= len(text) or not text[index].isalpha()
+
+
+def _numbering_command_at(text: str, index: int) -> str | None:
+ if text.startswith(r"\tag*", index) and _has_command_boundary(text, index + len(r"\tag*")):
+ return "tag*"
+ if text.startswith(r"\tag", index) and _has_command_boundary(text, index + len(r"\tag")):
+ return "tag"
+ if text.startswith(r"\leqno", index) and _has_command_boundary(text, index + len(r"\leqno")):
+ return "leqno"
+ if text.startswith(r"\eqno", index) and _has_command_boundary(text, index + len(r"\eqno")):
+ return "eqno"
+ return None
+
+
+def _find_next_numbering_command(text: str, start: int) -> int:
+ index = start
+ while index < len(text):
+ if _numbering_command_at(text, index):
+ return index
+ index += 1
+ return len(text)
+
+
+def _append_numbering(target: list[str], value: str) -> None:
+ value = value.strip()
+ if value:
+ target.append(value)
+
+
+def _extract_formula_numbering(text: str) -> tuple[str, str, str]:
+ formula_parts: list[str] = []
+ before_numbers: list[str] = []
+ after_numbers: list[str] = []
+ index = 0
+
+ while index < len(text):
+ command = _numbering_command_at(text, index)
+ if command in {"tag", "tag*"}:
+ command_end = index + len(r"\tag*") if command == "tag*" else index + len(r"\tag")
+ group_start = command_end
+ while group_start < len(text) and text[group_start].isspace():
+ group_start += 1
+
+ parsed = _parse_braced_group(text, group_start)
+ if parsed is None:
+ formula_parts.append(text[index])
+ index += 1
+ continue
+
+ number_text, index = parsed
+ number_text = number_text.strip()
+ if command == "tag":
+ _append_numbering(after_numbers, f"({number_text})")
+ else:
+ _append_numbering(after_numbers, number_text)
+ continue
+
+ if command in {"eqno", "leqno"}:
+ command_end = index + len(r"\leqno") if command == "leqno" else index + len(r"\eqno")
+ number_start = command_end
+ while number_start < len(text) and text[number_start].isspace():
+ number_start += 1
+ number_end = _find_next_numbering_command(text, number_start)
+ number_text = text[number_start:number_end].strip()
+ if command == "leqno":
+ _append_numbering(before_numbers, number_text)
+ else:
+ _append_numbering(after_numbers, number_text)
+ index = number_end
+ continue
+
+ formula_parts.append(text[index])
+ index += 1
+
+ return "".join(formula_parts).strip(), " ".join(before_numbers), " ".join(after_numbers)
+
+
+def _is_escaped(text: str, index: int) -> bool:
+ slash_count = 0
+ cursor = index - 1
+ while cursor >= 0 and text[cursor] == "\\":
+ slash_count += 1
+ cursor -= 1
+ return slash_count % 2 == 1
+
+
+def clean_formula_markdown_delimiters(latex: str) -> str:
+ """Normalize clear wrapper/seam dollars in a Markdown-only formula copy.
+
+ Leave mixed prose, incomplete math, text commands, escaped currency, and
+ comments intact. Never modify recognized blocks or infer formula numbers.
+ """
+ dollars = []
+ visible = []
+ depth = 0
+ index = 0
+ while index < len(latex):
+ if latex[index] == "%":
+ end = latex.find("\n", index)
+ index = len(latex) if end < 0 else end
+ continue
+ command = _LATEX_COMMAND.match(latex, index)
+ if command:
+ index = command.end()
+ if command.group()[1:] in _TEXT_COMMANDS:
+ if command.group()[1:] == "verb":
+ return latex
+ cursor = index
+ while cursor < len(latex) and latex[cursor].isspace():
+ cursor += 1
+ group = _parse_braced_group(latex, cursor)
+ if group is None:
+ return latex
+ index = group[1]
+ visible.append(" ")
+ continue
+ char = latex[index]
+ if char == "{":
+ depth += 1
+ elif char == "}":
+ depth -= 1
+ if depth < 0:
+ return latex
+ elif char == "$":
+ if depth or latex.startswith("$$", index) or (index and latex[index - 1] == "$"):
+ return latex
+ dollars.append(index)
+ visible.append(char)
+ index += 1
+
+ if depth or not dollars:
+ return latex
+ prose = "".join(visible)
+ if "`" in prose or re.search(r"[\u3400-\u9fff]|\b[A-Za-z]{2,}\s+[A-Za-z]{2,}\b", prose):
+ return latex
+ wrapper = len(dollars) == 2 and dollars == [0, len(latex) - 1]
+ seams = len(dollars) % 2 == 0 and all(
+ latex[start + 1:end].isspace()
+ for start, end in zip(dollars[::2], dollars[1::2])
+ )
+ if not wrapper and not seams:
+ return latex
+ if wrapper:
+ return latex[1:-1]
+ operators = ("=", "+", "-", "*", "/", "<", ">")
+ # Only join explicit continuations; preserve independent or unclear rows.
+ if not all(
+ latex[:start].rstrip().endswith(operators)
+ or latex[end + 1:].lstrip().startswith(operators)
+ for start, end in zip(dollars[::2], dollars[1::2])
+ ):
+ return latex
+ parts = []
+ cursor = 0
+ for start, end in zip(dollars[::2], dollars[1::2]):
+ parts.extend((latex[cursor:start], latex[start + 1:end]))
+ cursor = end + 1
+ parts.append(latex[cursor:])
+ return "".join(parts)
+
+
+def _find_unescaped(text: str, marker: str, start: int) -> int:
+ index = start
+ while True:
+ index = text.find(marker, index)
+ if index == -1:
+ return -1
+ if not _is_escaped(text, index):
+ return index
+ index += len(marker)
+
+
+def _format_numbered_math(
+ open_marker: str,
+ formula: str,
+ close_marker: str,
+ before: str,
+ after: str,
+) -> str:
+ parts = []
+ if before:
+ parts.append(before)
+ parts.append(f"{open_marker}{formula}{close_marker}")
+ if after:
+ parts.append(after)
+ return " ".join(parts)
+
+
+def _rewrite_numbered_math_range(
+ open_marker: str,
+ formula: str,
+ close_marker: str,
+) -> str:
+ cleaned_formula, before, after = _extract_formula_numbering(formula)
+ if not before and not after:
+ return f"{open_marker}{formula}{close_marker}"
+ return _format_numbered_math(open_marker, cleaned_formula, close_marker, before, after)
+
+
+def move_formula_numbering_outside_math(text: str) -> str:
+ result = []
+ index = 0
+
+ while index < len(text):
+ if text.startswith(r"\[", index):
+ close_index = text.find(r"\]", index + 2)
+ if close_index != -1:
+ formula = text[index + 2 : close_index]
+ result.append(_rewrite_numbered_math_range(r"\[", formula, r"\]"))
+ index = close_index + 2
+ continue
+
+ if text.startswith(r"\(", index):
+ close_index = text.find(r"\)", index + 2)
+ if close_index != -1:
+ formula = text[index + 2 : close_index]
+ result.append(_rewrite_numbered_math_range(r"\(", formula, r"\)"))
+ index = close_index + 2
+ continue
+
+ if text.startswith("$$", index) and not _is_escaped(text, index):
+ close_index = _find_unescaped(text, "$$", index + 2)
+ if close_index != -1:
+ formula = text[index + 2 : close_index]
+ result.append(_rewrite_numbered_math_range("$$", formula, "$$"))
+ index = close_index + 2
+ continue
+
+ if text[index] == "$" and not _is_escaped(text, index):
+ close_index = _find_unescaped(text, "$", index + 1)
+ if close_index != -1:
+ formula = text[index + 1 : close_index]
+ result.append(_rewrite_numbered_math_range("$", formula, "$"))
+ index = close_index + 1
+ continue
+
+ result.append(text[index])
+ index += 1
+
+ return "".join(result)
+
+
+def _numbering_text_block(source: Block, content: str) -> Block:
+ return Block(
+ idx=source.idx,
+ type=BlockType.TEXT,
+ bbox=list(source.bbox),
+ content=content,
+ format=ContentFormat.TEXT,
+ generated_role=FORMULA_NUMBERING_ROLE,
+ )
+
+
+def expand_formula_numbering_blocks(blocks: list[Block]) -> list[Block]:
+ expanded: list[Block] = []
+ for block in blocks:
+ if block.type != BlockType.FORMULA:
+ expanded.append(block)
+ continue
+
+ text_before = getattr(block, "text_before", "").strip()
+ text_after = getattr(block, "text_after", "").strip()
+ if text_before:
+ expanded.append(_numbering_text_block(block, text_before))
+ expanded.append(block)
+ if text_after:
+ expanded.append(_numbering_text_block(block, text_after))
+
+ for idx, block in enumerate(expanded):
+ block.idx = idx
+ return expanded
+
+
+def postprocess_formula(block: Block, raw_text: str) -> Block:
+ """Clean up formula block output to valid LaTeX."""
+ text = raw_text.strip()
+ match = re.search(r"```latex\n(.*?)\n```", text, re.DOTALL)
+ if match:
+ text = match.group(1)
+ elif "```" in text:
+ match = re.search(r"```(?:.*?)\n(.*?)\n```", text, re.DOTALL)
+ if match:
+ text = match.group(1)
+
+ # Formula blocks store bare KaTeX/LaTeX; assembly owns display-math delimiters.
+ wrappers = [
+ r"^\$\$(.*?)\$\$$",
+ r"^\$(.*?)\$$",
+ r"^\\\[(.*?)\\\]$",
+ r"^\\\((.*?)\\\)$",
+ ]
+ for pattern in wrappers:
+ match = re.match(pattern, text, re.DOTALL)
+ if match:
+ text = match.group(1).strip()
+ break
+
+ text, text_before, text_after = _extract_formula_numbering(text)
+ text = space_latex_row_breaks(text)
+
+ block.content = text
+ block.format = ContentFormat.LATEX
+ block.text_before = text_before
+ block.text_after = text_after
+ block.generated_role = ""
+ return block
diff --git a/oxr/pipeline/postprocess/full_overlap_dedupe.py b/oxr/pipeline/postprocess/full_overlap_dedupe.py
new file mode 100644
index 0000000..36758ab
--- /dev/null
+++ b/oxr/pipeline/postprocess/full_overlap_dedupe.py
@@ -0,0 +1,232 @@
+"""Conservative containment and duplicate-overlap cleanup on one page."""
+
+import math
+import re
+
+import cv2
+import numpy as np
+
+from oxr.pipeline.models import Block, BlockType
+from oxr.pipeline.postprocess.cross_category_dedupe import normalize_cross_category_content
+from oxr.pipeline.postprocess.formula_postprocess import FORMULA_NUMBERING_ROLE
+
+
+_MIN_IOU = 0.80
+_MIN_SMALLER_COVERAGE = 0.95
+_TEXT_HEIGHT_TOLERANCE = 0.20
+_MIN_TEXT_CHILD_COVERAGE = 0.80
+_TEXTUAL_TYPES = frozenset(BlockType) - {BlockType.PICTURE, BlockType.TABLE}
+_PICTURE_TEXT_TYPES = _TEXTUAL_TYPES - {BlockType.CHEMICAL_STRUCTURE, BlockType.STAMP}
+
+
+def _unprotected_textual_pair(a: Block, b: Block) -> bool:
+ return (
+ a.type in _TEXTUAL_TYPES and b.type in _TEXTUAL_TYPES
+ and not {BlockType.CODE_BLOCK, BlockType.CHEMICAL_STRUCTURE} & {a.type, b.type}
+ and FORMULA_NUMBERING_ROLE not in {a.generated_role, b.generated_role}
+ )
+
+
+def _formula_pair(a: Block, b: Block) -> bool:
+ return _unprotected_textual_pair(a, b) and BlockType.FORMULA in {a.type, b.type}
+
+
+def _valid_box(box: list[float]) -> bool:
+ if not isinstance(box, (list, tuple)) or len(box) != 4:
+ return False
+ if any(
+ not isinstance(value, (int, float))
+ or isinstance(value, bool)
+ or not math.isfinite(value)
+ for value in box
+ ):
+ return False
+ return box[0] < box[2] and box[1] < box[3]
+
+
+def _contains(outer: list[float], inner: list[float]) -> bool:
+ return (
+ tuple(outer) != tuple(inner)
+ and outer[0] <= inner[0] and outer[1] <= inner[1]
+ and outer[2] >= inner[2] and outer[3] >= inner[3]
+ )
+
+
+def _overlaps(a: list[float], b: list[float]) -> bool:
+ intersection = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(
+ 0.0, min(a[3], b[3]) - max(a[1], b[1])
+ )
+ area_a = (a[2] - a[0]) * (a[3] - a[1])
+ area_b = (b[2] - b[0]) * (b[3] - b[1])
+ return (
+ intersection / (area_a + area_b - intersection) >= _MIN_IOU
+ and intersection / min(area_a, area_b) >= _MIN_SMALLER_COVERAGE
+ )
+
+
+def _content(block: Block) -> str:
+ text = block.text_before + block.content + block.text_after
+ if block.type == BlockType.CODE_BLOCK:
+ return text
+ text = "".join(text.split())
+ if block.type not in {BlockType.FORMULA, BlockType.TEXT}:
+ return text
+ normalized = normalize_cross_category_content(text)
+ # Only canonicalize the restricted atom/count/arrow syntax. Unknown LaTeX
+ # stays literal, so formatting differences cannot erase distinct formulas.
+ equation = re.fullmatch(r"\\ce\{([A-Za-z0-9()+\-= >]+)\}", normalized)
+ if equation:
+ chemical = equation[1]
+ else:
+ chemical = re.sub(r"\\mathrm\{([A-Za-z]+)\}", r"\1", normalized)
+ chemical = re.sub(r"_\{([0-9]+)\}", r"\1", chemical)
+ chemical = re.sub(r"\\(?:to|rightarrow)(?![A-Za-z])", "->", chemical)
+ if "->" in chemical and re.fullmatch(r"[A-Za-z0-9()+\-= >]+", chemical):
+ return chemical
+ return normalized
+
+
+def _preserves_content(winner: Block, loser: Block, image: np.ndarray | None) -> bool:
+ if loser.type == BlockType.TABLE:
+ # Geometry and a caption cannot prove that table cells/structure survive.
+ return (
+ winner.type == BlockType.TABLE
+ and bool(loser.content.strip())
+ and (winner.text_before, winner.content, winner.text_after)
+ == (loser.text_before, loser.content, loser.text_after)
+ )
+ if loser.type == BlockType.PICTURE:
+ if winner.type != BlockType.PICTURE:
+ return False
+ a, b = winner.bbox, loser.bbox
+ if a[0] <= b[0] and a[1] <= b[1] and a[2] >= b[2] and a[3] >= b[3]:
+ return True
+ # A shifted crop can lose an edge even when its area overlaps almost all
+ # of the other crop. Require source pixels to verify actual ink coverage.
+ if image is None:
+ return False
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if image.ndim == 3 else image
+ height, width = gray.shape
+ x, y, u, v = map(round, b)
+ x, y, u, v = max(0, x), max(0, y), min(width, u), min(height, v)
+ if x >= u or y >= v:
+ return False
+ ink = gray[y:v, x:u] < 200
+ covered = np.zeros(ink.shape, dtype=bool)
+ left, top, right, bottom = map(round, a)
+ left, top = max(x, left), max(y, top)
+ right, bottom = min(u, right), min(v, bottom)
+ if left < right and top < bottom:
+ covered[top - y:bottom - y, left - x:right - x] = True
+ return bool(ink.any()) and float((ink & covered).sum() / ink.sum()) >= 0.999
+ if winner.type not in _TEXTUAL_TYPES:
+ return False
+ if loser.type == BlockType.CODE_BLOCK:
+ return (
+ winner.type == BlockType.CODE_BLOCK
+ and bool(_content(loser)) and _content(loser) in _content(winner)
+ )
+ content = _content(loser)
+ retained = _content(winner)
+ return bool(content) and content in retained
+
+
+def _absorbs(parent: Block, child: Block, image: np.ndarray | None) -> bool:
+ if _contains(parent.bbox, child.bbox):
+ return _unprotected_textual_pair(parent, child) or _preserves_content(parent, child, image)
+ # Near-containment scales with the child text height. Ordinary text must
+ # prove content inclusion; formula pairs retain the formula OCR exemption.
+ if not _unprotected_textual_pair(parent, child):
+ return False
+ a, b = parent.bbox, child.bbox
+ tolerance = (b[3] - b[1]) * _TEXT_HEIGHT_TOLERANCE
+ intersection = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(
+ 0.0, min(a[3], b[3]) - max(a[1], b[1])
+ )
+ child_area = (b[2] - b[0]) * (b[3] - b[1])
+ return (
+ (a[2] - a[0]) * (a[3] - a[1]) > child_area
+ and intersection / child_area >= _MIN_TEXT_CHILD_COVERAGE
+ and a[0] - tolerance <= b[0] and a[1] - tolerance <= b[1]
+ and a[2] + tolerance >= b[2] and a[3] + tolerance >= b[3]
+ and (_formula_pair(parent, child) or _preserves_content(parent, child, image))
+ )
+
+
+def _valid_score(score: float | None) -> bool:
+ return (
+ isinstance(score, (int, float))
+ and not isinstance(score, bool)
+ and math.isfinite(score)
+ )
+
+
+def dedupe_full_overlaps(blocks: list[Block], image: np.ndarray | None = None) -> list[Block]:
+ """Keep containing boxes and suppress only near-identical intersections.
+
+ Require full containment, or IoU >= 0.80 and smaller-box coverage >= 0.95.
+ Complete textual containment skips content matching, except for chemical structures, code and
+ generated equation numbers. Near-containment requires at least 80% child
+ coverage and edge protrusion <= 20% of the child height. Ordinary text must
+ preserve content; formula pairs skip content matching and use layout
+ confidence for duplicate intersections. Tables require identical content;
+ Pictures sharing exactly the same box with surviving recognized text yield
+ to that text regardless of confidence. Other pictures require a containing
+ picture crop or verified source ink coverage.
+ Reconsider children whenever their
+ proposed parent loses score suppression; only final survivors absorb them.
+ Unknown scores do not participate in score suppression. Retained fields,
+ object references and reading-order positions stay unchanged.
+ """
+ valid = [position for position, block in enumerate(blocks) if _valid_box(block.bbox)]
+ remaining = set(valid)
+ while remaining:
+ children = {
+ child for child in remaining
+ if any(
+ _absorbs(blocks[parent], blocks[child], image)
+ for parent in remaining
+ )
+ }
+ roots = remaining - children
+ scored = sorted(
+ (position for position in roots if _valid_score(blocks[position].layout_score)),
+ key=lambda position: (-blocks[position].layout_score, position),
+ )
+ kept: list[int] = []
+ losers = set()
+ for position in scored:
+ if any(
+ _overlaps(blocks[winner].bbox, blocks[position].bbox)
+ and (
+ _formula_pair(blocks[winner], blocks[position])
+ or _preserves_content(blocks[winner], blocks[position], image)
+ )
+ for winner in kept
+ ):
+ losers.add(position)
+ else:
+ kept.append(position)
+ if not losers:
+ remaining = roots
+ break
+ remaining -= losers
+
+ # Use final survivors as witnesses so a suppressed text box cannot erase
+ # its picture alias. Exact geometry is required; edge intersections stay.
+ remaining -= {
+ position for position in remaining
+ if blocks[position].type == BlockType.PICTURE
+ and any(
+ blocks[text].type in _PICTURE_TEXT_TYPES
+ and blocks[text].generated_role != FORMULA_NUMBERING_ROLE
+ and bool(blocks[text].content.strip())
+ and tuple(blocks[text].bbox) == tuple(blocks[position].bbox)
+ for text in remaining
+ )
+ }
+ removed = set(valid) - remaining
+
+ if not removed:
+ return blocks
+ return [block for position, block in enumerate(blocks) if position not in removed]
diff --git a/oxr/pipeline/postprocess/json_postprocess.py b/oxr/pipeline/postprocess/json_postprocess.py
new file mode 100644
index 0000000..79c4dad
--- /dev/null
+++ b/oxr/pipeline/postprocess/json_postprocess.py
@@ -0,0 +1,71 @@
+"""Serialize detected regions without turning formula numbers into regions."""
+
+import re
+
+from oxr.pipeline.models import Block, BlockType
+from oxr.pipeline.postprocess.formula_postprocess import FORMULA_NUMBERING_ROLE
+
+
+def _numbered_content(content: str, before: str, after: str) -> str:
+ if before:
+ content += r"\leqno " + before
+ if after:
+ parenthesized = re.fullmatch(r"\((.*)\)", after, re.DOTALL)
+ if parenthesized:
+ content += r"\tag{" + parenthesized.group(1) + "}"
+ else:
+ content += r"\tag*{" + after + "}"
+ return content
+
+
+def serialize_final_blocks(
+ blocks: list[Block], source_ranges: dict[int, tuple[int, int]] | None = None,
+) -> tuple[list[dict], list[dict]]:
+ """Fold surviving number witnesses into their formula; retain orphan text as notes.
+
+ Number witnesses and their source have adjacent expansion indexes and the
+ same box. Keep original indexes so footnote references and ordering remain
+ stable. Optional demo ranges include attached numbering lines. This function
+ never mutates the Markdown assembly input or its source ranges.
+ """
+ formulas = {block.idx: block for block in blocks if block.type == BlockType.FORMULA}
+ numbering: dict[int, dict[str, str]] = {}
+ numbering_indexes: dict[int, list[int]] = {}
+ notes = []
+ for block in blocks:
+ if block.generated_role != FORMULA_NUMBERING_ROLE:
+ continue
+ owner = None
+ for delta, field in ((1, "text_before"), (-1, "text_after")):
+ formula = formulas.get(block.idx + delta)
+ if (formula is not None and formula.bbox == block.bbox
+ and getattr(formula, field).strip() == block.content.strip()):
+ owner = formula
+ numbering.setdefault(owner.idx, {})[field] = block.content
+ numbering_indexes.setdefault(owner.idx, []).append(block.idx)
+ break
+ if owner is None:
+ # A formula removed by cleanup can leave protected numbering behind.
+ # Preserve that text without inventing another detected region.
+ notes.append({"idx": block.idx, "content": block.content})
+
+ serialized = []
+ for block in blocks:
+ if block.generated_role == FORMULA_NUMBERING_ROLE:
+ continue
+ numbers = numbering.get(block.idx, {})
+ content = _numbered_content(
+ block.content, numbers.get("text_before", ""), numbers.get("text_after", ""),
+ ) if block.type == BlockType.FORMULA else block.content
+ region = {
+ "idx": block.idx, "type": "Chemical Equation" if block.type == BlockType.FORMULA and r"\ce" in block.content else block.type.value, "bbox": list(block.bbox),
+ "content": content, "format": block.format.value,
+ }
+ if source_ranges is not None:
+ spans = [source_ranges[idx] for idx in (
+ block.idx, *numbering_indexes.get(block.idx, []),
+ ) if idx in source_ranges]
+ region["start_line"] = min(span[0] for span in spans) if spans else None
+ region["end_line"] = max(span[1] for span in spans) if spans else None
+ serialized.append(region)
+ return serialized, notes
diff --git a/oxr/pipeline/postprocess/layout_postprocess.py b/oxr/pipeline/postprocess/layout_postprocess.py
new file mode 100644
index 0000000..201b392
--- /dev/null
+++ b/oxr/pipeline/postprocess/layout_postprocess.py
@@ -0,0 +1,181 @@
+import math
+from typing import Any, Sequence
+
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+
+
+LA_CLASS_ID_TO_BLOCK_TYPE: tuple[BlockType, ...] = (
+ BlockType.CAPTION,
+ BlockType.FOOTNOTE,
+ BlockType.FORMULA,
+ BlockType.TEXT,
+ BlockType.PAGE_FOOTER,
+ BlockType.PAGE_HEADER,
+ BlockType.PICTURE,
+ BlockType.TITLE,
+ BlockType.TABLE,
+ BlockType.CODE_BLOCK,
+ BlockType.STAMP,
+ BlockType.CHEMICAL_STRUCTURE,
+)
+
+
+def _response_error(message: str) -> ValueError:
+ return ValueError(f"Invalid layout response: {message}")
+
+
+def _require_list(value: Any, field: str) -> list[Any]:
+ if not isinstance(value, list):
+ raise _response_error(f"{field} must be a list")
+ return value
+
+
+def _require_number(value: Any, field: str) -> float:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise _response_error(f"{field} must be numeric")
+ number = float(value)
+ if not math.isfinite(number):
+ raise _response_error(f"{field} must be finite")
+ return number
+
+
+def _require_image_size(value: Any, page_index: int) -> tuple[int, int]:
+ if not isinstance(value, tuple) or len(value) != 2:
+ raise _response_error(f"page {page_index} image dimensions must be a width-height tuple")
+ width, height = value
+ if (
+ isinstance(width, bool)
+ or isinstance(height, bool)
+ or not isinstance(width, int)
+ or not isinstance(height, int)
+ or width <= 0
+ or height <= 0
+ ):
+ raise _response_error(f"page {page_index} image dimensions must be positive integers")
+ return width, height
+
+
+def _intersection_over_union(left: list[float], right: list[float]) -> float:
+ intersection_width = max(0.0, min(left[2], right[2]) - max(left[0], right[0]))
+ intersection_height = max(0.0, min(left[3], right[3]) - max(left[1], right[1]))
+ intersection = intersection_width * intersection_height
+ if intersection == 0.0:
+ return 0.0
+ left_area = (left[2] - left[0]) * (left[3] - left[1])
+ right_area = (right[2] - right[0]) * (right[3] - right[1])
+ return intersection / (left_area + right_area - intersection)
+
+
+def _classwise_nms(
+ candidates: list[tuple[int, BlockType, list[float], float]],
+ iou_threshold: float | None,
+) -> list[tuple[int, BlockType, list[float], float]]:
+ if iou_threshold is None:
+ return candidates
+
+ kept: list[tuple[int, BlockType, list[float], float]] = []
+ for candidate in sorted(candidates, key=lambda item: (-item[3], item[0])):
+ _, block_type, bbox, _ = candidate
+ if any(
+ kept_type == block_type
+ and _intersection_over_union(bbox, kept_bbox) > iou_threshold
+ for _, kept_type, kept_bbox, _ in kept
+ ):
+ continue
+ kept.append(candidate)
+ kept_positions = {position for position, _, _, _ in kept}
+ return [candidate for candidate in candidates if candidate[0] in kept_positions]
+
+
+def parse_layout_batch(
+ payload: Any,
+ image_sizes: Sequence[tuple[int, int]],
+ score_threshold: float,
+ nms_iou_threshold: float | None = 0.6,
+) -> list[list[Block]]:
+ """Validate a native LA batch response and convert retained candidates to blocks."""
+ if not isinstance(payload, dict):
+ raise _response_error("response must be an object")
+ if payload.get("status") != "success":
+ raise _response_error("status must equal 'success'")
+ if not isinstance(payload.get("params"), dict):
+ raise _response_error("params must be an object")
+
+ data = payload.get("data")
+ if not isinstance(data, dict):
+ raise _response_error("data must be an object")
+ labels = _require_list(data.get("labels"), "data.labels")
+ boxes = _require_list(data.get("boxes"), "data.boxes")
+ scores = _require_list(data.get("scores"), "data.scores")
+ threshold = _require_number(score_threshold, "score threshold")
+ if not 0.0 <= threshold <= 1.0:
+ raise _response_error("score threshold must be between 0 and 1")
+ nms_threshold = None
+ if nms_iou_threshold is not None:
+ nms_threshold = _require_number(nms_iou_threshold, "NMS IoU threshold")
+ if not 0.0 <= nms_threshold <= 1.0:
+ raise _response_error("NMS IoU threshold must be between 0 and 1")
+ if not (len(labels) == len(boxes) == len(scores) == len(image_sizes)):
+ raise _response_error("batch count must match image count")
+
+ pages: list[list[Block]] = []
+ for page_index, image_size in enumerate(image_sizes):
+ width, height = _require_image_size(image_size, page_index)
+ page_labels = _require_list(labels[page_index], f"page {page_index} labels")
+ page_boxes = _require_list(boxes[page_index], f"page {page_index} boxes")
+ page_scores = _require_list(scores[page_index], f"page {page_index} scores")
+ if not (len(page_labels) == len(page_boxes) == len(page_scores)):
+ raise _response_error(f"page {page_index} candidate count mismatch")
+
+ candidates: list[tuple[int, BlockType, list[float], float]] = []
+ for candidate_index, (label, raw_box, raw_score) in enumerate(
+ zip(page_labels, page_boxes, page_scores)
+ ):
+ field = f"page {page_index} candidate {candidate_index}"
+ if isinstance(label, bool) or not isinstance(label, int):
+ raise _response_error(f"{field} label must be an integer")
+ if not 0 <= label < len(LA_CLASS_ID_TO_BLOCK_TYPE):
+ raise _response_error(f"{field} label must be between 0 and 11")
+ score = _require_number(raw_score, f"{field} score")
+ if not 0.0 <= score <= 1.0:
+ raise _response_error(f"{field} score must be between 0 and 1")
+ box = _require_list(raw_box, f"{field} bbox")
+ if len(box) != 4:
+ raise _response_error(f"{field} bbox must contain four coordinates")
+ x1, y1, x2, y2 = [
+ _require_number(value, f"{field} bbox[{coordinate_index}]")
+ for coordinate_index, value in enumerate(box)
+ ]
+ if score < threshold:
+ continue
+ if x1 >= x2 or y1 >= y2:
+ raise _response_error(f"{field} bbox must be nondegenerate")
+ x1 = min(max(x1, 0.0), float(width))
+ y1 = min(max(y1, 0.0), float(height))
+ x2 = min(max(x2, 0.0), float(width))
+ y2 = min(max(y2, 0.0), float(height))
+ if x1 >= x2 or y1 >= y2:
+ continue
+ candidates.append(
+ (
+ candidate_index,
+ LA_CLASS_ID_TO_BLOCK_TYPE[label],
+ [x1, y1, x2, y2],
+ score,
+ )
+ )
+
+ page_blocks: list[Block] = []
+ for _, block_type, bbox, score in _classwise_nms(candidates, nms_threshold):
+ page_blocks.append(
+ Block(
+ idx=len(page_blocks),
+ type=block_type,
+ bbox=bbox,
+ content="",
+ format=ContentFormat.TEXT,
+ layout_score=score,
+ )
+ )
+ pages.append(page_blocks)
+ return pages
diff --git a/oxr/pipeline/postprocess/overlap_dedupe.py b/oxr/pipeline/postprocess/overlap_dedupe.py
new file mode 100644
index 0000000..37d93f4
--- /dev/null
+++ b/oxr/pipeline/postprocess/overlap_dedupe.py
@@ -0,0 +1,183 @@
+"""Page-level overlap cleanup after recognition and formula-number expansion.
+
+Uses original layout evidence for Picture/Chemical parents and final reading
+order/content for Text. Retained boxes and IDs are never resized or renumbered.
+"""
+from collections import Counter
+from dataclasses import replace
+import re
+
+import cv2
+import numpy as np
+
+from oxr.pipeline.models import Block, BlockType
+
+
+def _area(box: list[float]) -> float:
+ return max(0.0, box[2] - box[0]) * max(0.0, box[3] - box[1])
+
+
+def _intersection(a: list[float], b: list[float]) -> float:
+ return _area([max(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), min(a[3], b[3])])
+
+
+def _inside(child: Block, parent: Block) -> bool:
+ return _intersection(child.bbox, parent.bbox) / max(_area(child.bbox), 1e-9) >= 0.95
+
+
+def _key(block: Block) -> tuple[BlockType, tuple[float, ...]]:
+ return block.type, tuple(block.bbox)
+
+
+def _normalized(content: str) -> str:
+ return re.sub(r"\s+", "", content)
+
+
+def dedupe_visual_parents(
+ raw_blocks: list[Block], blocks: list[Block], image: np.ndarray,
+ *, allow_mixed_children: bool = False,
+) -> list[Block]:
+ """Remove a uniquely mapped parent only when its stronger children cover ink.
+
+ Captions count toward ink coverage and must still exist in the final page.
+ Missing confidence, missing/ambiguous boxes, or nested deletion skip cleanup.
+ Mixed visual groups also preserve titles and require at least two stronger
+ children, while counting every retained child toward complete ink coverage.
+ """
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if image.ndim == 3 else image
+ decisions = []
+ for parent in raw_blocks:
+ if parent.type not in {BlockType.PICTURE, BlockType.CHEMICAL_STRUCTURE} or parent.layout_score is None:
+ continue
+ children = [
+ child for child in raw_blocks
+ if child.idx != parent.idx
+ and (child.type == parent.type or allow_mixed_children
+ and child.type in {BlockType.PICTURE, BlockType.CHEMICAL_STRUCTURE})
+ and child.layout_score is not None
+ and (allow_mixed_children or child.layout_score >= parent.layout_score + 0.1)
+ and _area(child.bbox) < 0.65 * _area(parent.bbox)
+ and _inside(child, parent)
+ ]
+ if len(children) < 2:
+ continue
+ if allow_mixed_children and sum(
+ child.layout_score >= parent.layout_score + 0.1 for child in children
+ ) < 2:
+ continue
+ if any(
+ _intersection(a.bbox, b.bbox) / max(_area(a.bbox) + _area(b.bbox) - _intersection(a.bbox, b.bbox), 1e-9) > 0.1
+ for i, a in enumerate(children) for b in children[i + 1:]
+ ):
+ continue
+ x, y, u, v = map(round, parent.bbox)
+ height, width = gray.shape
+ x, y, u, v = max(0, x), max(0, y), min(width, u), min(height, v)
+ if x >= u or y >= v:
+ continue
+ ink = gray[y:v, x:u] < 200
+ covered = np.zeros(ink.shape, dtype=bool)
+ label_types = {BlockType.CAPTION, BlockType.TITLE} if allow_mixed_children else {BlockType.CAPTION}
+ captions = [b for b in raw_blocks if b.type in label_types and _inside(b, parent)]
+ for block in children + captions:
+ a, c, e, f = map(round, block.bbox)
+ covered[max(0, c - y):min(v - y, f - y), max(0, a - x):min(u - x, e - x)] = True
+ if not ink.any() or float((ink & covered).sum() / ink.sum()) < 0.999:
+ continue
+ decisions.append((parent, children, captions))
+
+ raw_ids = Counter(block.idx for block in raw_blocks)
+ final_keys = Counter(_key(block) for block in blocks)
+ planned = {parent.idx for parent, _, _ in decisions}
+ removed = set()
+ for parent, children, captions in decisions:
+ if any(raw_ids[b.idx] != 1 for b in [parent, *children]):
+ continue
+ if any(final_keys[_key(b)] != 1 for b in [parent, *children, *captions]):
+ continue
+ if any(child.idx in planned for child in children):
+ continue
+ removed.add(_key(parent))
+ return [block for block in blocks if _key(block) not in removed]
+
+
+def dedupe_complete_text(blocks: list[Block]) -> list[Block]:
+ """Keep a large Text only if ordered small Texts reproduce all its characters.
+
+ Positions, rather than native IDs, establish final reading order. Parent
+ separators preserve sentence boundaries; existing line breaks become blank
+ lines between child pieces only in plain text. Structured content retains
+ its original separators; child-internal spacing never overwrites the parent.
+ All other fields, including generated roles,
+ survive unchanged.
+ """
+ text_positions = [i for i, b in enumerate(blocks) if b.type == BlockType.TEXT]
+ removed = set()
+ groups = []
+ # Match the frozen selector: provisional removals reserve children even if
+ # the later complete-cover guard rejects that parent.
+ for parent_pos in sorted(text_positions, key=lambda i: (-_area(blocks[i].bbox), i)):
+ if parent_pos in removed:
+ continue
+ parent = blocks[parent_pos]
+ parent_text = _normalized(parent.content)
+ eligible = []
+ for child_pos in text_positions:
+ if child_pos == parent_pos or child_pos in removed:
+ continue
+ child = blocks[child_pos]
+ if _area(child.bbox) > 0.8 * _area(parent.bbox) or not _inside(child, parent):
+ continue
+ child_text = _normalized(child.content)
+ if len(child_text) < 5 or child_text not in parent_text:
+ continue
+ eligible.append(child_pos)
+ if not eligible:
+ continue
+ positions = sorted([parent_pos, *eligible])
+ if len(positions) != positions[-1] - positions[0] + 1:
+ continue
+ cursor = 0
+ for child_pos in eligible:
+ child_text = _normalized(blocks[child_pos].content)
+ position = parent_text.find(child_text, cursor)
+ if position < 0:
+ break
+ cursor = position + len(child_text)
+ else:
+ removed.update(eligible)
+ groups.append((parent_pos, eligible))
+
+ actual_removed = set()
+ replacements = {}
+ for parent_pos, children in groups:
+ raw = blocks[parent_pos].content
+ if _normalized(raw) != "".join(_normalized(blocks[i].content) for i in children):
+ continue
+ char_positions = [i for i, char in enumerate(raw) if not char.isspace()]
+ cursor = 0
+ pieces = []
+ # Conservatively leave structured text byte-for-byte intact. A child
+ # boundary alone cannot prove that a newline is outside math, code,
+ # links, emphasis, HTML, a list or an indented block.
+ structured = bool(
+ re.search(r"[$`\\<>\[\]*_~|]", raw)
+ or re.search(r" {2,}\r?\n|(?m:^[ ]{0,3}(?:=+|-+)[ \t]*$)", raw)
+ or re.search(r"(?m)^(?: {4}|\t| {0,3}(?:#{1,6}\s|(?:[-+*]|\d+[.)])\s))", raw)
+ )
+ for i, child_pos in enumerate(children):
+ if i:
+ separator = raw[char_positions[cursor - 1] + 1:char_positions[cursor]]
+ if not structured and ("\n" in separator or "\r" in separator):
+ separator = "\n\n"
+ pieces.append(separator)
+ length = len(_normalized(blocks[child_pos].content))
+ # The child proves coverage, but the selected parent's text is the
+ # source of truth, including internal word and formula spacing.
+ pieces.append(raw[char_positions[cursor]:char_positions[cursor + length - 1] + 1])
+ cursor += length
+ content = raw[:char_positions[0]] + "".join(pieces) + raw[char_positions[-1] + 1:]
+ assert _normalized(content) == _normalized(raw)
+ replacements[parent_pos] = replace(blocks[parent_pos], content=content)
+ actual_removed.update(children)
+ return [replacements.get(i, block) for i, block in enumerate(blocks) if i not in actual_removed]
diff --git a/oxr/pipeline/postprocess/picture_postprocess.py b/oxr/pipeline/postprocess/picture_postprocess.py
new file mode 100644
index 0000000..32314d5
--- /dev/null
+++ b/oxr/pipeline/postprocess/picture_postprocess.py
@@ -0,0 +1,27 @@
+import os
+import cv2
+import numpy as np
+from oxr.pipeline.models import Block, ContentFormat
+from oxr.config.settings import settings
+from oxr.pipeline.image_assets import image_assets
+
+def postprocess_picture(block: Block, image: np.ndarray, file_name: str, page_num: int) -> Block:
+ """Save picture crop and return markdown reference."""
+ assets = image_assets.get()
+ if assets is not None:
+ block.content = f"![]({assets.save(image)})"
+ block.format = ContentFormat.MARKDOWN
+ return block
+ # filename without extension
+ base_name = os.path.splitext(os.path.basename(file_name))[0]
+ out_dir = os.path.join(settings.pipeline.image_output_dir, base_name, "imgs")
+ os.makedirs(out_dir, exist_ok=True)
+
+ img_name = f"{page_num}_{block.idx}.png"
+ img_path = os.path.join(out_dir, img_name)
+ cv2.imwrite(img_path, image)
+
+ # create markdown reference
+ block.content = f"![]({img_path})"
+ block.format = ContentFormat.MARKDOWN
+ return block
diff --git a/oxr/pipeline/postprocess/table_images.py b/oxr/pipeline/postprocess/table_images.py
new file mode 100644
index 0000000..f509b2f
--- /dev/null
+++ b/oxr/pipeline/postprocess/table_images.py
@@ -0,0 +1,280 @@
+"""Associate table pictures, mask numbered TIT tokens and restore inline images."""
+
+import base64
+import math
+import re
+from html.parser import HTMLParser
+
+import cv2
+import numpy as np
+
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.utils.image import crop_image
+from oxr.utils.table import strip_table_code_fence
+from oxr.pipeline.image_assets import image_assets
+
+TABLE_IMAGE_ROLE = "table_embedded_image"
+_TOKEN = re.compile(r"(?:<tit>|&lt;tit(?:>|&gt;))\s*([0-9]*)", re.IGNORECASE)
+_HTML_TAG = re.compile(
+ r"</?[A-Za-z][A-Za-z0-9:_-]*(?:\s+(?:\"[^\"]*\"|'[^']*'|[^'\"<>])*)?\s*/?>|<!--.*?-->",
+ re.DOTALL,
+)
+_PADDING = 4
+
+
+def _valid_box(box: list[float]) -> bool:
+ return (
+ len(box) == 4
+ and all(
+ isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
+ for v in box
+ )
+ and box[0] < box[2]
+ and box[1] < box[3]
+ )
+
+
+def group_table_images(
+ blocks: list[Block],
+ min_score: float,
+ *,
+ keep_outer_tables: bool = False,
+) -> dict[int, list[Block]]:
+ """Assign each confident Picture to a fully containing Table.
+
+ Normally prefer the smallest table. Full overlap cleanup keeps outer tables,
+ so in that mode integrate pictures in the outermost table instead of losing
+ them when the inner table is suppressed.
+
+ Keys are page-list positions, not block idx/read-order values. Existing block
+ order and coordinates are never changed. No image classification is inferred
+ from text or from page-specific coordinates.
+ """
+ tables = [
+ (i, b)
+ for i, b in enumerate(blocks)
+ if b.type == BlockType.TABLE and _valid_box(b.bbox)
+ ]
+ groups: dict[int, list[Block]] = {}
+ for picture in blocks:
+ score = picture.layout_score
+ if (
+ picture.type != BlockType.PICTURE
+ or not _valid_box(picture.bbox)
+ or not isinstance(score, (int, float))
+ or isinstance(score, bool)
+ or not math.isfinite(score)
+ or score < min_score
+ ):
+ continue
+ x1, y1, x2, y2 = picture.bbox
+ parents = [
+ (i, table)
+ for i, table in tables
+ if table.bbox != picture.bbox
+ and table.bbox[0] <= x1
+ and table.bbox[1] <= y1
+ and table.bbox[2] >= x2
+ and table.bbox[3] >= y2
+ ]
+ if parents:
+ i, _ = min(
+ parents,
+ key=lambda item: (
+ (-1 if keep_outer_tables else 1)
+ * (item[1].bbox[2] - item[1].bbox[0])
+ * (item[1].bbox[3] - item[1].bbox[1]),
+ item[0],
+ ),
+ )
+ groups.setdefault(i, []).append(picture)
+ for pictures in groups.values():
+ pictures.sort(key=lambda b: (b.bbox[1], b.bbox[0], b.idx))
+ return groups
+
+
+def image_data_url(image: np.ndarray) -> str:
+ assets = image_assets.get()
+ if assets is not None:
+ return assets.save(image)
+ ok, encoded = cv2.imencode(".png", image)
+ if not ok:
+ raise ValueError("Unable to encode a table image.")
+ return "data:image/png;base64," + base64.b64encode(encoded).decode("ascii")
+
+
+def prepare_table_images(
+ table: Block,
+ pictures: list[Block],
+ page_image: np.ndarray,
+) -> tuple[np.ndarray, dict[int, str]]:
+ """Keep original picture pixels; send blue/white numbered tokens to TBR."""
+ masked = crop_image(page_image, table.bbox)
+ h, w = masked.shape[:2]
+ page_h, page_w = page_image.shape[:2]
+ left = max(0, min(page_w, round(table.bbox[0])))
+ top = max(0, min(page_h, round(table.bbox[1])))
+ sources: dict[int, str] = {}
+ regions: list[tuple[int, int, int, int]] = []
+ for i, picture in enumerate(pictures, 1):
+ a, b, c, d = (round(v) for v in picture.bbox)
+ x1, y1 = max(0, a - left - _PADDING), max(0, b - top - _PADDING)
+ x2, y2 = min(w, c - left + _PADDING), min(h, d - top + _PADDING)
+ if x1 >= x2 or y1 >= y2:
+ raise ValueError("Empty table picture crop.")
+ if any(
+ max(x1, a) < min(x2, c) and max(y1, b) < min(y2, d)
+ for a, b, c, d in regions
+ ):
+ raise ValueError(
+ "Overlapping table pictures cannot receive unambiguous tokens."
+ )
+ regions.append((x1, y1, x2, y2))
+ sources[i] = image_data_url(
+ page_image[top + y1 : top + y2, left + x1 : left + x2]
+ )
+ symbol = f"<tit>{i}"
+ scale, thickness = 0.65, 1
+ (tw, th), baseline = cv2.getTextSize(
+ symbol, cv2.FONT_HERSHEY_SIMPLEX, scale, thickness
+ )
+ if tw + 4 > x2 - x1 or th + baseline + 4 > y2 - y1:
+ raise ValueError(
+ "Table picture is too small for a readable numbered token."
+ )
+ cv2.rectangle(masked, (x1, y1), (x2 - 1, y2 - 1), (255, 0, 0), -1)
+ cv2.putText(
+ masked,
+ symbol,
+ (x1 + (x2 - x1 - tw) // 2, y1 + (y2 - y1 + th) // 2),
+ cv2.FONT_HERSHEY_SIMPLEX,
+ scale,
+ (255, 255, 255),
+ thickness,
+ cv2.LINE_AA,
+ )
+ return masked, sources
+
+
+def _escape_stray_less_than(text: str) -> str:
+ """Keep HTML tags intact while escaping OCR's bare math comparisons."""
+ parts = []
+ start = 0
+ while (position := text.find("<", start)) != -1:
+ parts.append(text[start:position])
+ tag = _HTML_TAG.match(text, position)
+ if tag:
+ parts.append(tag.group())
+ start = tag.end()
+ else:
+ parts.append("&lt;")
+ start = position + 1
+ parts.append(text[start:])
+ return "".join(parts)
+
+
+class _CellTokenValidator(HTMLParser):
+ """Require every token to occur in cell text in a complete HTML table."""
+
+ def __init__(self, markers: list[str]):
+ super().__init__(convert_charrefs=True)
+ self.markers = markers
+ self.seen: list[str] = []
+ self.table = False
+ self.row = False
+ self.cell = False
+ self.complete = False
+ self.valid = True
+
+ def handle_starttag(self, tag, attrs):
+ if tag == "table":
+ if self.table:
+ self.valid = False
+ self.table = True
+ elif tag == "tr":
+ if not self.table or self.row:
+ self.valid = False
+ self.row = True
+ elif tag in {"td", "th"}:
+ if not self.row or self.cell:
+ self.valid = False
+ self.cell = True
+
+ def handle_endtag(self, tag):
+ if tag in {"td", "th"}:
+ if not self.cell:
+ self.valid = False
+ self.cell = False
+ elif tag == "tr":
+ if not self.row or self.cell:
+ self.valid = False
+ self.row = False
+ elif tag == "table":
+ if not self.table or self.row or self.cell:
+ self.valid = False
+ self.table = False
+ self.complete = True
+
+ def handle_data(self, data):
+ for marker in self.markers:
+ if marker in data:
+ if not self.table or not self.cell:
+ self.valid = False
+ self.seen.extend([marker] * data.count(marker))
+
+
+def restore_table_images(raw_text: str, sources: dict[int, str]) -> str | None:
+ """Restore only a complete unique ID set; never guess by token order."""
+ text = strip_table_code_fence(raw_text)
+ matches = list(_TOKEN.finditer(text))
+ if len(matches) != len(sources) or not sources:
+ return None
+ numbers = [m.group(1) for m in matches]
+ if any(not n or len(n) > len(str(len(sources))) for n in numbers):
+ return None
+ ids = [int(n) for n in numbers]
+ if sorted(ids) != sorted(sources):
+ return None
+ prefix = "__OXR_TABLE_IMAGE_"
+ while prefix in text:
+ prefix = "_" + prefix
+ markers = [f"{prefix}{i}__" for i in ids]
+ marker_iter = iter(markers)
+ probe = _escape_stray_less_than(_TOKEN.sub(lambda _: next(marker_iter), text))
+ validator = _CellTokenValidator(markers)
+ validator.feed(probe)
+ validator.close()
+ if not (
+ validator.valid
+ and validator.complete
+ and not validator.table
+ and not validator.row
+ and not validator.cell
+ and sorted(validator.seen) == sorted(markers)
+ ):
+ return None
+ for marker, i in zip(markers, ids):
+ probe = probe.replace(
+ marker,
+ f'<img data-table-image-id="{i}" alt="Table image {i}" src="{sources[i]}">',
+ )
+ return probe
+
+
+def table_image_fallback(table: Block, page_image: np.ndarray) -> Block:
+ """Retain the entire original table, including all pictures, on failure."""
+ table.content = (
+ f'<img alt="Table" src="{image_data_url(crop_image(page_image, table.bbox))}">'
+ )
+ table.format = ContentFormat.HTML
+ return table
+
+
+def mark_table_images(pictures: list[Block]) -> None:
+ for picture in pictures:
+ picture.generated_role = TABLE_IMAGE_ROLE
+
+
+async def unchanged_block(block: Block) -> Block:
+ """Keep RO's original index space while the parent recognizes its pictures."""
+ return block
diff --git a/oxr/pipeline/postprocess/table_postprocess.py b/oxr/pipeline/postprocess/table_postprocess.py
new file mode 100644
index 0000000..8e52056
--- /dev/null
+++ b/oxr/pipeline/postprocess/table_postprocess.py
@@ -0,0 +1,15 @@
+from oxr.pipeline.models import Block, ContentFormat
+from oxr.utils.table import html_table_to_markdown, strip_table_code_fence
+
+
+def postprocess_table(block: Block, raw_text: str, output_format: str = "html") -> Block:
+ """Clean up table block output to the requested table format."""
+ text = strip_table_code_fence(raw_text)
+ if output_format == "markdown":
+ block.content = html_table_to_markdown(text)
+ block.format = ContentFormat.MARKDOWN
+ return block
+
+ block.content = text.strip()
+ block.format = ContentFormat.HTML
+ return block
diff --git a/oxr/pipeline/postprocess/text_postprocess.py b/oxr/pipeline/postprocess/text_postprocess.py
new file mode 100644
index 0000000..3e0995f
--- /dev/null
+++ b/oxr/pipeline/postprocess/text_postprocess.py
@@ -0,0 +1,13 @@
+import re
+from oxr.pipeline.models import Block, ContentFormat
+from oxr.pipeline.postprocess.formula_postprocess import move_formula_numbering_outside_math
+
+def postprocess_text(block: Block, raw_text: str) -> Block:
+ """Clean up text block output."""
+ text = raw_text.strip()
+ # Remove some excessive whitespaces
+ text = re.sub(r'\n+', '\n', text)
+ text = move_formula_numbering_outside_math(text)
+ block.content = text
+ block.format = ContentFormat.TEXT
+ return block
diff --git a/oxr/pipeline/reading_order.py b/oxr/pipeline/reading_order.py
new file mode 100644
index 0000000..ffc4568
--- /dev/null
+++ b/oxr/pipeline/reading_order.py
@@ -0,0 +1,323 @@
+import asyncio
+import hashlib
+import logging
+import re
+from collections import Counter
+from typing import Sequence
+
+import numpy as np
+
+from oxr.config.settings import OXRModelConfig, settings
+from oxr.model.client import OXRModelClient, model_client
+from oxr.model.prompts import build_reading_order_prompt
+from oxr.pipeline.concurrency import gather_cancel_on_error
+from oxr.pipeline.errors import PipelineError, format_error_message, get_error_status_code
+from oxr.pipeline.models import Block
+from oxr.pipeline.xycut_order import xycut_plus_order
+
+
+logger = logging.getLogger(__name__)
+
+_READING_ORDER_PATTERN = re.compile(r"\s*(?:[0-9]+(?:\s+[0-9]+)*)?\s*")
+
+
+def _reading_order_diagnostics(raw_text: object, block_count: int) -> str:
+ """Describe invalid model output without logging document-derived text."""
+ if not isinstance(raw_text, str):
+ return f"output_type={type(raw_text).__name__}"
+
+ digest = hashlib.sha256(raw_text.encode("utf-8")).hexdigest()[:16]
+ if _READING_ORDER_PATTERN.fullmatch(raw_text) is None:
+ return f"syntax=invalid char_count={len(raw_text)} raw_sha256={digest}"
+
+ order = [int(value) for value in raw_text.split()]
+ counts = Counter(order)
+ expected = set(range(block_count))
+ actual = set(order)
+ missing_ids = sorted(expected - actual)
+ duplicate_ids = sorted(value for value, count in counts.items() if count > 1)
+ out_of_range_ids = sorted(actual - expected)
+ return (
+ f"syntax=valid token_count={len(order)} missing_ids={missing_ids} "
+ f"duplicate_ids={duplicate_ids} out_of_range_ids={out_of_range_ids} "
+ f"raw_sha256={digest}"
+ )
+
+
+def parse_reading_order(raw_text: str, block_count: int) -> list[int]:
+ """Parse a strict whitespace-only integer permutation from OXR output."""
+ if not isinstance(raw_text, str):
+ raise ValueError("Invalid reading order: model output must be text")
+ if (
+ isinstance(block_count, bool)
+ or not isinstance(block_count, int)
+ or block_count < 0
+ ):
+ raise ValueError(
+ "Invalid reading order: block count must be a non-negative integer"
+ )
+ if _READING_ORDER_PATTERN.fullmatch(raw_text) is None:
+ raise ValueError(
+ "Invalid reading order: expected whitespace-separated integer IDs only"
+ )
+
+ order = [int(value) for value in raw_text.split()]
+ expected = list(range(block_count))
+ if len(order) != block_count or sorted(order) != expected:
+ raise ValueError(
+ "Invalid reading order: expected an exact permutation of IDs "
+ f"0 through {block_count - 1}"
+ )
+ return order
+
+
+def _insert_missing_from_reference(
+ order: Sequence[int],
+ missing_ids: set[int],
+ reference_order: Sequence[int],
+) -> list[int]:
+ """Insert missing IDs while preserving every existing pairwise order.
+
+ XY-Cut++ supplies only the reference ranks for insertion. For each missing
+ block, choose the position with the fewest pairwise disagreements against
+ that reference. Existing OXR-RO IDs are never reordered.
+ """
+ reference_rank = {block_id: rank for rank, block_id in enumerate(reference_order)}
+ repaired_order = list(order)
+ for missing_id in sorted(missing_ids, key=reference_rank.__getitem__):
+ missing_rank = reference_rank[missing_id]
+
+ def insertion_cost(index: int) -> tuple[int, int]:
+ left_inversions = sum(
+ reference_rank[block_id] > missing_rank
+ for block_id in repaired_order[:index]
+ )
+ right_inversions = sum(
+ reference_rank[block_id] < missing_rank
+ for block_id in repaired_order[index:]
+ )
+ return left_inversions + right_inversions, index
+
+ insertion_index = min(
+ range(len(repaired_order) + 1),
+ key=insertion_cost,
+ )
+ repaired_order.insert(insertion_index, missing_id)
+ return repaired_order
+
+
+def _partial_reading_order(
+ raw_text: object,
+ block_count: int,
+) -> tuple[list[int], set[int], bool] | None:
+ """Parse an in-range partial order and retain each ID's first occurrence."""
+ if (
+ not isinstance(raw_text, str)
+ or _READING_ORDER_PATTERN.fullmatch(raw_text) is None
+ ):
+ return None
+
+ raw_order = [int(value) for value in raw_text.split()]
+ expected = set(range(block_count))
+ if not set(raw_order).issubset(expected):
+ return None
+
+ unique_order = list(dict.fromkeys(raw_order))
+ missing_ids = expected - set(unique_order)
+ has_duplicates = len(unique_order) != len(raw_order)
+ return unique_order, missing_ids, has_duplicates
+
+
+def repair_incomplete_reading_order(
+ raw_text: object,
+ blocks: Sequence[Block],
+) -> list[int] | None:
+ """Repair a nearly complete, valid, unique partial permutation.
+
+ Pages below 20 blocks may be missing one ID; larger pages may be missing two.
+ The model's relative order is preserved. XY-Cut++ is used only to choose the
+ omitted blocks' insertion points; malformed, duplicate, out-of-range, or more
+ incomplete output remains an error.
+ """
+ partial = _partial_reading_order(raw_text, len(blocks))
+ if partial is None:
+ return None
+
+ order, missing_ids, has_duplicates = partial
+ block_count = len(blocks)
+ missing_count = len(missing_ids)
+ allowed_missing = min(2, max(1, block_count // 10))
+ if missing_count < 1 or missing_count > allowed_missing or has_duplicates:
+ return None
+
+ return _insert_missing_from_reference(
+ order,
+ missing_ids,
+ xycut_plus_order(blocks),
+ )
+
+
+def supplement_incomplete_reading_order(
+ raw_text: object,
+ blocks: Sequence[Block],
+) -> list[int] | None:
+ """Use XY-Cut++ to insert omissions after OXR-RO exhausts its retries.
+
+ At least half of all unique IDs must come from OXR-RO so this remains a
+ supplementation step rather than a full-page replacement. Duplicate IDs
+ are collapsed to their first occurrence; malformed or out-of-range output
+ remains an error.
+ """
+ partial = _partial_reading_order(raw_text, len(blocks))
+ if partial is None:
+ return None
+
+ order, missing_ids, has_duplicates = partial
+ block_count = len(blocks)
+ if not missing_ids and not has_duplicates:
+ return None
+ if block_count and len(order) * 2 < block_count:
+ return None
+
+ supplemented_order = _insert_missing_from_reference(
+ order,
+ missing_ids,
+ xycut_plus_order(blocks),
+ )
+ if sorted(supplemented_order) != list(range(block_count)):
+ raise ValueError("XY-Cut++ supplementation did not produce an exact permutation")
+ return supplemented_order
+
+
+async def _resolve_page_reading_order(
+ blocks: Sequence[Block],
+ image: np.ndarray,
+ semaphore: asyncio.Semaphore,
+ page_index: int,
+ *,
+ client: OXRModelClient,
+ config: OXRModelConfig,
+) -> list[int]:
+ block_count = len(blocks)
+ if block_count <= 1:
+ return list(range(block_count))
+
+ if image is None or image.ndim < 2:
+ raise ValueError(
+ f"Page {page_index} image must have height and width dimensions"
+ )
+ image_size = (int(image.shape[1]), int(image.shape[0]))
+ objects = {
+ "ref": [block.type.value for block in blocks],
+ "bbox": [block.bbox for block in blocks],
+ "bbox_type": "real",
+ }
+ prompt = build_reading_order_prompt(objects, image_size=image_size)
+ max_tokens = min(config.max_tokens, max(16, 4 * block_count))
+
+ for attempt in range(config.retry_times):
+ response_received = False
+ try:
+ async with semaphore:
+ raw_text = await client.request_reading_order(prompt, image, max_tokens)
+ response_received = True
+ try:
+ return parse_reading_order(raw_text, block_count)
+ except ValueError:
+ repaired_order = repair_incomplete_reading_order(raw_text, blocks)
+ if repaired_order is not None:
+ logger.warning(
+ "reading_order_repaired page=%d blocks=%d attempt=%d/%d %s",
+ page_index,
+ block_count,
+ attempt + 1,
+ config.retry_times,
+ _reading_order_diagnostics(raw_text, block_count),
+ )
+ return repaired_order
+ if attempt == config.retry_times - 1:
+ supplemented_order = supplement_incomplete_reading_order(
+ raw_text,
+ blocks,
+ )
+ if supplemented_order is not None:
+ logger.warning(
+ "reading_order_supplemented page=%d blocks=%d attempt=%d/%d %s",
+ page_index,
+ block_count,
+ attempt + 1,
+ config.retry_times,
+ _reading_order_diagnostics(raw_text, block_count),
+ )
+ return supplemented_order
+ fallback_order = xycut_plus_order(blocks)
+ logger.warning(
+ "reading_order_xycut_fallback page=%d blocks=%d attempt=%d/%d %s",
+ page_index,
+ block_count,
+ attempt + 1,
+ config.retry_times,
+ _reading_order_diagnostics(raw_text, block_count),
+ )
+ return fallback_order
+ raise
+ except Exception as error:
+ if response_received:
+ logger.warning(
+ "reading_order_invalid page=%d blocks=%d attempt=%d/%d %s",
+ page_index,
+ block_count,
+ attempt + 1,
+ config.retry_times,
+ _reading_order_diagnostics(raw_text, block_count),
+ )
+ if attempt == config.retry_times - 1:
+ message = format_error_message(error, f"Timeout after {config.timeout}s")
+ raise PipelineError(
+ f"Reading order failed for page {page_index} after "
+ f"{config.retry_times} attempts: {message}",
+ status_code=get_error_status_code(error, default=503),
+ ) from error
+ await asyncio.sleep(1)
+
+ raise AssertionError("unreachable")
+
+
+async def resolve_reading_orders(
+ pages_blocks: Sequence[Sequence[Block]],
+ pages_images: Sequence[np.ndarray],
+ semaphore: asyncio.Semaphore,
+ *,
+ client: OXRModelClient | None = None,
+ config: OXRModelConfig | None = None,
+) -> list[list[int]]:
+ """Resolve each page's local reading-order permutation using original images."""
+ if len(pages_blocks) != len(pages_images):
+ raise ValueError("Page block and image counts must match")
+
+ resolved_config = config or (
+ client.config if client is not None else settings.oxr_model
+ )
+ owns_client = client is None and config is not None
+ resolved_client = client or (
+ OXRModelClient(resolved_config) if owns_client else model_client
+ )
+ try:
+ return await gather_cancel_on_error(
+ *(
+ _resolve_page_reading_order(
+ blocks,
+ image,
+ semaphore,
+ page_index,
+ client=resolved_client,
+ config=resolved_config,
+ )
+ for page_index, (blocks, image) in enumerate(
+ zip(pages_blocks, pages_images)
+ )
+ )
+ )
+ finally:
+ if owns_client:
+ await resolved_client.aclose()
diff --git a/oxr/pipeline/recognition.py b/oxr/pipeline/recognition.py
new file mode 100644
index 0000000..a1be680
--- /dev/null
+++ b/oxr/pipeline/recognition.py
@@ -0,0 +1,266 @@
+import asyncio
+import logging
+from typing import Any, Awaitable, Callable, Dict, List, Optional
+
+import numpy as np
+
+from oxr.config.settings import settings
+from oxr.model.client import model_client
+from oxr.pipeline.concurrency import gather_cancel_on_error
+from oxr.pipeline.errors import PipelineError, format_error_message, get_error_status_code
+from oxr.pipeline.models import Block, BlockType
+from oxr.pipeline.postprocess.chemical_structure_postprocess import (
+ postprocess_chemical_structure,
+)
+from oxr.pipeline.postprocess.code_postprocess import postprocess_code
+from oxr.pipeline.postprocess.formula_postprocess import postprocess_formula
+from oxr.pipeline.postprocess.picture_postprocess import postprocess_picture
+from oxr.pipeline.postprocess.table_postprocess import postprocess_table
+from oxr.pipeline.postprocess.table_images import (
+ group_table_images, mark_table_images, prepare_table_images,
+ restore_table_images, table_image_fallback, unchanged_block,
+)
+from oxr.pipeline.postprocess.text_postprocess import postprocess_text
+from oxr.utils.image import crop_image, resize_image
+
+logger = logging.getLogger(__name__)
+
+LENGTH_RECOVERY_REPETITION_PENALTY = 1.1
+TABLE_LENGTH_RECOVERY_SCALE = 0.75
+
+
+def _finish_reason(output: str) -> str:
+ return str(getattr(output, "finish_reason", "unknown"))
+
+
+def _length_recovery_options(
+ model_options: Optional[Dict[str, Any]],
+) -> Dict[str, Any]:
+ recovered = dict(model_options or {})
+ current_penalty = float(recovered.get("repetition_penalty", 1.0))
+ recovered["repetition_penalty"] = max(
+ current_penalty,
+ LENGTH_RECOVERY_REPETITION_PENALTY,
+ )
+ return recovered
+
+
+async def _request_with_retries(
+ request: Callable[[], Awaitable[str]],
+ *,
+ block: Block,
+ attempts: int,
+ timeout: int,
+) -> str:
+ for attempt in range(attempts):
+ try:
+ return await request()
+ except Exception as error:
+ if attempt == attempts - 1:
+ message = format_error_message(error, f"Timeout after {timeout}s")
+ raise PipelineError(
+ f"Recognition failed for block {block.idx} after {attempts} attempts: {message}",
+ status_code=get_error_status_code(error, default=503),
+ ) from error
+ await asyncio.sleep(1)
+
+ raise AssertionError("Recognition retry loop exited unexpectedly.")
+
+
+async def _request_block(
+ block: Block,
+ crop_img: np.ndarray,
+ sem: asyncio.Semaphore,
+ model_options: Optional[Dict[str, Any]],
+) -> str:
+ async with sem:
+ if block.type == BlockType.TABLE:
+ return await model_client.recognize_table(crop_img, model_options)
+ if block.type == BlockType.FORMULA:
+ return await model_client.recognize_formula(crop_img, model_options)
+ if block.type == BlockType.CODE_BLOCK:
+ return await model_client.recognize_code(crop_img, model_options)
+ if block.type == BlockType.CHEMICAL_STRUCTURE:
+ return await model_client.recognize_chemical_structure(
+ crop_img,
+ model_options,
+ )
+ return await model_client.recognize_text(crop_img, model_options)
+
+
+async def recognize_block(
+ block: Block,
+ page_image: np.ndarray,
+ sem: asyncio.Semaphore,
+ file_name: str,
+ page_num: int,
+ model_options: Optional[Dict[str, Any]] = None,
+ element_formats: Optional[Dict[str, str]] = None,
+ table_images: Optional[List[Block]] = None,
+) -> Block:
+ crop_img = crop_image(page_image, block.bbox)
+ element_formats = element_formats or {}
+
+ if block.type == BlockType.PICTURE:
+ # No OCR for picture, just save it
+ return await asyncio.to_thread(postprocess_picture, block, crop_img, file_name, page_num)
+ if (
+ block.type == BlockType.CHEMICAL_STRUCTURE
+ and element_formats.get("cs") == "image"
+ ):
+ return await asyncio.to_thread(postprocess_picture, block, crop_img, file_name, page_num)
+
+ sources: Dict[int, str] = {}
+ if table_images:
+ try:
+ crop_img, sources = await asyncio.to_thread(prepare_table_images, block, table_images, page_image)
+ except ValueError as error:
+ logger.warning("Table %s image placeholders skipped: %s; preserving original table image.", block.idx, error)
+ mark_table_images(table_images)
+ return await asyncio.to_thread(table_image_fallback, block, page_image)
+
+ config = settings.oxr_model
+ try:
+ raw_out = await _request_with_retries(
+ lambda: _request_block(block, crop_img, sem, model_options),
+ block=block,
+ attempts=config.retry_times,
+ timeout=config.timeout,
+ )
+ except PipelineError:
+ if not table_images:
+ raise
+ logger.warning("Table %s placeholder recognition failed; preserving original table image.", block.idx)
+ mark_table_images(table_images)
+ return await asyncio.to_thread(table_image_fallback, block, page_image)
+
+ if _finish_reason(raw_out) == "length":
+ recovery_image: Optional[np.ndarray] = None
+ recovery_options: Optional[Dict[str, Any]] = None
+ recovery_method: Optional[str] = None
+ if block.type == BlockType.TABLE:
+ recovery_image = resize_image(crop_img, TABLE_LENGTH_RECOVERY_SCALE)
+ recovery_options = model_options
+ recovery_method = f"input scale {TABLE_LENGTH_RECOVERY_SCALE}"
+ elif block.type in {
+ BlockType.TEXT,
+ BlockType.TITLE,
+ BlockType.CAPTION,
+ BlockType.FOOTNOTE,
+ BlockType.PAGE_HEADER,
+ BlockType.PAGE_FOOTER,
+ BlockType.STAMP,
+ }:
+ recovery_image = crop_img
+ recovery_options = _length_recovery_options(model_options)
+ recovery_method = (
+ "repetition penalty "
+ f"{recovery_options['repetition_penalty']}"
+ )
+ else:
+ logger.warning(
+ "Recognition output reached the token limit for block %s (%s); "
+ "no recovery is defined, preserving the truncated model output.",
+ block.idx,
+ block.type.value,
+ )
+
+ if recovery_method is not None and recovery_image is not None:
+ logger.warning(
+ "Recognition output reached the token limit for block %s (%s); "
+ "retrying with %s.",
+ block.idx,
+ block.type.value,
+ recovery_method,
+ )
+ try:
+ raw_out = await _request_with_retries(
+ lambda: _request_block(block, recovery_image, sem, recovery_options),
+ block=block,
+ attempts=config.retry_times,
+ timeout=config.timeout,
+ )
+ except PipelineError:
+ if not table_images:
+ raise
+ logger.warning("Table %s placeholder recovery failed; preserving original table image.", block.idx)
+ mark_table_images(table_images)
+ return await asyncio.to_thread(table_image_fallback, block, page_image)
+ if _finish_reason(raw_out) == "length":
+ logger.warning(
+ "Recognition output remained truncated for block %s (%s) "
+ "after length recovery with %s; preserving the truncated "
+ "model output.",
+ block.idx,
+ block.type.value,
+ recovery_method,
+ )
+
+ if block.type == BlockType.TABLE:
+ if table_images:
+ restored = restore_table_images(raw_out, sources)
+ mark_table_images(table_images)
+ if restored is None or _finish_reason(raw_out) == "length":
+ logger.warning("Table %s has incomplete image IDs/output; preserving original table image.", block.idx)
+ return await asyncio.to_thread(table_image_fallback, block, page_image)
+ raw_out = restored
+ return postprocess_table(
+ block,
+ raw_out,
+ element_formats.get("table", "html"),
+ )
+ if block.type == BlockType.FORMULA:
+ return postprocess_formula(block, raw_out)
+ if block.type == BlockType.CODE_BLOCK:
+ return postprocess_code(block, raw_out)
+ if block.type == BlockType.CHEMICAL_STRUCTURE:
+ return postprocess_chemical_structure(block, raw_out)
+ return postprocess_text(block, raw_out)
+
+
+async def recognize_pages(
+ pages_blocks: List[List[Block]],
+ pages_images: List[np.ndarray],
+ file_name: str,
+ semaphore: asyncio.Semaphore,
+ model_options: Optional[Dict[str, Any]] = None,
+ element_formats: Optional[Dict[str, str]] = None,
+) -> List[List[Block]]:
+ """Run recognition for all blocks across all pages concurrently."""
+ if len(pages_blocks) != len(pages_images):
+ raise ValueError("Page block and image counts must match")
+
+ tasks = []
+ # keep track of which task belongs to which page and block index
+ # tasks structure: (page_idx, block_idx, task)
+ for page_idx, (blocks, image) in enumerate(zip(pages_blocks, pages_images)):
+ groups = (
+ group_table_images(
+ blocks, settings.pipeline.table_image_min_score,
+ keep_outer_tables=settings.pipeline.full_overlap_dedupe,
+ )
+ if settings.pipeline.table_image_placeholders else {}
+ )
+ nested = {id(picture) for pictures in groups.values() for picture in pictures}
+ for block_idx, block in enumerate(blocks):
+ if id(block) in nested:
+ task = unchanged_block(block)
+ else:
+ kwargs = {"table_images": groups[block_idx]} if block_idx in groups else {}
+ task = recognize_block(
+ block, image, semaphore, file_name, page_idx,
+ model_options, element_formats, **kwargs,
+ )
+ tasks.append((page_idx, block_idx, task))
+
+ # Run all tasks
+ gathered_results = await gather_cancel_on_error(*(t[2] for t in tasks))
+
+ # Reconstruct pages_blocks
+ final_pages_blocks: List[List[Optional[Block]]] = [
+ [None] * len(page_blocks) for page_blocks in pages_blocks
+ ]
+ for (page_idx, block_idx, _), block_result in zip(tasks, gathered_results):
+ final_pages_blocks[page_idx][block_idx] = block_result
+
+ return [[block for block in page if block is not None] for page in final_pages_blocks]
diff --git a/oxr/pipeline/xycut_order.py b/oxr/pipeline/xycut_order.py
new file mode 100644
index 0000000..c99cef6
--- /dev/null
+++ b/oxr/pipeline/xycut_order.py
@@ -0,0 +1,76 @@
+"""XY-Cut++ adapter that returns a validated order without dropping blocks."""
+
+from __future__ import annotations
+
+import math
+from typing import Sequence
+
+from oxr.pipeline._vendor import xycut_plus_plus
+from oxr.pipeline.models import Block, BlockType
+
+
+_LABEL_MAP = {
+ BlockType.TEXT: "text",
+ BlockType.TITLE: "paragraph_title",
+ BlockType.CAPTION: "figure_title",
+ BlockType.FOOTNOTE: "footnote",
+ BlockType.FORMULA: "formula",
+ BlockType.TABLE: "table",
+ BlockType.PICTURE: "image",
+ BlockType.PAGE_HEADER: "text",
+ BlockType.PAGE_FOOTER: "text",
+ BlockType.STAMP: "seal",
+ BlockType.CHEMICAL_STRUCTURE: "image",
+ BlockType.CODE_BLOCK: "algorithm",
+}
+
+_NO_MASK_LABELS = [
+ "text",
+ "formula",
+ "algorithm",
+ "reference",
+ "content",
+ "abstract",
+]
+
+
+def _integer_bbox(block: Block) -> list[int]:
+ if len(block.bbox) != 4 or not all(math.isfinite(value) for value in block.bbox):
+ raise ValueError(f"invalid bbox for XY-Cut++ block {block.idx}: {block.bbox!r}")
+
+ x1, y1, x2, y2 = block.bbox
+ bbox = [math.floor(x1), math.floor(y1), math.ceil(x2), math.ceil(y2)]
+ if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
+ raise ValueError(f"degenerate bbox for XY-Cut++ block {block.idx}: {block.bbox!r}")
+ return bbox
+
+
+def xycut_plus_order(blocks: Sequence[Block]) -> list[int]:
+ """Return the pinned XY-Cut++ reference order for every input block.
+
+ The adapter is order-only: overlap deletion is disabled, and the returned
+ sequence must be an exact permutation before it can be used for repair.
+ """
+ if len(blocks) <= 1:
+ return list(range(len(blocks)))
+
+ entries = [
+ {
+ "block_bbox": _integer_bbox(block),
+ "block_label": _LABEL_MAP[block.type],
+ "block_content": str(index),
+ "seg_start_flag": False,
+ "seg_end_flag": False,
+ }
+ for index, block in enumerate(blocks)
+ ]
+ result = xycut_plus_plus.get_layout_ordering(
+ entries,
+ no_mask_labels=_NO_MASK_LABELS,
+ remove_overlaps=False,
+ )
+ order = [int(entry["block_content"]) for entry in result]
+ expected = list(range(len(blocks)))
+ if len(order) != len(expected) or sorted(order) != expected:
+ raise ValueError("XY-Cut++ did not return a complete unique permutation")
+ return order
diff --git a/oxr/server/__init__.py b/oxr/server/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/oxr/server/app.py b/oxr/server/app.py
new file mode 100644
index 0000000..501f26b
--- /dev/null
+++ b/oxr/server/app.py
@@ -0,0 +1,50 @@
+import asyncio
+from contextlib import asynccontextmanager
+from pathlib import Path
+from fastapi import FastAPI
+from fastapi.responses import FileResponse
+from fastapi.staticfiles import StaticFiles
+from oxr.config.settings import settings
+from oxr.model.client import model_client
+from oxr.model.layout_client import layout_client
+from oxr.server.queue.memory_store import MemoryTaskStore
+from oxr.server.demo_api import router as demo_router, start_demo, stop_demo
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ settings.validate_for_server()
+ app.state.task_store = MemoryTaskStore()
+ await start_demo(app)
+ try:
+ yield
+ finally:
+ demo_close_results = await asyncio.gather(stop_demo(app), return_exceptions=True)
+ close_results = await asyncio.gather(
+ layout_client.aclose(),
+ model_client.aclose(),
+ return_exceptions=True,
+ )
+ for result in demo_close_results + close_results:
+ if isinstance(result, BaseException):
+ raise result
+
+
+app = FastAPI(title="OXR Server", version="0.1.0", lifespan=lifespan)
+
+from oxr.server.routes import router
+
+app.include_router(router, prefix="/v1")
+
+# OXR Online Demo — bundled UI and its dedicated API endpoints.
+app.include_router(demo_router, prefix="/v1")
+DEMO_DIR = Path(__file__).parent / "demo"
+
+
[email protected]("/demo", include_in_schema=False)
[email protected]("/demo/", include_in_schema=False)
+async def demo_page():
+ return FileResponse(DEMO_DIR / "index.html", headers={"Cache-Control": "no-cache"})
+
+
+app.mount("/demo/assets", StaticFiles(directory=DEMO_DIR, check_dir=False), name="demo-assets")
diff --git a/oxr/server/demo/LICENSE-SoMarkDownViewer b/oxr/server/demo/LICENSE-SoMarkDownViewer
new file mode 100644
index 0000000..76fefe3
--- /dev/null
+++ b/oxr/server/demo/LICENSE-SoMarkDownViewer
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020 Mathpix
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/oxr/server/demo/favicon.svg b/oxr/server/demo/favicon.svg
new file mode 100644
index 0000000..2f63ca7
--- /dev/null
+++ b/oxr/server/demo/favicon.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 210 210">
+ <rect width="210" height="210" rx="28" fill="#111"/>
+ <g transform="translate(19.59 36.28)">
+ <rect width="170.82" height="27.49" fill="#fff"/>
+ <rect y="54.97" width="170.82" height="27.49" fill="#f39800"/>
+ <rect y="109.95" width="71.67" height="27.49" fill="#fff"/>
+ <rect x="99.15" y="109.95" width="71.67" height="27.49" fill="#fff"/>
+ </g>
+</svg>
diff --git a/oxr/server/demo/index.html b/oxr/server/demo/index.html
new file mode 100644
index 0000000..f91f971
--- /dev/null
+++ b/oxr/server/demo/index.html
@@ -0,0 +1,160 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>OXR Online Demo</title>
+ <link rel="icon" type="image/svg+xml" href="/demo/assets/favicon.svg">
+ <link rel="stylesheet" href="/demo/assets/vendor/deps/katex.min.css">
+ <link rel="stylesheet" href="/demo/assets/vendor/deps/highlight.js.default.min.css">
+ <link rel="stylesheet" href="/demo/assets/vendor/somarkdown/somarkdown.css">
+ <link rel="stylesheet" href="/demo/assets/style/index.css">
+</head>
+<body>
+ <main class="app-container" id="app-container">
+ <header class="app-header">
+ <a href="https://somark.ai" target="_blank" rel="noopener noreferrer" class="logo-text" aria-label="OXR Online Demo SoMark">
+ <span>O<span class="brand-accent">X</span>R Online Demo|</span>
+ <svg class="header__logo-svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 170.82 137.43" aria-hidden="true">
+ <rect class="header__logo-rect header__logo-rect--top" x="0" width="170.82" height="27.49" fill="#fff"/>
+ <rect class="header__logo-rect header__logo-rect--middle" y="54.97" width="170.82" height="27.49" fill="#f39800"/>
+ <rect class="header__logo-rect header__logo-rect--bottom-left" x="0" y="109.95" width="71.67" height="27.49" fill="#fff"/>
+ <rect class="header__logo-rect header__logo-rect--bottom-right" x="99.15" y="109.95" width="71.67" height="27.49" fill="#fff"/>
+ </svg>
+ <span>SoMark</span>
+ </a>
+ <div class="header-actions">
+ <button class="icon-btn" id="download-button" type="button" disabled aria-label="Download Markdown" title="Download Markdown">
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v12"></path><path d="m7 10 5 5 5-5"></path><path d="M5 21h14"></path></svg>
+ </button>
+ </div>
+ </header>
+ <div class="markdown-content" id="markdown-content">
+ <aside class="config-panel" aria-label="Config">
+ <div class="panel-header"><span class="panel-title">Config</span></div>
+ <div class="config-content" tabindex="0" aria-label="Configuration and model information">
+ <nav class="config-badges" aria-label="OXR resources">
+ <a class="resource-badge" href="https://github.com/SoMarkAI/OXR" target="_blank" rel="noopener noreferrer">
+ <svg class="resource-badge-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 19c-4 1.2-4-2-6-2m12 5v-4a3.5 3.5 0 0 0-1-2.7c3.3-.4 6-1.6 6-5.3a4.2 4.2 0 0 0-1-2.8 4 4 0 0 0-.1-2.8s-1-.3-3.2 1a11 11 0 0 0-5.4 0c-2.2-1.3-3.2-1-3.2-1A4 4 0 0 0 7 7.2 4.2 4.2 0 0 0 6 10c0 3.7 2.7 4.9 6 5.3A3.5 3.5 0 0 0 11 18v4"/></svg>
+ <span class="resource-badge-text"><span class="resource-badge-label">GitHub</span></span>
+ </a>
+ <a class="resource-badge" href="https://huggingface.co/SoMarkAI/OXR-1.0" target="_blank" rel="noopener noreferrer">
+ <svg class="resource-badge-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12a7 7 0 1 1 14 0M9 11h.01M15 11h.01M9 14c1.6 1.3 4.4 1.3 6 0M8 20l-4-2-2-4c-.5-1.2 1-2 1.8-.9l1.7 2.1M8 20h2v-3l-3-2c-1.2-.8-2.3.5-1.3 1.5L7 18m9 2 4-2 2-4c.5-1.2-1-2-1.8-.9l-1.7 2.1M16 20h-2v-3l3-2c1.2-.8 2.3.5 1.3 1.5L17 18"/></svg>
+ <span class="resource-badge-text"><span class="resource-badge-label">Hugging Face</span></span>
+ </a>
+ <a class="resource-badge" href="https://modelscope.cn/models/SoMark/OXR-1.0" target="_blank" rel="noopener noreferrer">
+ <svg class="resource-badge-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m12 2 9 5v10l-9 5-9-5V7l9-5Zm0 10 9-5M12 12 3 7m9 5v10M7.5 4.5l9 5v5l-4.5 2.5-4.5-2.5v-5l9-5"/></svg>
+ <span class="resource-badge-text"><span class="resource-badge-label">ModelScope</span></span>
+ </a>
+ <a class="resource-badge" href="https://somark.ai/oxr" target="_blank" rel="noopener noreferrer">
+ <svg class="resource-badge-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="4" ry="9"/><path d="M3 12h18"/></svg>
+ <span class="resource-badge-text"><span class="resource-badge-label">Official Website</span></span>
+ </a>
+ <span class="resource-badge resource-badge--static">
+ <svg class="resource-badge-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m7 3 10 18M17 3 7 21M5 8l4-3m6 14 4-3"/></svg>
+ <span class="resource-badge-text"><span class="resource-badge-label">arXiv</span><span class="resource-badge-detail">· Coming soon</span></span>
+ </span>
+ <span class="resource-badge resource-badge--static">
+ <svg class="resource-badge-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13 3H5v18h14v-9M13 3v6h6l-6-6M8 13h5m-5 4h8"/></svg>
+ <span class="resource-badge-text"><span class="resource-badge-label">License</span><span class="resource-badge-detail">· Apache 2.0</span></span>
+ </span>
+ </nav>
+ <button class="upload-button" id="upload-button" type="button">
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 16V4m-4 4 4-4 4 4M4 16v4h16v-4"/></svg>
+ Upload File
+ </button>
+ <input id="file-input" type="file" accept="application/pdf,image/png,image/jpeg,image/webp,image/bmp,image/tiff,.pdf,.png,.jpg,.jpeg,.webp,.bmp,.tif,.tiff" hidden>
+ <section class="config-section" aria-labelledby="parameters-title">
+ <h2 class="config-heading" id="parameters-title">Parsing Parameters</h2>
+ <div class="parameter-control">
+ <div class="parameter-label-row">
+ <label for="temperature-value">Temperature</label>
+ <input id="temperature-value" type="number" min="0" max="2" step="0.01" value="0" inputmode="decimal">
+ </div>
+ <input id="temperature-slider" type="range" min="0" max="2" step="0.01" value="0" aria-label="Temperature slider">
+ </div>
+ <div class="parameter-control">
+ <div class="parameter-label-row">
+ <label for="top_p-value">Top P</label>
+ <input id="top_p-value" type="number" min="0" max="1" step="0.01" value="1" inputmode="decimal">
+ </div>
+ <input id="top_p-slider" type="range" min="0" max="1" step="0.01" value="1" aria-label="Top P slider">
+ </div>
+ <div class="parameter-control">
+ <div class="parameter-label-row">
+ <label for="repetition_penalty-value">Repetition Penalty</label>
+ <input id="repetition_penalty-value" type="number" min="0.1" max="2" step="0.01" value="1" inputmode="decimal">
+ </div>
+ <input id="repetition_penalty-slider" type="range" min="0.1" max="2" step="0.01" value="1" aria-label="Repetition Penalty slider">
+ </div>
+ </section>
+ <section class="config-section" id="status-section" aria-labelledby="status-title">
+ <div class="status-heading-row">
+ <h2 class="config-heading" id="status-title">Status</h2>
+ <span class="status-indicator" id="status-state" data-state="empty" role="status">Empty</span>
+ </div>
+ <dl class="status-details">
+ <div class="status-file-row"><dt>File</dt><dd id="status-file">—</dd></div>
+ <div><dt>Pages</dt><dd id="status-pages">—</dd></div>
+ <div><dt>Total elapsed</dt><dd id="status-elapsed">—</dd></div>
+ <div id="status-processing-row" hidden><dt>Processing time</dt><dd id="status-processing">—</dd></div>
+ </dl>
+ <p class="status-error" id="status-error" role="alert" hidden></p>
+ <button class="text-btn retry-button" id="retry-button" type="button" hidden>Retry</button>
+ </section>
+ <section class="config-section config-about" aria-labelledby="about-title">
+ <h2 class="config-heading" id="about-title">About OXR</h2>
+ <p>OXR (Optical Everything Recognition) is an open-source model from the SoMark team. It turns PDFs and document images into Agent-Friendly data in Markdown or JSON, with layout coordinates included.</p>
+ <p>Pretrained from scratch, OXR uses a recursive self-improvement (RSI) loop during post-training—a first in document parsing. With just 1.3B parameters, OXR ranks #1 on olmOCR-Bench, OmniDocBench, and DocParsingBench while delivering industry-leading parsing speed.</p>
+ </section>
+ </div>
+ </aside>
+ <div class="document-panels" id="document-panels">
+ <section class="file-panel" aria-label="File">
+ <div class="panel-header">
+ <span class="panel-title">File</span>
+ </div>
+ <div class="panel-viewport file-viewport" id="file-viewport" tabindex="0" aria-label="File pages">
+ <button class="empty-state upload-dropzone" id="upload-dropzone" type="button">
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><path d="M14 2v6h6M12 17v-6m-3 3 3-3 3 3"></path></svg>
+ <span class="empty-title">Drop a PDF or image here</span>
+ <span>or click to choose a file</span>
+ </button>
+ <div id="file-pages"></div>
+ </div>
+ </section>
+ <div class="markdown-splitter" id="markdown-splitter" role="separator" aria-label="Resize File and result panels" aria-orientation="vertical" aria-valuemin="20" aria-valuemax="80" aria-valuenow="50" tabindex="0"></div>
+ <section class="result-panel" aria-label="Parsing result">
+ <div class="panel-header result-header">
+ <div class="tabs" role="tablist" aria-label="Result view">
+ <button class="tab active" id="tab-rendered" role="tab" aria-selected="true" aria-controls="rendered-viewport" data-tab="rendered">Preview</button>
+ <button class="tab" id="tab-source" role="tab" aria-selected="false" aria-controls="source-viewport" data-tab="source" tabindex="-1">Source</button>
+ <button class="tab" id="tab-layout" role="tab" aria-selected="false" aria-controls="layout-viewport" data-tab="layout" tabindex="-1">Layout</button>
+ </div>
+ <span class="page-count" id="page-count"></span>
+ </div>
+ <div class="panel-viewport rendered-viewport" id="rendered-viewport" role="tabpanel" aria-labelledby="tab-rendered" tabindex="0"><div class="empty-state result-empty">Your parsed document will appear here</div></div>
+ <div class="panel-viewport source-viewport" id="source-viewport" role="tabpanel" aria-labelledby="tab-source" tabindex="0" hidden></div>
+ <div class="panel-viewport layout-viewport" id="layout-viewport" role="tabpanel" aria-labelledby="tab-layout" tabindex="0" hidden></div>
+ </section>
+ </div>
+ </div>
+ <div class="bottom-spacer" aria-hidden="true"></div>
+ </main>
+ <div class="file-drop-overlay" id="file-drop-overlay" role="status" aria-live="polite" hidden>
+ <div class="file-drop-message">
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 16V4m-4 4 4-4 4 4M4 16v4h16v-4"/></svg>
+ <strong>Drop file to parse</strong>
+ <span>Release your PDF or image to start parsing</span>
+ </div>
+ </div>
+ <div class="parse-progress" id="parse-progress" role="status" aria-live="polite" aria-atomic="true" hidden>
+ <ol class="progress-tree" aria-label="Document progress">
+ <li class="progress-step" id="upload-step"><span class="progress-node" aria-hidden="true"></span><span id="upload-progress-label">Uploading...</span></li>
+ <li class="progress-step" id="parse-step"><span class="progress-node" aria-hidden="true"></span><span>Parsing...</span></li>
+ </ol>
+ </div>
+ <script src="/demo/assets/vendor/somarkdown/somarkdown.umd.min.js"></script>
+ <script type="module" src="/demo/assets/lib/index.js"></script>
+</body>
+</html>
diff --git a/oxr/server/demo/lib/config.js b/oxr/server/demo/lib/config.js
new file mode 100644
index 0000000..ef7330e
--- /dev/null
+++ b/oxr/server/demo/lib/config.js
@@ -0,0 +1,98 @@
+const $ = (id) => document.getElementById(id);
+const parameters = [
+ ["temperature", "Temperature"],
+ ["top_p", "Top P"],
+ ["repetition_penalty", "Repetition Penalty"],
+];
+let startedAt = null;
+let timer = null;
+
+for (const [key] of parameters) {
+ const number = $(`${key}-value`);
+ const slider = $(`${key}-slider`);
+ slider.addEventListener("input", () => {
+ number.value = slider.value;
+ number.removeAttribute("aria-invalid");
+ });
+ number.addEventListener("input", () => {
+ const valid = number.value !== "" && number.validity.valid;
+ number.setAttribute("aria-invalid", String(!valid));
+ if (valid) slider.value = number.value;
+ });
+}
+
+export function readModelOptions() {
+ const options = {};
+ for (const [key, label] of parameters) {
+ const input = $(`${key}-value`);
+ const value = input.valueAsNumber;
+ if (!Number.isFinite(value) || !input.validity.valid) {
+ input.setAttribute("aria-invalid", "true");
+ throw new Error(`${label} must be between ${input.min} and ${input.max}, in steps of 0.01.`);
+ }
+ options[key] = value;
+ }
+ return options;
+}
+
+function setState(state, label) {
+ $("status-state").dataset.state = state;
+ $("status-state").textContent = label;
+}
+
+function duration(milliseconds) {
+ const seconds = Math.max(0, milliseconds) / 1000;
+ if (seconds < 60) return `${seconds.toFixed(1)} s`;
+ const wholeSeconds = Math.floor(seconds);
+ return `${Math.floor(wholeSeconds / 60)}m ${String(wholeSeconds % 60).padStart(2, "0")}s`;
+}
+
+function updateElapsed() {
+ if (startedAt !== null) $("status-elapsed").textContent = duration(performance.now() - startedAt);
+}
+
+export function resetStatus(file) {
+ clearInterval(timer);
+ timer = null;
+ startedAt = null;
+ setState("empty", "Empty");
+ $("status-file").textContent = file.name;
+ $("status-pages").textContent = "—";
+ $("status-elapsed").textContent = "—";
+ $("status-processing-row").hidden = true;
+ $("status-processing").textContent = "—";
+ $("status-error").textContent = "";
+ $("status-error").hidden = true;
+ $("retry-button").hidden = true;
+}
+
+export function startStatus() {
+ setState("parsing", "Parsing");
+ startedAt = performance.now();
+ updateElapsed();
+ timer = setInterval(updateElapsed, 100);
+}
+
+export function updateStatusPages(count) {
+ $("status-pages").textContent = Number.isInteger(count) && count > 0 ? String(count) : "—";
+}
+
+export function finishStatus(error = null, metadata = {}, retry = true) {
+ updateElapsed();
+ clearInterval(timer);
+ timer = null;
+ if (error) {
+ setState("error", "Error");
+ $("status-error").textContent = error;
+ $("status-error").hidden = false;
+ $("retry-button").hidden = !retry;
+ $("status-section").scrollIntoView({ block: "nearest" });
+ } else {
+ setState("completed", "Completed");
+ if (Number.isInteger(metadata.page_num)) updateStatusPages(metadata.page_num);
+ if (Number.isFinite(metadata.processing_time_ms) && metadata.processing_time_ms >= 0) {
+ $("status-processing").textContent = duration(metadata.processing_time_ms);
+ $("status-processing-row").hidden = false;
+ }
+ }
+}
diff --git a/oxr/server/demo/lib/index.js b/oxr/server/demo/lib/index.js
new file mode 100644
index 0000000..1acc1d5
--- /dev/null
+++ b/oxr/server/demo/lib/index.js
@@ -0,0 +1,363 @@
+import { createRenderer, sanitizeMarkup, renderedNodesForRange, sourceNodesForRange, addPageDivider, renderSource } from "./rendering.js";
+import { createPageImage, createLegend } from "./layout.js";
+import { PageSync, initSplitter } from "./page-sync.js";
+import { downloadLayoutImage } from "./layout-export.js";
+import { readModelOptions, resetStatus, startStatus, updateStatusPages, finishStatus } from "./config.js";
+
+const $ = (id) => document.getElementById(id);
+const fileViewport = $("file-viewport");
+const resultViewports = [$("rendered-viewport"), $("source-viewport"), $("layout-viewport")];
+const renderer = createRenderer();
+let pages = [];
+let markdown = "";
+let fileName = "document";
+let lastFile = null;
+let activeTab = "rendered";
+let selectedKey = null;
+let requestController = null;
+let generation = 0;
+let imageSignature = "";
+let resultReady = false;
+let isLoading = false;
+let dragDepth = 0;
+const blockMap = new Map();
+const sync = new PageSync(fileViewport, resultViewports, (page) => {
+ $("page-count").textContent = pages.length ? `${page + 1} / ${pages.length}` : "";
+});
+initSplitter($("document-panels"), $("markdown-splitter"));
+
+function setProgress(stage) {
+ isLoading = Boolean(stage);
+ if (isLoading) clearFileDrag();
+ $("app-container").inert = isLoading;
+ $("app-container").setAttribute("aria-busy", String(isLoading));
+ $("parse-progress").hidden = !stage;
+ $("upload-step").className = `progress-step ${stage === "upload" ? "active" : "complete"}`;
+ $("upload-progress-label").textContent = stage === "upload" ? "Uploading..." : "Uploaded.";
+ $("parse-step").className = `progress-step${stage === "parse" ? " active" : ""}`;
+}
+
+async function request(url, options = {}) {
+ const response = await fetch(url, { ...options, signal: requestController.signal });
+ let body;
+ try { body = await response.json(); } catch { throw new Error(`Server returned an invalid response (${response.status}).`); }
+ if (!response.ok || body.code !== 0) {
+ const detail = body.detail || body.message || body.error;
+ throw new Error(typeof detail === "string" ? detail : `Request failed (${response.status}).`);
+ }
+ return body.data;
+}
+
+function pause(ms, signal) {
+ return new Promise((resolve, reject) => {
+ const abort = () => { clearTimeout(timer); reject(new DOMException("Aborted", "AbortError")); };
+ const timer = setTimeout(() => { signal.removeEventListener("abort", abort); resolve(); }, ms);
+ if (signal.aborted) abort(); else signal.addEventListener("abort", abort, { once: true });
+ });
+}
+
+function pageSection(page, className) {
+ const section = document.createElement("section");
+ section.className = className;
+ section.dataset.pageIndex = String(page.page_num);
+ section.setAttribute("aria-label", `Page ${page.page_num + 1}`);
+ return section;
+}
+
+function appendImagePage(parent, page, mode) {
+ const section = pageSection(page, `${mode}-page`);
+ const label = document.createElement("div");
+ label.className = "page-label";
+ label.textContent = `PAGE ${page.page_num + 1}`;
+ const image = createPageImage(page, mode, (key) => selectBlock(key, mode), () => selectedKey);
+ section.append(label);
+ if (mode === "layout") {
+ const documentName = fileName;
+ const download = document.createElement("button");
+ download.type = "button";
+ download.className = "page-download";
+ download.setAttribute("aria-label", `Download layout for page ${page.page_num + 1}`);
+ download.title = "Download page layout as PNG";
+ download.innerHTML = $("download-button").innerHTML;
+ const errorNotice = document.createElement("div");
+ errorNotice.className = "page-download-error";
+ errorNotice.setAttribute("role", "alert");
+ errorNotice.hidden = true;
+ download.addEventListener("click", async (event) => {
+ event.stopPropagation();
+ download.disabled = true;
+ download.setAttribute("aria-busy", "true");
+ errorNotice.hidden = true;
+ try {
+ await downloadLayoutImage(image, documentName, page.page_num);
+ } catch (error) {
+ errorNotice.textContent = `Download failed: ${error.message || "Please try again."}`;
+ errorNotice.hidden = false;
+ } finally {
+ download.disabled = false;
+ download.removeAttribute("aria-busy");
+ }
+ });
+ label.append(download);
+ section.append(errorNotice);
+ }
+ section.append(image);
+ if (mode === "file") section.append(createLegend(page.blocks || []));
+ parent.append(section);
+}
+
+function renderFiles() {
+ const fragment = document.createDocumentFragment();
+ pages.forEach((page) => appendImagePage(fragment, page, "file"));
+ $("file-pages").replaceChildren(fragment);
+ $("upload-dropzone").hidden = pages.length > 0;
+ sync.setPage(Math.min(sync.page, Math.max(0, pages.length - 1)));
+}
+
+function updatePageImages(incoming) {
+ const signature = JSON.stringify(incoming.map((page) => [page.page_num, page.image_url, page.page_size]));
+ if (signature === imageSignature) return;
+ imageSignature = signature;
+ pages = incoming.slice().sort((a, b) => a.page_num - b.page_num);
+ renderFiles();
+}
+
+function showResult(result) {
+ markdown = String(result.outputs?.markdown || "");
+ const images = new Map(pages.map((page) => [page.page_num, page]));
+ pages = (result.demo_pages || []).map((page) => ({ ...images.get(page.page_num), ...page })).sort((a, b) => a.page_num - b.page_num);
+ if (!pages.length) throw new Error("The server returned no document pages.");
+ blockMap.clear();
+ renderFiles();
+ const fragments = resultViewports.map(() => document.createDocumentFragment());
+ pages.forEach((page, index) => {
+ const rendered = pageSection(page, "rendered-page somarkdown-container theme-dark");
+ const source = pageSection(page, "source-page");
+ const content = String(page.markdown || "");
+ if (content.trim()) {
+ try { rendered.append(sanitizeMarkup(renderer.render(content), `page-${page.page_num}-`)); }
+ catch { const warning = document.createElement("p"); warning.className = "empty-page"; warning.textContent = "This page could not be rendered. Its Markdown is available in Source."; rendered.append(warning); }
+ } else {
+ const empty = document.createElement("p"); empty.className = "empty-page"; empty.textContent = "No Markdown content on this page."; rendered.append(empty);
+ }
+ renderSource(content, source);
+ // HTML-table cells are parsed separately by SoMarkDown; their data-line
+ // values are cell-local, not page-local. The table root owns this block.
+ rendered.querySelectorAll("table[data-line] [data-line]").forEach((node) => node.removeAttribute("data-line"));
+ for (const node of rendered.querySelectorAll("[data-line]")) node.classList.add("bi-direction-jump__target");
+ (page.blocks || []).forEach((block, position) => {
+ const key = `${page.page_num}:${position}`;
+ const sourceNodes = sourceNodesForRange(source, block.start_line, block.end_line);
+ let renderedNodes = renderedNodesForRange(rendered, block.start_line, block.end_line);
+ // Markdown definitions (for example unreferenced footnotes) may have no
+ // rendered node. Keep their nonempty content visible and selectable.
+ if (!renderedNodes.length && sourceNodes.length && String(block.content || "").trim()) {
+ const fallback = document.createElement("aside");
+ fallback.className = "block-fallback bi-direction-jump__target";
+ fallback.dataset.blockKey = key;
+ const label = document.createElement("span");
+ label.className = "fallback-label";
+ label.textContent = String(block.type);
+ const text = document.createElement("div");
+ text.className = "fallback-content";
+ text.textContent = String(block.content);
+ fallback.append(label, text);
+ rendered.append(fallback);
+ renderedNodes = [fallback];
+ }
+ blockMap.set(key, { page: page.page_num, block, position, rendered: renderedNodes, source: sourceNodes });
+ });
+ fragments[0].append(rendered);
+ fragments[1].append(source);
+ appendImagePage(fragments[2], page, "layout");
+ if (index < pages.length - 1) {
+ addPageDivider(fragments[0], page.page_num, pages[index + 1].page_num);
+ addPageDivider(fragments[1], page.page_num, pages[index + 1].page_num);
+ }
+ });
+ resultViewports.forEach((viewport, index) => viewport.replaceChildren(fragments[index]));
+ resultReady = true;
+ $("download-button").disabled = false;
+ sync.setPage(Math.min(sync.page, pages.length - 1));
+}
+
+function clearSelection() {
+ selectedKey = null;
+ document.querySelectorAll(".bi-direction-jump__target--active, .layout-box.selected").forEach((node) => {
+ node.classList.remove("bi-direction-jump__target--active", "selected");
+ });
+}
+
+function selectBlock(key, origin = "tab") {
+ const entry = blockMap.get(key);
+ if (!entry) return;
+ clearSelection();
+ selectedKey = key;
+ for (const node of [...entry.rendered, ...entry.source]) node.classList.add("bi-direction-jump__target--active");
+ for (const node of document.querySelectorAll(".layout-box")) node.classList.toggle("selected", node.dataset.blockKey === key);
+ const viewport = $(`${activeTab}-viewport`);
+ sync.setPage(entry.page, origin === "layout" ? viewport : fileViewport);
+ if (origin === "layout") {
+ const fileBox = Array.from(fileViewport.querySelectorAll(".layout-box")).find((node) => node.dataset.blockKey === key);
+ sync.reveal(fileViewport, fileBox);
+ }
+ const target = activeTab === "layout" ? Array.from(viewport.querySelectorAll(".layout-box")).find((node) => node.dataset.blockKey === key) : entry[activeTab][0];
+ sync.reveal(viewport, target);
+
+}
+
+function selectTab(name) {
+ activeTab = name;
+ document.querySelectorAll("[data-tab]").forEach((tab) => {
+ const active = tab.dataset.tab === name;
+ tab.classList.toggle("active", active);
+ tab.setAttribute("aria-selected", String(active));
+ tab.tabIndex = active ? 0 : -1;
+ });
+ resultViewports.forEach((viewport) => { viewport.hidden = viewport.id !== `${name}-viewport`; });
+ sync.setResult($(`${name}-viewport`));
+ if (selectedKey && blockMap.get(selectedKey)?.page === sync.page) selectBlock(selectedKey);
+}
+
+async function upload(file) {
+ if (!file || isLoading) return;
+ resetStatus(file);
+ lastFile = null;
+ if (!/\.(pdf|png|jpe?g|webp|bmp|tiff?)$/i.test(file.name)) {
+ finishStatus("Choose a PDF, PNG, JPEG, WebP, BMP, or TIFF file.", {}, false);
+ return;
+ }
+ if (!file.size) { finishStatus("The selected file is empty.", {}, false); return; }
+ lastFile = file;
+ let modelOptions;
+ try { modelOptions = readModelOptions(); }
+ catch (error) { finishStatus(error.message); return; }
+ requestController?.abort();
+ requestController = new AbortController();
+ const signal = requestController.signal;
+ const currentGeneration = ++generation;
+ fileName = file.name;
+ lastFile = file;
+ pages = [];
+ markdown = "";
+ selectedKey = null;
+ imageSignature = "";
+ resultReady = false;
+ blockMap.clear();
+ $("download-button").disabled = true;
+ $("file-pages").replaceChildren();
+ $("upload-dropzone").hidden = false;
+ $("page-count").textContent = "";
+ resultViewports.forEach((viewport) => {
+ const message = document.createElement("div");
+ message.className = "empty-state result-empty";
+ message.textContent = "Your parsed document will appear here";
+ viewport.replaceChildren(message);
+ });
+ sync.page = 0;
+ startStatus();
+ setProgress("upload");
+ try {
+ const form = new FormData();
+ form.append("file", file);
+ for (const [key, value] of Object.entries(modelOptions)) form.append(key, String(value));
+ const job = await request("/v1/demo/jobs", { method: "POST", body: form });
+ if (currentGeneration !== generation) return;
+ setProgress("parse");
+ let delay = 650;
+ while (currentGeneration === generation) {
+ const status = await request(`/v1/demo/jobs/${encodeURIComponent(job.id)}`);
+ if (currentGeneration !== generation) return;
+ updatePageImages(status.pages || []);
+ updateStatusPages(status.pages?.length);
+ if (status.status === "failed") throw new Error(typeof status.error === "string" ? status.error : status.error?.message || "Document parsing failed.");
+ if (status.status === "success") {
+ const result = await request(status.result_url || `/v1/demo/jobs/${encodeURIComponent(job.id)}/result`);
+ if (currentGeneration === generation) {
+ showResult(result);
+ setProgress(null);
+ updateStatusPages(pages.length);
+ finishStatus(null, result.metadata);
+ }
+ return;
+ }
+ await pause(delay, signal);
+ delay = Math.min(1800, delay * 1.15);
+ }
+ } catch (error) {
+ if (error.name === "AbortError" || currentGeneration !== generation) return;
+ setProgress(null);
+ finishStatus(error.message || "Unable to connect to the server.");
+ resultViewports.forEach((viewport) => {
+ if (!resultReady) {
+ const message = document.createElement("div");
+ message.className = "empty-state";
+ message.textContent = "Parsing could not finish. Upload a file to try again.";
+ viewport.replaceChildren(message);
+ }
+ });
+ }
+}
+
+$("retry-button").addEventListener("click", () => upload(lastFile));
+$("upload-button").addEventListener("click", () => $("file-input").click());
+for (const viewport of [fileViewport, $("layout-viewport")]) {
+ viewport.addEventListener("click", (event) => {
+ if (!event.target.closest('.layout-box[role="button"]')) clearSelection();
+ });
+}
+$("upload-dropzone").addEventListener("click", () => $("file-input").click());
+$("file-input").addEventListener("change", (event) => { upload(event.target.files[0]); event.target.value = ""; });
+function clearFileDrag() {
+ dragDepth = 0;
+ $("file-drop-overlay").hidden = true;
+}
+const hasDraggedFile = (event) => Array.from(event.dataTransfer?.types || []).includes("Files");
+window.addEventListener("dragenter", (event) => {
+ if (!hasDraggedFile(event)) return;
+ event.preventDefault();
+ if (isLoading) return;
+ dragDepth += 1;
+ $("file-drop-overlay").hidden = false;
+});
+window.addEventListener("dragover", (event) => {
+ if (!hasDraggedFile(event)) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = isLoading ? "none" : "copy";
+ if (!isLoading) $("file-drop-overlay").hidden = false;
+});
+window.addEventListener("dragleave", () => {
+ dragDepth = Math.max(0, dragDepth - 1);
+ if (!dragDepth) clearFileDrag();
+});
+window.addEventListener("drop", (event) => {
+ const file = event.dataTransfer?.files[0];
+ if (hasDraggedFile(event) || file) event.preventDefault();
+ clearFileDrag();
+ if (!isLoading) upload(file);
+});
+window.addEventListener("dragend", clearFileDrag);
+window.addEventListener("blur", clearFileDrag);
+window.addEventListener("keydown", (event) => { if (event.key === "Escape") clearFileDrag(); });
+document.querySelectorAll("[data-tab]").forEach((tab) => {
+ tab.addEventListener("click", () => selectTab(tab.dataset.tab));
+ tab.addEventListener("keydown", (event) => {
+ const tabs = Array.from(document.querySelectorAll("[data-tab]"));
+ if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
+ event.preventDefault();
+ const index = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1 : (tabs.indexOf(tab) + (event.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length;
+ selectTab(tabs[index].dataset.tab);
+ tabs[index].focus();
+ });
+});
+$("download-button").addEventListener("click", () => {
+ if (!resultReady) return;
+ const url = URL.createObjectURL(new Blob([markdown], { type: "text/markdown;charset=utf-8" }));
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = `${fileName.replace(/\.[^.]+$/, "") || "document"}.md`;
+ document.body.append(anchor);
+ anchor.click();
+ anchor.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+});
diff --git a/oxr/server/demo/lib/layout-export.js b/oxr/server/demo/lib/layout-export.js
new file mode 100644
index 0000000..3bb3950
--- /dev/null
+++ b/oxr/server/demo/lib/layout-export.js
@@ -0,0 +1,106 @@
+const SVG_NS = "http://www.w3.org/2000/svg";
+
+function imageLoaded(src) {
+ return new Promise((resolve, reject) => {
+ const image = new Image();
+ image.onload = () => resolve(image);
+ image.onerror = () => reject(new Error("Unable to render the layout image."));
+ image.src = src;
+ });
+}
+
+function dataURL(blob) {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result);
+ reader.onerror = () => reject(new Error("Unable to read the page image."));
+ reader.readAsDataURL(blob);
+ });
+}
+
+function snapshot(wrap, width, height) {
+ const clone = wrap.cloneNode(true);
+ const originals = [wrap, ...wrap.querySelectorAll("*")];
+ const copies = [clone, ...clone.querySelectorAll("*")];
+ for (let index = 0; index < originals.length; index += 1) {
+ const computed = getComputedStyle(originals[index]);
+ const target = copies[index];
+ target.removeAttribute("id");
+ // Freeze the actual appearance, including selection, label truncation,
+ // responsive dimensions and non-scaling SVG strokes, before any await.
+ for (const property of computed) {
+ let value = computed.getPropertyValue(property);
+ // Browser-computed marker URLs may include the current document URL.
+ // The standalone snapshot must resolve them within its own SVG.
+ value = value.replace(/url\(["']?[^)"']*#([^\s)"']+)["']?\)/g, "url(#$1)");
+ target.style.setProperty(property, value);
+ }
+ target.style.setProperty("animation", "none");
+ target.style.setProperty("transition", "none");
+ // Marker IDs are referenced by the reading-order paths.
+ if (originals[index].namespaceURI === SVG_NS && originals[index].id) {
+ target.id = originals[index].id;
+ }
+ }
+ Object.assign(clone.style, {
+ position: "relative", width: `${width}px`, height: `${height}px`,
+ minWidth: "0", minHeight: "0", maxWidth: "none", maxHeight: "none",
+ margin: "0", transform: "none", aspectRatio: "auto"
+ });
+ const image = clone.querySelector("img");
+ image.removeAttribute("srcset");
+ image.removeAttribute("sizes");
+ image.setAttribute("loading", "eager");
+ return clone;
+}
+
+/** Download exactly the current page drawing, excluding its surrounding controls. */
+export async function downloadLayoutImage(wrap, fileName, pageNum) {
+ const image = wrap.querySelector("img");
+ const { width, height } = wrap.getBoundingClientRect();
+ const source = image?.currentSrc || image?.src;
+ if (!source || !width || !height || wrap.querySelector(".image-error")) {
+ throw new Error("The page image is not available to download.");
+ }
+ const clone = snapshot(wrap, width, height);
+ const response = await fetch(source, { credentials: "same-origin" });
+ if (!response.ok) throw new Error("Unable to load the page image. Please try again.");
+ const rasterURL = await dataURL(await response.blob());
+ const raster = await imageLoaded(rasterURL);
+ clone.querySelector("img").src = rasterURL;
+
+ const svg = document.createElementNS(SVG_NS, "svg");
+ svg.setAttribute("width", String(width));
+ svg.setAttribute("height", String(height));
+ svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
+ const content = document.createElementNS(SVG_NS, "foreignObject");
+ content.setAttribute("width", "100%");
+ content.setAttribute("height", "100%");
+ content.append(clone);
+ svg.append(content);
+ // A self-contained data URL keeps foreignObject canvas rendering origin-clean;
+ // a Blob URL SVG can taint the canvas even when all its images are embedded.
+ const serialized = new XMLSerializer().serializeToString(svg);
+ const drawing = await imageLoaded(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(serialized)}`);
+ const scale = Math.max(raster.naturalWidth / width, raster.naturalHeight / height, window.devicePixelRatio || 1);
+ const canvas = document.createElement("canvas");
+ canvas.width = Math.ceil(width * scale);
+ canvas.height = Math.ceil(height * scale);
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("This browser cannot export the layout image.");
+ context.drawImage(drawing, 0, 0, canvas.width, canvas.height);
+ const png = await new Promise((resolve, reject) => {
+ canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Unable to export the layout image.")), "image/png");
+ });
+ const url = URL.createObjectURL(png);
+ const link = document.createElement("a");
+ const baseName = String(fileName || "document").replace(/\.[^.]+$/, "").replace(/[\\/\u0000-\u001f]/g, "_");
+ link.download = `${baseName}-page-${pageNum + 1}-layout.png`;
+ link.href = url;
+ document.body.append(link);
+ try { link.click(); } finally {
+ link.remove();
+ // Give the browser time to consume the download before releasing its URL.
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ }
+}
diff --git a/oxr/server/demo/lib/layout.js b/oxr/server/demo/lib/layout.js
new file mode 100644
index 0000000..ee1f59f
--- /dev/null
+++ b/oxr/server/demo/lib/layout.js
@@ -0,0 +1,129 @@
+const NS = "http://www.w3.org/2000/svg";
+const COLORS = new Map(Object.entries({
+ "Text": "#3b82f6", "Title": "#10b981", "Caption": "#ec4899", "Footnote": "#a3a3a3",
+ "Formula": "#f59e0b", "Table": "#0ea5e9", "Picture": "#ef4444", "Page-header": "#a3a3a3",
+ "Page-footer": "#a3a3a3", "Stamp": "#8b5cf6", "Chemical Structure": "#f97316", "Code Block": "#a3e635"
+}));
+
+export function categoryColor(type) {
+ if (!COLORS.has(type)) COLORS.set(type, `hsl(${(COLORS.size * 137.508) % 360} 72% 65%)`);
+ return COLORS.get(type);
+}
+
+function svgElement(tag, attrs) {
+ const element = document.createElementNS(NS, tag);
+ for (const [key, value] of Object.entries(attrs)) element.setAttribute(key, String(value));
+ return element;
+}
+
+function validBox(block) {
+ return Array.isArray(block.bbox) && block.bbox.length === 4 && block.bbox.every(Number.isFinite)
+ && block.bbox[2] > block.bbox[0] && block.bbox[3] > block.bbox[1];
+}
+
+export function createPageImage(page, mode, onSelect, currentKey) {
+ const wrap = document.createElement("div");
+ wrap.className = "page-image";
+ const w = Number(page.page_size?.w) || 1;
+ const h = Number(page.page_size?.h) || 1;
+ wrap.style.aspectRatio = `${w} / ${h}`;
+ wrap.style.setProperty("--page-ratio", String(w / h));
+ const image = document.createElement("img");
+ image.alt = `Page ${page.page_num + 1}`;
+ image.loading = page.page_num === 0 ? "eager" : "lazy";
+ image.decoding = "async";
+ image.width = w;
+ image.height = h;
+ if (page.image_url) image.src = page.image_url;
+ image.addEventListener("error", () => {
+ const error = document.createElement("span");
+ error.className = "image-error";
+ error.textContent = "Page image unavailable. Upload the file again to retry.";
+ wrap.append(error);
+ }, { once: true });
+ wrap.append(image);
+ const blocks = (page.blocks || []).map((block, position) => ({ ...block, position, key: `${page.page_num}:${position}` })).filter(validBox);
+ const readingBlocks = blocks.filter((block) => !["Page-header", "Page-footer"].includes(block.type));
+ // Number the same reading sequence as the arrows, independently of JSON IDs.
+ const readingNumbers = new Map(readingBlocks.map((block, index) => [block.key, index + 1]));
+ const overlay = svgElement("svg", { viewBox: `0 0 ${w} ${h}`, class: "layout-overlay", "aria-label": `Page ${page.page_num + 1} layout` });
+ if (mode === "layout" && readingBlocks.length > 1) {
+ const markerId = `reading-arrow-${page.page_num}`;
+ const defs = svgElement("defs", {});
+ const marker = svgElement("marker", { id: markerId, viewBox: "0 0 10 10", refX: 9, refY: 5, markerWidth: 5, markerHeight: 5, orient: "auto-start-reverse", overflow: "visible" });
+ marker.append(svgElement("path", { d: "M 0 0 L 10 5 L 0 10 z", fill: "#000", stroke: "#fff", "stroke-width": 0.7, "stroke-linejoin": "round", "paint-order": "stroke fill" }));
+ defs.append(marker);
+ overlay.append(defs);
+ const outlines = document.createDocumentFragment();
+ const lines = document.createDocumentFragment();
+ for (let index = 1; index < readingBlocks.length; index += 1) {
+ const before = readingBlocks[index - 1].bbox;
+ const after = readingBlocks[index].bbox;
+ const d = `M ${(before[0] + before[2]) / 2} ${(before[1] + before[3]) / 2} L ${(after[0] + after[2]) / 2} ${(after[1] + after[3]) / 2}`;
+ outlines.append(svgElement("path", { d, class: "reading-line-outline" }));
+ lines.append(svgElement("path", { d, class: "reading-line", "marker-end": `url(#${markerId})` }));
+ }
+ overlay.append(outlines, lines);
+ }
+ const labels = document.createDocumentFragment();
+ for (const block of blocks) {
+ const [x1, y1, x2, y2] = block.bbox;
+ const color = categoryColor(String(block.type));
+ const displayOnly = !readingBlocks.includes(block);
+ const blockLabel = displayOnly ? String(block.type) : `[${readingNumbers.get(block.key)}] ${block.type}`;
+ const rect = svgElement("rect", { x: x1, y: y1, width: x2 - x1, height: y2 - y1, stroke: color, class: `layout-box${displayOnly ? " layout-box--display-only" : ""}`, "aria-label": blockLabel, "data-block-key": block.key });
+ rect.style.setProperty("--box-color", color);
+ const title = svgElement("title", {});
+ title.textContent = displayOnly ? blockLabel : `${blockLabel} — select to highlight`;
+ rect.append(title);
+ if (!displayOnly) {
+ rect.setAttribute("tabindex", "0");
+ rect.setAttribute("role", "button");
+ rect.addEventListener("click", (event) => {
+ // Coincident formula/number boxes remain individually selectable by cycling.
+ const bounds = overlay.getBoundingClientRect();
+ const x = (event.clientX - bounds.left) / bounds.width * w;
+ const y = (event.clientY - bounds.top) / bounds.height * h;
+ const hits = readingBlocks.filter((candidate) => x >= candidate.bbox[0] && x <= candidate.bbox[2] && y >= candidate.bbox[1] && y <= candidate.bbox[3]);
+ const selected = hits.findIndex((candidate) => candidate.key === currentKey());
+ const next = hits.length ? hits[(selected + 1) % hits.length] : block;
+ onSelect(next.key, hits.length);
+ });
+ rect.addEventListener("keydown", (event) => {
+ if (event.key === "Enter" || event.key === " ") { event.preventDefault(); onSelect(block.key, 1); }
+ });
+ }
+ overlay.append(rect);
+ if (mode === "layout") {
+ // HTML labels keep a readable CSS-pixel font size while the image and
+ // SVG geometry resize. Percent positions stay anchored to the bbox.
+ const label = document.createElement("span");
+ const left = Math.max(0, Math.min(100, x1 / w * 100));
+ label.className = "layout-category-label";
+ label.textContent = blockLabel;
+ label.setAttribute("aria-hidden", "true");
+ label.style.left = `${left}%`;
+ label.style.top = `max(0px, calc(${Math.max(0, Math.min(100, y1 / h * 100))}% - var(--layout-label-height, 1.6em)))`;
+ label.style.maxWidth = `${100 - left}%`;
+ label.style.setProperty("--box-color", color);
+ labels.append(label);
+ }
+ }
+ wrap.append(overlay, labels);
+ return wrap;
+}
+
+export function createLegend(blocks) {
+ const legend = document.createElement("div");
+ legend.className = "layout-legend";
+ for (const type of new Set(blocks.map((block) => String(block.type)))) {
+ const item = document.createElement("span");
+ item.className = "legend-item";
+ const swatch = document.createElement("span");
+ swatch.className = "legend-swatch";
+ swatch.style.setProperty("--box-color", categoryColor(type));
+ item.append(swatch, document.createTextNode(type));
+ legend.append(item);
+ }
+ return legend;
+}
diff --git a/oxr/server/demo/lib/page-sync.js b/oxr/server/demo/lib/page-sync.js
new file mode 100644
index 0000000..eb648d8
--- /dev/null
+++ b/oxr/server/demo/lib/page-sync.js
@@ -0,0 +1,187 @@
+export class PageSync {
+ constructor(fileViewport, resultViewports, onPage) {
+ this.fileViewport = fileViewport;
+ this.resultViewports = resultViewports;
+ this.activeResult = resultViewports[0];
+ this.page = 0;
+ this.onPage = onPage;
+ this.suppressed = new WeakMap();
+ for (const viewport of [fileViewport, ...resultViewports]) {
+ let pending = false;
+ viewport.addEventListener("scroll", () => {
+ if (pending) return;
+ pending = true;
+ requestAnimationFrame(() => {
+ pending = false;
+ if (viewport.hidden || this.suppressed.has(viewport)) return;
+ this.updateFrom(viewport);
+ });
+ }, { passive: true });
+ viewport.addEventListener("load", (event) => {
+ if (event.target.tagName === "IMG" && !viewport.hidden && !this.suppressed.has(viewport) && this.currentPage(viewport) !== this.page) this.scrollToPage(viewport, this.page, false);
+ }, true);
+ for (const event of ["wheel", "touchstart", "pointerdown", "keydown"]) {
+ viewport.addEventListener(event, () => this.cancelScroll(viewport), { passive: true });
+ }
+ }
+ // Reflow changes page heights without a scroll event (especially Source
+ // wrapping). Preserve the active page when either pane is resized.
+ if ("ResizeObserver" in window) {
+ const sizes = new WeakMap();
+ let resizePending = false;
+ this.resizeObserver = new ResizeObserver((entries) => {
+ let changed = false;
+ for (const entry of entries) {
+ if (entry.target.hidden || !entry.contentRect.width || !entry.contentRect.height) continue;
+ const size = `${entry.contentRect.width}:${entry.contentRect.height}`;
+ if (sizes.has(entry.target) && sizes.get(entry.target) !== size) changed = true;
+ sizes.set(entry.target, size);
+ }
+ if (!changed || resizePending) return;
+ resizePending = true;
+ requestAnimationFrame(() => {
+ resizePending = false;
+ this.scrollToPage(this.fileViewport, this.page, false);
+ this.scrollToPage(this.activeResult, this.page, false);
+ });
+ });
+ for (const viewport of [fileViewport, ...resultViewports]) this.resizeObserver.observe(viewport);
+ }
+ }
+
+ currentPage(viewport) {
+ const pages = Array.from(viewport.querySelectorAll("[data-page-index]"));
+ if (!pages.length) return null;
+ if (viewport.scrollHeight > viewport.clientHeight + 2 && viewport.scrollTop + viewport.clientHeight >= viewport.scrollHeight - 2) {
+ return Number(pages[pages.length - 1].dataset.pageIndex);
+ }
+ const midpoint = viewport.getBoundingClientRect().top + viewport.clientHeight / 2;
+ let selected = pages[0];
+ let distance = Infinity;
+ for (const page of pages) {
+ const rect = page.getBoundingClientRect();
+ const delta = midpoint < rect.top ? rect.top - midpoint : midpoint > rect.bottom ? midpoint - rect.bottom : 0;
+ if (delta < distance) { distance = delta; selected = page; }
+ }
+ return Number(selected.dataset.pageIndex);
+ }
+
+ updateFrom(viewport) {
+ const page = this.currentPage(viewport);
+ if (page === null || page === this.page) return;
+ this.page = page;
+ this.onPage(page);
+ this.scrollToPage(viewport === this.fileViewport ? this.activeResult : this.fileViewport, page);
+ }
+
+ cancelScroll(viewport) {
+ const motion = this.suppressed.get(viewport);
+ if (!motion) return;
+ cancelAnimationFrame(motion.frame);
+ this.suppressed.delete(viewport);
+ }
+
+ scrollTo(viewport, top, animate = true) {
+ const target = Math.max(0, Math.min(top, viewport.scrollHeight - viewport.clientHeight));
+ this.cancelScroll(viewport);
+ const start = viewport.scrollTop;
+ const distance = target - start;
+ const motion = { target, frame: 0 };
+ this.suppressed.set(viewport, motion);
+ // Keep the final scroll event suppressed as well as every intermediate
+ // frame. User input cancels this immediately and takes over the pane.
+ const finish = () => {
+ motion.frame = requestAnimationFrame(() => {
+ motion.frame = requestAnimationFrame(() => {
+ if (this.suppressed.get(viewport) === motion) this.suppressed.delete(viewport);
+ });
+ });
+ };
+ if (!animate || Math.abs(distance) < 1 || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
+ viewport.scrollTop = target;
+ finish();
+ return;
+ }
+ const started = performance.now();
+ const duration = Math.min(520, 280 + Math.abs(distance) * 0.12);
+ const step = (now) => {
+ const progress = Math.min(1, (now - started) / duration);
+ const eased = progress < 0.5 ? 4 * progress ** 3 : 1 - (-2 * progress + 2) ** 3 / 2;
+ viewport.scrollTop = start + distance * eased;
+ if (progress < 1) motion.frame = requestAnimationFrame(step);
+ else finish();
+ };
+ motion.frame = requestAnimationFrame(step);
+ }
+
+ scrollToPage(viewport, index, animate = true) {
+ const page = viewport.querySelector(`[data-page-index="${Number(index)}"]`);
+ if (!page) return;
+ const rect = page.getBoundingClientRect();
+ const parent = viewport.getBoundingClientRect();
+ const offset = rect.top - parent.top + viewport.scrollTop;
+ this.scrollTo(viewport, offset + Math.min(rect.height / 2, viewport.clientHeight / 2) - viewport.clientHeight / 2, animate);
+ }
+
+ setPage(page, origin = null) {
+ this.page = page;
+ this.onPage(page);
+ for (const viewport of [this.fileViewport, this.activeResult]) {
+ if (viewport !== origin) this.scrollToPage(viewport, page);
+ }
+ }
+
+ setResult(viewport) {
+ if (this.activeResult !== viewport) this.cancelScroll(this.activeResult);
+ this.activeResult = viewport;
+ this.scrollToPage(viewport, this.page);
+ }
+
+ reveal(viewport, node) {
+ if (!node) return;
+ const rect = node.getBoundingClientRect();
+ const parent = viewport.getBoundingClientRect();
+ const top = rect.top - parent.top + viewport.scrollTop;
+ const bottom = top + rect.height;
+ // Selection often follows setPage in the same event. Test against its
+ // destination, then retarget the animation instead of jumping twice.
+ const destination = this.suppressed.get(viewport)?.target ?? viewport.scrollTop;
+ if (top < destination || bottom > destination + viewport.clientHeight) {
+ this.scrollTo(viewport, top - 24);
+ }
+ }
+}
+
+export function initSplitter(container, splitter) {
+ let ratio = 0.5;
+ const apply = (next) => {
+ const width = container.clientWidth - splitter.clientWidth;
+ if (width <= 0 || getComputedStyle(container).flexDirection === "column") return;
+ const min = Math.min(0.45, 280 / width);
+ const max = Math.max(0.55, 1 - 320 / width);
+ ratio = Math.max(min, Math.min(max, next));
+ container.style.setProperty("--file-panel-width", `calc((100% - var(--splitter-hit-size)) * ${ratio})`);
+ splitter.setAttribute("aria-valuenow", String(Math.round(ratio * 100)));
+ };
+ splitter.addEventListener("pointerdown", (event) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ splitter.setPointerCapture(event.pointerId);
+ container.classList.add("panel-resizing");
+ });
+ splitter.addEventListener("pointermove", (event) => {
+ if (!splitter.hasPointerCapture(event.pointerId)) return;
+ apply((event.clientX - container.getBoundingClientRect().left) / (container.clientWidth - splitter.clientWidth));
+ });
+ for (const event of ["pointerup", "pointercancel", "lostpointercapture"]) {
+ splitter.addEventListener(event, () => container.classList.remove("panel-resizing"));
+ }
+ splitter.addEventListener("dblclick", () => apply(0.5));
+ splitter.addEventListener("keydown", (event) => {
+ if (["ArrowLeft", "ArrowRight", "Home", "Enter"].includes(event.key)) {
+ event.preventDefault();
+ apply(["Home", "Enter"].includes(event.key) ? 0.5 : ratio + (event.key === "ArrowLeft" ? -1 : 1) * (event.shiftKey ? 0.1 : 0.02));
+ }
+ });
+ window.addEventListener("resize", () => apply(ratio));
+}
diff --git a/oxr/server/demo/lib/rendering.js b/oxr/server/demo/lib/rendering.js
new file mode 100644
index 0000000..67ac579
--- /dev/null
+++ b/oxr/server/demo/lib/rendering.js
@@ -0,0 +1,135 @@
+/* Viewer-compatible rendering and block highlights. No source/preview scroll coupling. */
+const HTML_TAGS = new Set("a abbr b blockquote br caption code col colgroup dd del details div dl dt em figcaption figure h1 h2 h3 h4 h5 h6 hr i img ins kbd li mark ol p pre s samp small span strong sub summary sup table tbody td th thead tfoot tr u ul var".split(" "));
+const SVG_TAGS = new Set("svg g path line polyline polygon rect circle ellipse text tspan defs clippath mask marker pattern lineargradient radialgradient stop use title desc".split(" "));
+const MATH_TAGS = new Set("math semantics annotation mrow mi mo mn ms mtext mspace msup msub msubsup mfrac msqrt mroot mstyle mtable mtr mtd mover munder munderover mpadded mphantom menclose".split(" "));
+const DROP_TAGS = new Set("script style iframe frame frameset object embed foreignobject form input button textarea select option link meta base audio video source".split(" "));
+const SAFE_ATTRS = new Set("class id title alt width height colspan rowspan scope start reversed type open data-line data-alt aria-hidden aria-label role xmlns display encoding mathvariant viewbox preserveaspectratio d x y x1 y1 x2 y2 dx dy cx cy r rx ry points transform fill fill-opacity fill-rule stroke stroke-width stroke-opacity stroke-linecap stroke-linejoin stroke-dasharray opacity font-size font-family font-weight text-anchor dominant-baseline markerwidth markerheight refx refy orient markerunits offset stop-color stop-opacity gradientunits gradienttransform spreadmethod patternunits patterntransform clippathunits maskunits".split(" "));
+const SAFE_STYLES = new Set("color background-color font-size font-family font-weight font-style text-align text-decoration vertical-align display width height min-width max-width min-height max-height margin margin-left margin-right margin-top margin-bottom padding padding-left padding-right padding-top padding-bottom border border-width border-style border-color border-top border-bottom border-left border-right border-radius position top bottom left right line-height letter-spacing white-space transform transform-origin fill fill-opacity stroke stroke-width stroke-opacity opacity overflow".split(" "));
+
+function safeUrl(value, image = false) {
+ const compact = value.trim().replace(/[\u0000-\u0020\u007f]/g, "");
+ if (image && /^data:image\/(?:png|jpeg|gif|webp|avif|bmp);base64,/i.test(compact)) return value;
+ if (compact.startsWith("#")) return value;
+ try {
+ const url = new URL(compact, window.location.href);
+ return ["http:", "https:"].includes(url.protocol) ? url.href : null;
+ } catch { return null; }
+}
+
+export function sanitizeMarkup(html, prefix) {
+ const template = document.createElement("template");
+ template.innerHTML = html;
+ const visit = (parent) => {
+ for (const node of Array.from(parent.children)) {
+ const tag = node.localName.toLowerCase();
+ if (DROP_TAGS.has(tag)) { node.remove(); continue; }
+ if (!HTML_TAGS.has(tag) && !SVG_TAGS.has(tag) && !MATH_TAGS.has(tag)) {
+ visit(node);
+ node.replaceWith(...node.childNodes);
+ continue;
+ }
+ for (const attr of Array.from(node.attributes)) {
+ const name = attr.name.toLowerCase();
+ if (name === "style") {
+ const declarations = [];
+ for (const property of Array.from(node.style)) {
+ const value = node.style.getPropertyValue(property);
+ if (SAFE_STYLES.has(property) && !/url\s*\(|expression|@|\\|\/\*|fixed|sticky/i.test(value)) {
+ declarations.push(`${property}:${value}`);
+ }
+ }
+ node.setAttribute("style", declarations.join(";"));
+ } else if (name === "href" || name === "xlink:href" || name === "src") {
+ let value = null;
+ if (attr.value.startsWith("#")) value = `#${prefix}${attr.value.slice(1)}`;
+ else if (tag === "a" && name === "href") value = safeUrl(attr.value);
+ else if (tag === "img" && name === "src") value = safeUrl(attr.value, true);
+ if (value === null) node.removeAttribute(attr.name); else node.setAttribute(attr.name, value);
+ } else if (["clip-path", "mask", "marker-start", "marker-mid", "marker-end"].includes(name) || (["fill", "stroke"].includes(name) && /url\s*\(/i.test(attr.value))) {
+ const match = /^url\(#([\w:.-]+)\)$/.exec(attr.value);
+ if (match) node.setAttribute(attr.name, `url(#${prefix}${match[1]})`); else node.removeAttribute(attr.name);
+ } else if (!SAFE_ATTRS.has(name) || /url\s*\(|javascript|expression/i.test(attr.value)) {
+ node.removeAttribute(attr.name);
+ } else if (name === "id") {
+ node.setAttribute("id", prefix + attr.value);
+ }
+ }
+ if (tag === "a" && node.hasAttribute("href") && !node.getAttribute("href").startsWith("#")) {
+ node.setAttribute("target", "_blank");
+ node.setAttribute("rel", "noopener noreferrer");
+ }
+ if (tag === "img") { node.loading = "lazy"; node.decoding = "async"; }
+ visit(node);
+ }
+ };
+ visit(template.content);
+ return template.content;
+}
+
+export function createRenderer() {
+ return new window.SoMarkDown({
+ html: true,
+ typographer: true,
+ imgDescEnabled: false,
+ lineNumbers: { enable: true, nested: true },
+ smiles: { disableColors: false },
+ toc: { includeLevel: [1, 2, 3] }
+ });
+}
+
+export function renderedNodesForRange(container, start, end) {
+ if (!Number.isInteger(start) || !Number.isInteger(end) || end <= start) return [];
+ const inRange = (node) => {
+ const line = Number(node.getAttribute("data-line"));
+ return Number.isInteger(line) && line >= start && line < end;
+ };
+ // A list container may begin in one OCR block and contain several other blocks.
+ // Highlight only whole subtrees whose mapped lines all belong to this block.
+ const candidates = Array.from(container.querySelectorAll("[data-line]"))
+ .filter((node) => inRange(node) && Array.from(node.querySelectorAll("[data-line]")).every(inRange));
+ const candidateSet = new Set(candidates);
+ return candidates.filter((node) => {
+ for (let parent = node.parentElement; parent && parent !== container; parent = parent.parentElement) {
+ if (candidateSet.has(parent)) return false;
+ }
+ return true;
+ });
+}
+
+export function sourceNodesForRange(container, start, end) {
+ if (!Number.isInteger(start) || !Number.isInteger(end) || end <= start) return [];
+ return Array.from(container.querySelectorAll("[data-source-line]"))
+ .filter((node) => Number(node.dataset.sourceLine) >= start && Number(node.dataset.sourceLine) < end);
+}
+
+export function addPageDivider(parent, previous, next) {
+ const divider = document.createElement("div");
+ divider.className = "page-divider";
+ divider.setAttribute("role", "separator");
+ divider.setAttribute("aria-label", `End of page ${previous + 1}; start of page ${next + 1}`);
+ for (const page of [previous, next]) {
+ const label = document.createElement("span");
+ label.textContent = `PAGE ${page + 1}`;
+ divider.append(label);
+ }
+ parent.append(divider);
+}
+
+export function renderSource(markdown, element) {
+ const fragment = document.createDocumentFragment();
+ String(markdown).split("\n").forEach((text, index) => {
+ const line = document.createElement("div");
+ line.className = "source-line bi-direction-jump__target";
+ line.dataset.sourceLine = String(index);
+ const number = document.createElement("span");
+ number.className = "source-line-number";
+ number.textContent = String(index + 1);
+ number.setAttribute("aria-hidden", "true");
+ const content = document.createElement("span");
+ content.className = "source-line-text";
+ content.textContent = text || "\u200b";
+ line.append(number, content);
+ fragment.append(line);
+ });
+ element.replaceChildren(fragment);
+}
diff --git a/oxr/server/demo/style/index.css b/oxr/server/demo/style/index.css
new file mode 100644
index 0000000..45c5388
--- /dev/null
+++ b/oxr/server/demo/style/index.css
@@ -0,0 +1,241 @@
+/* Adapted from SoMarkDown Viewer; see LICENSE-SoMarkDownViewer. */
+:root {
+ --bg-color: #000000;
+ --text-color: #ffffff;
+ --text-muted: #a1a1aa;
+ --text-muted-dim: rgba(161, 161, 170, 0.45);
+ --text-muted-half: rgba(161, 161, 170, 0.6);
+ --border-color: #262626;
+ --bg-navbar: #000000;
+ --bg-accent: rgba(239, 135, 27, 0.16);
+ --bg-card: #0b0b0b;
+ --input-border: #393939;
+ --input-bg: #151515;
+ --bg-editor: #050505;
+ --bg-preview: #101010;
+ --ring-color: #ef871b;
+ --accent-color: #ef871b;
+ --selection-bg-color: rgba(239, 135, 27, 0.3);
+ --jump-highlight-bg: rgb(0, 0, 0);
+ --transition-normal: 220ms ease;
+ --splitter-hit-size: 0.6875rem;
+ --nav-unit: 1rem;
+ --panel-header-height: 2.125rem;
+}
+/* Keep type and controls stable across viewport widths; honor browser font settings. */
+html { font-size: 100%; }
+* { box-sizing: border-box; }
+body { margin: 0; background: var(--bg-color); color: var(--text-color); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }
+button { font: inherit; }
+[hidden] { display: none !important; }
+.app-container { height: 100vh; height: 100dvh; display: flex; flex-direction: column; overflow: hidden; }
+.app-header { height: calc(3.5 * var(--nav-unit)); display: flex; align-items: center; justify-content: space-between; padding: 0 calc(1 * var(--nav-unit)); background: var(--bg-navbar); border-bottom: 1px solid var(--border-color); flex-shrink: 0; }
+.logo-text { display: inline-flex; align-items: center; white-space: nowrap; color: var(--text-color); font-weight: 600; font-size: calc(1.125 * var(--nav-unit)); letter-spacing: -0.025em; user-select: none; text-decoration: none; }
+.brand-accent { color: var(--accent-color); }
+.header__logo-svg {
+ width: 0;
+ height: calc(1.5 * var(--nav-unit));
+ margin-right: 0;
+ opacity: 0;
+ transition: width 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275),
+ margin-right 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275),
+ opacity 0.4s ease;
+}
+
+.logo-text:is(:hover, :focus-visible) .header__logo-svg {
+ width: calc(1.75 * var(--nav-unit));
+ margin-right: calc(0.375 * var(--nav-unit));
+ opacity: 1;
+}
+
+.header__logo-rect {
+ transform-origin: center;
+ opacity: 0;
+ transform: rotate(-90deg) scale(0);
+ transition: transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275),
+ opacity 0.4s ease;
+}
+
+.header__logo-rect--top {
+ transition-delay: 0s;
+}
+
+.header__logo-rect--middle {
+ transition-delay: 0.1s;
+}
+
+.header__logo-rect--bottom-left,
+.header__logo-rect--bottom-right {
+ transition-delay: 0.2s;
+}
+
+.logo-text:is(:hover, :focus-visible) .header__logo-rect {
+ opacity: 1;
+ transform: rotate(0deg) scale(1);
+}
+
+.logo-text:is(:hover, :focus-visible) .header__logo-rect--top {
+ transition-delay: 0.2s;
+}
+
+.logo-text:is(:hover, :focus-visible) .header__logo-rect--middle {
+ transition-delay: 0.1s;
+}
+
+.logo-text:is(:hover, :focus-visible) .header__logo-rect--bottom-left,
+.logo-text:is(:hover, :focus-visible) .header__logo-rect--bottom-right {
+ transition-delay: 0s;
+}
+
+
+.icon-btn { display: inline-flex; align-items: center; justify-content: center; border-radius: calc(0.375 * var(--nav-unit)); height: calc(2.5 * var(--nav-unit)); width: calc(2.5 * var(--nav-unit)); color: var(--text-muted); background: transparent; border: none; cursor: pointer; transition: background-color 0.2s, color 0.2s; }
+.icon-btn:hover, .text-btn:hover { background: var(--bg-accent); color: var(--accent-color); }
+button:focus-visible, [tabindex]:focus-visible { outline: 2px solid var(--ring-color); outline-offset: -2px; }
+.icon-btn:disabled { pointer-events: none; opacity: 0.4; }
+.icon-btn svg { width: calc(1 * var(--nav-unit)); height: calc(1 * var(--nav-unit)); pointer-events: none; }
+.markdown-content { flex: 1; display: flex; min-height: 0; min-width: 0; }
+.document-panels { --file-panel-width: calc((100% - var(--splitter-hit-size)) / 2); position: relative; flex: 1; display: flex; min-height: 0; min-width: 0; }
+.file-panel { flex: 0 0 var(--file-panel-width); min-width: 280px; }
+.result-panel { flex: 1 1 0; min-width: 320px; }
+.file-panel, .result-panel { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
+.panel-header { height: var(--panel-header-height); display: flex; align-items: center; padding: 0 1rem; border-bottom: 1px solid var(--border-color); flex-shrink: 0; gap: 1rem; }
+.panel-title, .tab { color: var(--text-muted); font-size: 0.75rem; font-family: monospace; text-transform: uppercase; letter-spacing: 0.05em; }
+.text-btn { border: 0; background: transparent; color: var(--text-muted); cursor: pointer; border-radius: 0.375rem; padding: 0.35rem 0.55rem; margin-left: auto; font-size: 0.75rem; }
+.tabs { display: flex; align-self: stretch; gap: 1.25rem; }
+.tab { position: relative; border: 0; background: transparent; cursor: pointer; padding: 0; }
+.tab:hover, .tab.active { color: var(--text-color); }
+.tab.active::after { content: ""; position: absolute; height: 2px; left: 0; right: 0; bottom: -1px; background: var(--accent-color); }
+.page-count { margin-left: auto; font: 0.75rem monospace; color: var(--text-muted-half); white-space: nowrap; }
+.markdown-splitter { position: relative; flex: 0 0 var(--splitter-hit-size); width: var(--splitter-hit-size); align-self: stretch; cursor: col-resize; outline: none; touch-action: none; }
+.markdown-splitter::before { content: ""; position: absolute; top: 0; bottom: 0; left: 50%; width: 1px; background: var(--border-color); transform: translateX(-50%); transition: background-color 160ms ease; }
+.markdown-splitter::after { content: ""; position: absolute; top: calc(var(--panel-header-height) - 1px); left: 0; width: 100%; height: 1px; background: var(--border-color); }
+.markdown-splitter:hover::before, .markdown-splitter:focus-visible::before, .panel-resizing .markdown-splitter::before { background: var(--accent-color); }
+.panel-resizing, .panel-resizing * { cursor: col-resize !important; user-select: none; }
+.panel-viewport { flex: 1; min-height: 0; overflow: auto; overflow-anchor: none; overscroll-behavior: contain; }
+.file-viewport, .source-viewport { background: var(--bg-editor); }
+.rendered-viewport { background: #0f0f10; }
+.layout-viewport { background: var(--bg-preview); }
+.empty-state { min-height: 100%; display: flex; flex-direction: column; gap: 0.75rem; align-items: center; justify-content: center; color: var(--text-muted-half); font-size: 0.8rem; text-align: center; padding: 2rem; }
+.upload-dropzone { width: 100%; background: transparent; border: 0; cursor: pointer; }
+.upload-dropzone:hover { background: rgba(239, 135, 27, 0.04); }
+.upload-dropzone svg { width: 2rem; height: 2rem; margin-bottom: 0.25rem; color: var(--text-muted); }
+.empty-title { color: var(--text-muted); font-size: 0.9rem; }
+.bottom-spacer { flex: 0 0 0.35rem; border-top: 1px solid var(--border-color); }
+.file-viewport, .layout-viewport { container-type: size; }
+.file-page, .layout-page { padding: 1rem 10%; }
+/* Fit both portrait and landscape pages within either image viewport, including
+ the page caption and breathing room. The SVG shares the fitted image box. */
+.file-page .page-image, .layout-page .page-image { max-width: max(1px, calc((100cqh - 3.75rem) * var(--page-ratio))); margin-inline: auto; }
+.page-label { display: flex; align-items: center; gap: 0.4rem; min-height: 1rem; margin: 0 0 0.65rem; font: 0.75rem monospace; color: var(--text-muted-half); }
+.page-download { display: inline-flex; align-items: center; justify-content: center; width: 1rem; height: 1rem; padding: 0; border: 0; border-radius: 0.2rem; background: transparent; color: var(--text-muted); cursor: pointer; }
+.page-download:hover { color: var(--accent-color); background: var(--bg-accent); }
+.page-download:disabled { opacity: 0.4; cursor: wait; }
+.page-download svg { width: 0.8rem; height: 0.8rem; pointer-events: none; }
+.page-download-error { margin-bottom: 0.65rem; font-size: 0.75rem; color: #fca5a5; overflow-wrap: anywhere; }
+.page-image { position: relative; width: 100%; background: #181818; overflow: hidden; }
+.page-image img { display: block; width: 100%; height: 100%; object-fit: contain; }
+.page-image img:not([src]) { visibility: hidden; }
+.image-error { position: absolute; inset: 0; display: grid; place-items: center; color: var(--text-muted); background: #181818; font-size: 0.8rem; padding: 1rem; }
+.layout-overlay { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
+.layout-box { fill: transparent; stroke-width: 1.5; vector-effect: non-scaling-stroke; cursor: pointer; outline: none; }
+.layout-box:hover, .layout-box:focus { fill: var(--box-color); fill-opacity: 0.15; stroke-width: 2.5; }
+.layout-box.selected { fill: var(--box-color); fill-opacity: 0.18; stroke-width: 3; }
+.layout-box--display-only { pointer-events: none; }
+.reading-line, .reading-line-outline { fill: none; vector-effect: non-scaling-stroke; pointer-events: none; }
+.reading-line { stroke: #000; stroke-width: 3; }
+.reading-line-outline { stroke: #fff; stroke-width: 5; stroke-linecap: round; }
+.layout-category-label { --layout-label-height: 1.55em; position: absolute; font: max(14px, 0.65rem)/1.35 monospace; padding: 0.1em 0.35em; background: var(--box-color); color: #fff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; pointer-events: none; }
+.layout-legend { display: flex; flex-wrap: wrap; gap: 0.5rem 1rem; padding-top: 0.8rem; font: 0.75rem monospace; color: var(--text-muted); }
+.legend-item { display: inline-flex; align-items: center; gap: 0.4rem; }
+.legend-swatch { height: 7px; width: 7px; border-radius: 2px; background: var(--box-color); }
+.rendered-page { padding: 1rem 2rem; min-height: 5rem; position: relative; contain: paint; }
+.rendered-page.somarkdown-container { background: transparent; font-size: 1rem; line-height: 1.6; }
+.rendered-page.somarkdown-container h1 { font-size: 1.4em; }
+.rendered-page.somarkdown-container h2 { font-size: 1.2em; }
+.rendered-page.somarkdown-container h3 { font-size: 1.05em; }
+.rendered-page [data-line] { margin-top: 1rem; margin-bottom: 1rem; }
+.bi-direction-jump__target { transition: background-color var(--transition-normal), border-radius var(--transition-normal); }
+.rendered-page .bi-direction-jump__target--active, .rendered-page .bi-direction-jump__target--hover { background: var(--jump-highlight-bg); border-radius: 0.3rem; }
+.rendered-page .bi-direction-jump__target--active { border-left: 3px solid var(--accent-color); margin-left: -12px; padding-left: 10px; }
+.source-page { padding: 1rem 0; min-height: 5rem; font: 0.875rem/1.6 monospace; }
+.source-line { display: grid; grid-template-columns: 3.75rem minmax(0, 1fr); min-height: 1.6em; }
+.source-line-number { user-select: none; text-align: right; padding-right: 1rem; color: var(--text-muted-dim); font-size: 0.75rem; }
+.source-line-text { white-space: pre-wrap; overflow-wrap: anywhere; padding-right: 1rem; }
+.source-line.bi-direction-jump__target--active { background: var(--bg-accent); box-shadow: inset 3px 0 var(--accent-color); }
+::selection { background: var(--selection-bg-color); color: #fff; }
+.page-divider { display: flex; flex-direction: column; align-items: center; position: relative; gap: 0.625rem; margin: 1.5rem 1rem; padding: 0.25rem 0; color: var(--text-muted-dim); font: 0.625rem/1 monospace; letter-spacing: 0.08em; }
+.page-divider::after { content: ""; height: 1px; background: rgba(161, 161, 170, 0.25); position: absolute; left: 0; right: 0; top: 50%; }
+.empty-page { color: var(--text-muted-half); font: 0.75rem monospace; padding: 1rem; }
+/* Configuration shares the viewer's quiet surfaces and orange focus accents. */
+.config-panel { flex: 0 0 18.5rem; display: flex; flex-direction: column; min-height: 0; min-width: 0; border-right: 1px solid var(--border-color); background: var(--bg-card); }
+.config-content { flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; padding: 1rem; scrollbar-width: thin; scrollbar-color: var(--input-border) transparent; }
+.config-badges { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0.4rem; margin-bottom: 1rem; }
+.resource-badge { display: flex; align-items: center; gap: 0.2rem; min-width: 0; min-height: 1.6rem; padding: 0.25rem; border: 1px solid var(--border-color); border-radius: 0.3rem; background: var(--input-bg); color: var(--text-muted); font-size: 0.625rem; line-height: 1.2; text-decoration: none; white-space: nowrap; transition: color var(--transition-normal), border-color var(--transition-normal), background-color var(--transition-normal); }
+a.resource-badge:hover { border-color: var(--accent-color); color: var(--text-color); background: var(--bg-accent); }
+.resource-badge-icon { flex: 0 0 0.75rem; width: 0.75rem; height: 0.75rem; color: #a1a1aa; }
+.resource-badge-text { display: flex; align-items: center; gap: 0.1rem; min-width: 0; }
+.resource-badge-detail { color: var(--text-muted-half); }
+.upload-button { display: flex; align-items: center; justify-content: center; gap: 0.5rem; width: 100%; min-height: 2.5rem; padding: 0.6rem; border: 1px solid rgba(239, 135, 27, 0.45); border-radius: 0.4rem; background: var(--bg-accent); color: var(--accent-color); font-size: 0.8rem; font-weight: 500; cursor: pointer; transition: background-color var(--transition-normal), border-color var(--transition-normal); }
+.upload-button svg { width: 1rem; height: 1rem; }
+.upload-button:hover { background: rgba(239, 135, 27, 0.24); border-color: var(--accent-color); }
+.upload-button:active { transform: translateY(1px); }
+.config-section { margin-top: 1.25rem; padding-top: 1.1rem; border-top: 1px solid var(--border-color); }
+.config-heading { margin: 0 0 0.9rem; color: var(--text-muted); font: 0.6875rem/1.4 monospace; letter-spacing: 0.05em; text-transform: uppercase; }
+.parameter-control + .parameter-control { margin-top: 0.85rem; }
+.parameter-label-row { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; margin-bottom: 0.4rem; font-size: 0.75rem; color: var(--text-muted); }
+.parameter-label-row input { width: 3.75rem; min-width: 0; padding: 0.3rem 0.35rem; border: 1px solid var(--input-border); border-radius: 0.3rem; background: var(--input-bg); color: var(--text-color); font: 0.75rem monospace; font-variant-numeric: tabular-nums; }
+.parameter-label-row input:hover { border-color: var(--accent-color); }
+.parameter-label-row input[aria-invalid="true"] { border-color: #fca5a5; }
+.parameter-control input[type="range"] { display: block; width: 100%; height: 1rem; margin: 0; accent-color: var(--accent-color); cursor: pointer; }
+.config-panel :is(a, input):focus-visible { outline: 2px solid var(--ring-color); outline-offset: 2px; }
+.status-heading-row { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; margin-bottom: 0.9rem; }
+.status-heading-row .config-heading { margin: 0; }
+.status-indicator { display: inline-flex; align-items: center; gap: 0.4rem; font-size: 0.6875rem; color: var(--text-muted); }
+.status-indicator::before { content: ""; width: 0.35rem; height: 0.35rem; border-radius: 50%; background: currentColor; }
+.status-indicator[data-state="parsing"], .status-indicator[data-state="completed"] { color: var(--accent-color); }
+.status-indicator[data-state="error"] { color: #fca5a5; }
+.status-details { margin: 0; font-size: 0.6875rem; line-height: 1.5; }
+.status-details > div { display: flex; justify-content: space-between; gap: 0.75rem; margin-top: 0.45rem; }
+.status-details dt { flex-shrink: 0; color: var(--text-muted); }
+.status-details dd { min-width: 0; margin: 0; text-align: right; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; }
+.status-error { margin: 0.8rem 0 0; color: #fca5a5; font-size: 0.75rem; line-height: 1.5; overflow-wrap: anywhere; white-space: pre-wrap; }
+.config-about p { margin: 0.8rem 0 0; color: var(--text-muted); font-size: 0.75rem; line-height: 1.7; overflow-wrap: anywhere; }
+
+
+@media (max-width: 960px) {
+ .markdown-content, .document-panels { flex-direction: column; }
+ .config-panel { flex: 0 1 40dvh; width: 100%; max-height: 40dvh; border-right: 0; border-bottom: 1px solid var(--border-color); }
+ .file-panel, .result-panel { flex: 1 1 0; width: 100%; min-width: 0; }
+ .file-panel { border-bottom: 1px solid var(--border-color); }
+ .markdown-splitter { display: none; }
+ .rendered-page { padding: 1rem; }
+ .panel-header { padding: 0 0.75rem; }
+}
+@media (max-width: 480px) {
+ .app-header { padding-inline: 0.75rem; --nav-unit: 0.8rem; }
+}
+@media (prefers-reduced-motion: reduce) { * { transition: none !important; scroll-behavior: auto !important; } }
+
+.block-fallback { margin: 1rem 0; padding: 0.6rem 0; }
+.fallback-label { display: block; color: var(--text-muted-half); font: 0.625rem monospace; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }
+.fallback-content { white-space: pre-wrap; overflow-wrap: anywhere; }
+
+.retry-button { margin: 0.65rem 0 0; padding: 0.35rem 0.6rem; color: var(--accent-color); border: 1px solid var(--border-color); }
+
+.header-actions { display: flex; align-items: center; gap: calc(0.5 * var(--nav-unit)); }
+.file-drop-overlay { position: fixed; inset: 0; z-index: 9; display: grid; place-items: center; padding: 2rem; background: rgba(0, 0, 0, 0.8); pointer-events: none; }
+.file-drop-overlay::before { content: ""; position: absolute; inset: 1rem; border: 2px dashed var(--accent-color); border-radius: 0.5rem; background: rgba(239, 135, 27, 0.04); }
+.file-drop-message { position: relative; display: flex; flex-direction: column; align-items: center; gap: 0.75rem; text-align: center; }
+.file-drop-message svg { width: 2.5rem; height: 2.5rem; color: var(--accent-color); }
+.file-drop-message strong { font-size: 1.1rem; font-weight: 600; }
+.file-drop-message span { color: var(--text-muted); font-size: 0.8rem; }
+.parse-progress { position: fixed; inset: 0; z-index: 10; display: grid; place-items: center; background: rgba(0, 0, 0, 0.65); cursor: wait; touch-action: none; }
+.progress-tree { list-style: none; margin: 0; padding: 0; font-size: 0.8rem; line-height: 1.5; }
+.progress-step { position: relative; display: flex; align-items: center; gap: 0.7rem; min-height: 2.5rem; color: var(--text-muted-half); }
+.progress-step:first-child::after { content: ""; position: absolute; left: calc(0.35rem - 0.5px); top: calc(50% + 0.35rem); height: calc(2.5rem - 0.7rem); width: 1px; background: var(--border-color); }
+.progress-node { flex: 0 0 0.7rem; width: 0.7rem; height: 0.7rem; border: 2px solid var(--text-muted-dim); border-radius: 50%; }
+.progress-step.active, .progress-step.complete { color: var(--text-color); }
+.progress-step.active .progress-node { border-color: var(--accent-color); border-right-color: transparent; animation: progress-spin 0.85s linear infinite; }
+.progress-step.complete .progress-node { border-color: var(--accent-color); }
+@keyframes progress-spin { to { transform: rotate(360deg); } }
+@media (prefers-reduced-motion: reduce) { .progress-step.active .progress-node { animation: none; } }
diff --git a/oxr/server/demo/vendor/deps/LICENSE-KaTeX b/oxr/server/demo/vendor/deps/LICENSE-KaTeX
new file mode 100644
index 0000000..37c6433
--- /dev/null
+++ b/oxr/server/demo/vendor/deps/LICENSE-KaTeX
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2013-2020 Khan Academy and other contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/oxr/server/demo/vendor/deps/LICENSE-highlight.js b/oxr/server/demo/vendor/deps/LICENSE-highlight.js
new file mode 100644
index 0000000..2250cc7
--- /dev/null
+++ b/oxr/server/demo/vendor/deps/LICENSE-highlight.js
@@ -0,0 +1,29 @@
+BSD 3-Clause License
+
+Copyright (c) 2006, Ivan Sagalaev.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/oxr/server/demo/vendor/deps/highlight.js.default.min.css b/oxr/server/demo/vendor/deps/highlight.js.default.min.css
new file mode 100644
index 0000000..a162d6f
--- /dev/null
+++ b/oxr/server/demo/vendor/deps/highlight.js.default.min.css
@@ -0,0 +1,11 @@
+/*!
+ Theme: Default
+ Version: 11.9.0
+ Description: Original highlight.js style
+ Author: (c) Ivan Sagalaev <[email protected]>
+ Maintainer: @highlightjs/core-team
+ Website: https://highlightjs.org/
+ License: see project LICENSE
+ Touched: 2021
+ URL: https://cdn.jsdelivr.net/npm/[email protected]/styles/default.min.css
+*/pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}.hljs{background:#f3f3f3;color:#444}.hljs-comment{color:#697070}.hljs-punctuation,.hljs-tag{color:#444a}.hljs-tag .hljs-attr,.hljs-tag .hljs-name{color:#444}.hljs-attribute,.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-name,.hljs-selector-tag{font-weight:700}.hljs-deletion,.hljs-number,.hljs-quote,.hljs-selector-class,.hljs-selector-id,.hljs-string,.hljs-template-tag,.hljs-type{color:#800}.hljs-section,.hljs-title{color:#800;font-weight:700}.hljs-link,.hljs-operator,.hljs-regexp,.hljs-selector-attr,.hljs-selector-pseudo,.hljs-symbol,.hljs-template-variable,.hljs-variable{color:#ab5656}.hljs-literal{color:#695}.hljs-addition,.hljs-built_in,.hljs-bullet,.hljs-code{color:#397300}.hljs-meta{color:#1f7199}.hljs-meta .hljs-string{color:#38a}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}
\ No newline at end of file
diff --git a/oxr/server/demo/vendor/deps/katex.min.css b/oxr/server/demo/vendor/deps/katex.min.css
new file mode 100644
index 0000000..7cbfc69
--- /dev/null
+++ b/oxr/server/demo/vendor/deps/katex.min.css
@@ -0,0 +1,6 @@
+/* 0.16.9 */
+/* https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css */
+
+@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_AMS-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_AMS-Regular.woff) format("woff"),url(katex_fonts/KaTeX_AMS-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:700;src:url(katex_fonts/KaTeX_Caligraphic-Bold.woff2) format("woff2"),url(katex_fonts/KaTeX_Caligraphic-Bold.woff) format("woff"),url(katex_fonts/KaTeX_Caligraphic-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_Caligraphic-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_Caligraphic-Regular.woff) format("woff"),url(katex_fonts/KaTeX_Caligraphic-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:700;src:url(katex_fonts/KaTeX_Fraktur-Bold.woff2) format("woff2"),url(katex_fonts/KaTeX_Fraktur-Bold.woff) format("woff"),url(katex_fonts/KaTeX_Fraktur-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_Fraktur-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_Fraktur-Regular.woff) format("woff"),url(katex_fonts/KaTeX_Fraktur-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:700;src:url(katex_fonts/KaTeX_Main-Bold.woff2) format("woff2"),url(katex_fonts/KaTeX_Main-Bold.woff) format("woff"),url(katex_fonts/KaTeX_Main-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:700;src:url(katex_fonts/KaTeX_Main-BoldItalic.woff2) format("woff2"),url(katex_fonts/KaTeX_Main-BoldItalic.woff) format("woff"),url(katex_fonts/KaTeX_Main-BoldItalic.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:400;src:url(katex_fonts/KaTeX_Main-Italic.woff2) format("woff2"),url(katex_fonts/KaTeX_Main-Italic.woff) format("woff"),url(katex_fonts/KaTeX_Main-Italic.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_Main-Regular.woff) format("woff"),url(katex_fonts/KaTeX_Main-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:700;src:url(katex_fonts/KaTeX_Math-BoldItalic.woff2) format("woff2"),url(katex_fonts/KaTeX_Math-BoldItalic.woff) format("woff"),url(katex_fonts/KaTeX_Math-BoldItalic.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:400;src:url(katex_fonts/KaTeX_Math-Italic.woff2) format("woff2"),url(katex_fonts/KaTeX_Math-Italic.woff) format("woff"),url(katex_fonts/KaTeX_Math-Italic.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:normal;font-weight:700;src:url(katex_fonts/KaTeX_SansSerif-Bold.woff2) format("woff2"),url(katex_fonts/KaTeX_SansSerif-Bold.woff) format("woff"),url(katex_fonts/KaTeX_SansSerif-Bold.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:italic;font-weight:400;src:url(katex_fonts/KaTeX_SansSerif-Italic.woff2) format("woff2"),url(katex_fonts/KaTeX_SansSerif-Italic.woff) format("woff"),url(katex_fonts/KaTeX_SansSerif-Italic.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_SansSerif-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_SansSerif-Regular.woff) format("woff"),url(katex_fonts/KaTeX_SansSerif-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Script;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_Script-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_Script-Regular.woff) format("woff"),url(katex_fonts/KaTeX_Script-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size1;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_Size1-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_Size1-Regular.woff) format("woff"),url(katex_fonts/KaTeX_Size1-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size2;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_Size2-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_Size2-Regular.woff) format("woff"),url(katex_fonts/KaTeX_Size2-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size3;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_Size3-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_Size3-Regular.woff) format("woff"),url(katex_fonts/KaTeX_Size3-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size4;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_Size4-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_Size4-Regular.woff) format("woff"),url(katex_fonts/KaTeX_Size4-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Typewriter;font-style:normal;font-weight:400;src:url(katex_fonts/KaTeX_Typewriter-Regular.woff2) format("woff2"),url(katex_fonts/KaTeX_Typewriter-Regular.woff) format("woff"),url(katex_fonts/KaTeX_Typewriter-Regular.ttf) format("truetype")}.katex{text-rendering:auto;font:normal 1.21em KaTeX_Main,Times New Roman,serif;line-height:1.2;text-indent:0}.katex *{-ms-high-contrast-adjust:none!important;border-color:currentColor}.katex .katex-version:after{content:"0.16.9"}.katex .katex-mathml{clip:rect(1px,1px,1px,1px);border:0;height:1px;overflow:hidden;padding:0;position:absolute;width:1px}.katex .katex-html>.newline{display:block}.katex .base{position:relative;white-space:nowrap;width:-webkit-min-content;width:-moz-min-content;width:min-content}.katex .base,.katex .strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathnormal{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-style:italic;font-weight:700}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathboldfrak,.katex .textboldfrak{font-family:KaTeX_Fraktur;font-weight:700}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{border-collapse:collapse;display:inline-table;table-layout:fixed}.katex .vlist-r{display:table-row}.katex .vlist{display:table-cell;position:relative;vertical-align:bottom}.katex .vlist>span{display:block;height:0;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{overflow:hidden;width:0}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{display:table-cell;font-size:1px;min-width:2px;vertical-align:bottom;width:2px}.katex .vbox{align-items:baseline;display:inline-flex;flex-direction:column}.katex .hbox{width:100%}.katex .hbox,.katex .thinbox{display:inline-flex;flex-direction:row}.katex .thinbox{max-width:0;width:0}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline,.katex .hline,.katex .mfrac .frac-line,.katex .overline .overline-line,.katex .rule,.katex .underline .underline-line{min-height:1px}.katex .mspace{display:inline-block}.katex .clap,.katex .llap,.katex .rlap{position:relative;width:0}.katex .clap>.inner,.katex .llap>.inner,.katex .rlap>.inner{position:absolute}.katex .clap>.fix,.katex .llap>.fix,.katex .rlap>.fix{display:inline-block}.katex .llap>.inner{right:0}.katex .clap>.inner,.katex .rlap>.inner{left:0}.katex .clap>.inner>span{margin-left:-50%;margin-right:50%}.katex .rule{border:0 solid;display:inline-block;position:relative}.katex .hline,.katex .overline .overline-line,.katex .underline .underline-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .hdashline{border-bottom-style:dashed;display:inline-block;width:100%}.katex .sqrt>.root{margin-left:.27777778em;margin-right:-.55555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .sizing.reset-size2.size1{font-size:.83333333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .sizing.reset-size2.size3{font-size:1.16666667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .sizing.reset-size2.size4{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .sizing.reset-size2.size6{font-size:1.66666667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .sizing.reset-size2.size10{font-size:3.45666667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .sizing.reset-size2.size11{font-size:4.14666667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .sizing.reset-size3.size1{font-size:.71428571em}.katex .fontsize-ensurer.reset-size3.size2,.katex .sizing.reset-size3.size2{font-size:.85714286em}.katex .fontsize-ensurer.reset-size3.size3,.katex .sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .sizing.reset-size3.size4{font-size:1.14285714em}.katex .fontsize-ensurer.reset-size3.size5,.katex .sizing.reset-size3.size5{font-size:1.28571429em}.katex .fontsize-ensurer.reset-size3.size6,.katex .sizing.reset-size3.size6{font-size:1.42857143em}.katex .fontsize-ensurer.reset-size3.size7,.katex .sizing.reset-size3.size7{font-size:1.71428571em}.katex .fontsize-ensurer.reset-size3.size8,.katex .sizing.reset-size3.size8{font-size:2.05714286em}.katex .fontsize-ensurer.reset-size3.size9,.katex .sizing.reset-size3.size9{font-size:2.46857143em}.katex .fontsize-ensurer.reset-size3.size10,.katex .sizing.reset-size3.size10{font-size:2.96285714em}.katex .fontsize-ensurer.reset-size3.size11,.katex .sizing.reset-size3.size11{font-size:3.55428571em}.katex .fontsize-ensurer.reset-size4.size1,.katex .sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .sizing.reset-size5.size1{font-size:.55555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .sizing.reset-size5.size2{font-size:.66666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .sizing.reset-size5.size3{font-size:.77777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .sizing.reset-size5.size4{font-size:.88888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .sizing.reset-size5.size6{font-size:1.11111111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .sizing.reset-size5.size7{font-size:1.33333333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .sizing.reset-size5.size10{font-size:2.30444444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .sizing.reset-size5.size11{font-size:2.76444444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .sizing.reset-size7.size1{font-size:.41666667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .sizing.reset-size7.size3{font-size:.58333333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .sizing.reset-size7.size4{font-size:.66666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .sizing.reset-size7.size6{font-size:.83333333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .sizing.reset-size7.size10{font-size:1.72833333em}.katex .fontsize-ensurer.reset-size7.size11,.katex .sizing.reset-size7.size11{font-size:2.07333333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .sizing.reset-size8.size1{font-size:.34722222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .sizing.reset-size8.size2{font-size:.41666667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .sizing.reset-size8.size3{font-size:.48611111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .sizing.reset-size8.size4{font-size:.55555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .sizing.reset-size8.size6{font-size:.69444444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .sizing.reset-size8.size7{font-size:.83333333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .sizing.reset-size8.size10{font-size:1.44027778em}.katex .fontsize-ensurer.reset-size8.size11,.katex .sizing.reset-size8.size11{font-size:1.72777778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .sizing.reset-size9.size1{font-size:.28935185em}.katex .fontsize-ensurer.reset-size9.size2,.katex .sizing.reset-size9.size2{font-size:.34722222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .sizing.reset-size9.size3{font-size:.40509259em}.katex .fontsize-ensurer.reset-size9.size4,.katex .sizing.reset-size9.size4{font-size:.46296296em}.katex .fontsize-ensurer.reset-size9.size5,.katex .sizing.reset-size9.size5{font-size:.52083333em}.katex .fontsize-ensurer.reset-size9.size6,.katex .sizing.reset-size9.size6{font-size:.5787037em}.katex .fontsize-ensurer.reset-size9.size7,.katex .sizing.reset-size9.size7{font-size:.69444444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .sizing.reset-size9.size8{font-size:.83333333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .sizing.reset-size9.size10{font-size:1.20023148em}.katex .fontsize-ensurer.reset-size9.size11,.katex .sizing.reset-size9.size11{font-size:1.43981481em}.katex .fontsize-ensurer.reset-size10.size1,.katex .sizing.reset-size10.size1{font-size:.24108004em}.katex .fontsize-ensurer.reset-size10.size2,.katex .sizing.reset-size10.size2{font-size:.28929605em}.katex .fontsize-ensurer.reset-size10.size3,.katex .sizing.reset-size10.size3{font-size:.33751205em}.katex .fontsize-ensurer.reset-size10.size4,.katex .sizing.reset-size10.size4{font-size:.38572806em}.katex .fontsize-ensurer.reset-size10.size5,.katex .sizing.reset-size10.size5{font-size:.43394407em}.katex .fontsize-ensurer.reset-size10.size6,.katex .sizing.reset-size10.size6{font-size:.48216008em}.katex .fontsize-ensurer.reset-size10.size7,.katex .sizing.reset-size10.size7{font-size:.57859209em}.katex .fontsize-ensurer.reset-size10.size8,.katex .sizing.reset-size10.size8{font-size:.69431051em}.katex .fontsize-ensurer.reset-size10.size9,.katex .sizing.reset-size10.size9{font-size:.83317261em}.katex .fontsize-ensurer.reset-size10.size10,.katex .sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .sizing.reset-size10.size11{font-size:1.19961427em}.katex .fontsize-ensurer.reset-size11.size1,.katex .sizing.reset-size11.size1{font-size:.20096463em}.katex .fontsize-ensurer.reset-size11.size2,.katex .sizing.reset-size11.size2{font-size:.24115756em}.katex .fontsize-ensurer.reset-size11.size3,.katex .sizing.reset-size11.size3{font-size:.28135048em}.katex .fontsize-ensurer.reset-size11.size4,.katex .sizing.reset-size11.size4{font-size:.32154341em}.katex .fontsize-ensurer.reset-size11.size5,.katex .sizing.reset-size11.size5{font-size:.36173633em}.katex .fontsize-ensurer.reset-size11.size6,.katex .sizing.reset-size11.size6{font-size:.40192926em}.katex .fontsize-ensurer.reset-size11.size7,.katex .sizing.reset-size11.size7{font-size:.48231511em}.katex .fontsize-ensurer.reset-size11.size8,.katex .sizing.reset-size11.size8{font-size:.57877814em}.katex .fontsize-ensurer.reset-size11.size9,.katex .sizing.reset-size11.size9{font-size:.69453376em}.katex .fontsize-ensurer.reset-size11.size10,.katex .sizing.reset-size11.size10{font-size:.83360129em}.katex .fontsize-ensurer.reset-size11.size11,.katex .sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{display:inline-block;width:.12em}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .accent>.vlist-t,.katex .op-limits>.vlist-t{text-align:center}.katex .accent .accent-body{position:relative}.katex .accent .accent-body:not(.accent-full){width:0}.katex .overlay{display:block}.katex .mtable .vertical-separator{display:inline-block;min-width:1px}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{fill:currentColor;stroke:currentColor;fill-rule:nonzero;fill-opacity:1;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;display:block;height:inherit;position:absolute;width:100%}.katex svg path{stroke:none}.katex img{border-style:none;max-height:none;max-width:none;min-height:0;min-width:0}.katex .stretchy{display:block;overflow:hidden;position:relative;width:100%}.katex .stretchy:after,.katex .stretchy:before{content:""}.katex .hide-tail{overflow:hidden;position:relative;width:100%}.katex .halfarrow-left{left:0;overflow:hidden;position:absolute;width:50.2%}.katex .halfarrow-right{overflow:hidden;position:absolute;right:0;width:50.2%}.katex .brace-left{left:0;overflow:hidden;position:absolute;width:25.1%}.katex .brace-center{left:25%;overflow:hidden;position:absolute;width:50%}.katex .brace-right{overflow:hidden;position:absolute;right:0;width:25.1%}.katex .x-arrow-pad{padding:0 .5em}.katex .cd-arrow-pad{padding:0 .55556em 0 .27778em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{border:.04em solid;box-sizing:border-box}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .sout{border-bottom-style:solid;border-bottom-width:.08em}.katex .angl{border-right:.049em solid;border-top:.049em solid;box-sizing:border-box;margin-right:.03889em}.katex .anglpad{padding:0 .03889em}.katex .eqn-num:before{content:"(" counter(katexEqnNo) ")";counter-increment:katexEqnNo}.katex .mml-eqn-num:before{content:"(" counter(mmlEqnNo) ")";counter-increment:mmlEqnNo}.katex .mtr-glue{width:50%}.katex .cd-vert-arrow{display:inline-block;position:relative}.katex .cd-label-left{display:inline-block;position:absolute;right:calc(50% + .3em);text-align:left}.katex .cd-label-right{display:inline-block;left:calc(50% + .3em);position:absolute;text-align:right}.katex-display{display:block;margin:1em 0;text-align:center}.katex-display>.katex{display:block;text-align:center;white-space:nowrap}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.tag{left:0;right:auto}.katex-display.fleqn>.katex{padding-left:2em;text-align:left}body{counter-reset:katexEqnNo mmlEqnNo}
+
+
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_AMS-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_AMS-Regular.ttf
new file mode 100644
index 0000000..c6f9a5e
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_AMS-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_AMS-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_AMS-Regular.woff
new file mode 100644
index 0000000..b804d7b
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_AMS-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_AMS-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_AMS-Regular.woff2
new file mode 100644
index 0000000..0acaaff
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_AMS-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Bold.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Bold.ttf
new file mode 100644
index 0000000..9ff4a5e
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Bold.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Bold.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Bold.woff
new file mode 100644
index 0000000..9759710
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Bold.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Bold.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Bold.woff2
new file mode 100644
index 0000000..f390922
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Bold.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Regular.ttf
new file mode 100644
index 0000000..f522294
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Regular.woff
new file mode 100644
index 0000000..9bdd534
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Regular.woff2
new file mode 100644
index 0000000..75344a1
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Caligraphic-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Bold.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Bold.ttf
new file mode 100644
index 0000000..4e98259
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Bold.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Bold.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Bold.woff
new file mode 100644
index 0000000..e7730f6
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Bold.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Bold.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Bold.woff2
new file mode 100644
index 0000000..395f28b
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Bold.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Regular.ttf
new file mode 100644
index 0000000..b8461b2
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Regular.woff
new file mode 100644
index 0000000..acab069
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Regular.woff2
new file mode 100644
index 0000000..735f694
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Fraktur-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Bold.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Bold.ttf
new file mode 100644
index 0000000..4060e62
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Bold.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Bold.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Bold.woff
new file mode 100644
index 0000000..f38136a
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Bold.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Bold.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Bold.woff2
new file mode 100644
index 0000000..ab2ad21
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Bold.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-BoldItalic.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-BoldItalic.ttf
new file mode 100644
index 0000000..dc00797
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-BoldItalic.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-BoldItalic.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-BoldItalic.woff
new file mode 100644
index 0000000..67807b0
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-BoldItalic.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-BoldItalic.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-BoldItalic.woff2
new file mode 100644
index 0000000..5931794
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-BoldItalic.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Italic.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Italic.ttf
new file mode 100644
index 0000000..0e9b0f3
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Italic.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Italic.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Italic.woff
new file mode 100644
index 0000000..6f43b59
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Italic.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Italic.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Italic.woff2
new file mode 100644
index 0000000..b50920e
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Italic.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Regular.ttf
new file mode 100644
index 0000000..dd45e1e
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Regular.woff
new file mode 100644
index 0000000..21f5812
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Regular.woff2
new file mode 100644
index 0000000..eb24a7b
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Main-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-BoldItalic.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-BoldItalic.ttf
new file mode 100644
index 0000000..728ce7a
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-BoldItalic.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-BoldItalic.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-BoldItalic.woff
new file mode 100644
index 0000000..0ae390d
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-BoldItalic.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-BoldItalic.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-BoldItalic.woff2
new file mode 100644
index 0000000..2965702
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-BoldItalic.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-Italic.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-Italic.ttf
new file mode 100644
index 0000000..70d559b
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-Italic.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-Italic.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-Italic.woff
new file mode 100644
index 0000000..eb5159d
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-Italic.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-Italic.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-Italic.woff2
new file mode 100644
index 0000000..215c143
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Math-Italic.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Bold.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Bold.ttf
new file mode 100644
index 0000000..2f65a8a
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Bold.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Bold.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Bold.woff
new file mode 100644
index 0000000..8d47c02
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Bold.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Bold.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Bold.woff2
new file mode 100644
index 0000000..cfaa3bd
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Bold.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Italic.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Italic.ttf
new file mode 100644
index 0000000..d5850df
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Italic.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Italic.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Italic.woff
new file mode 100644
index 0000000..7e02df9
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Italic.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Italic.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Italic.woff2
new file mode 100644
index 0000000..349c06d
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Italic.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Regular.ttf
new file mode 100644
index 0000000..537279f
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Regular.woff
new file mode 100644
index 0000000..31b8482
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Regular.woff2
new file mode 100644
index 0000000..a90eea8
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_SansSerif-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Script-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Script-Regular.ttf
new file mode 100644
index 0000000..fd679bf
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Script-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Script-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Script-Regular.woff
new file mode 100644
index 0000000..0e7da82
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Script-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Script-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Script-Regular.woff2
new file mode 100644
index 0000000..b3048fc
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Script-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size1-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size1-Regular.ttf
new file mode 100644
index 0000000..871fd7d
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size1-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size1-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size1-Regular.woff
new file mode 100644
index 0000000..7f292d9
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size1-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size1-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size1-Regular.woff2
new file mode 100644
index 0000000..c5a8462
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size1-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size2-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size2-Regular.ttf
new file mode 100644
index 0000000..7a212ca
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size2-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size2-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size2-Regular.woff
new file mode 100644
index 0000000..d241d9b
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size2-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size2-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size2-Regular.woff2
new file mode 100644
index 0000000..e1bccfe
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size2-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size3-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size3-Regular.ttf
new file mode 100644
index 0000000..00bff34
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size3-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size3-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size3-Regular.woff
new file mode 100644
index 0000000..e6e9b65
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size3-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size3-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size3-Regular.woff2
new file mode 100644
index 0000000..249a286
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size3-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size4-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size4-Regular.ttf
new file mode 100644
index 0000000..74f0892
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size4-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size4-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size4-Regular.woff
new file mode 100644
index 0000000..e1ec545
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size4-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size4-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size4-Regular.woff2
new file mode 100644
index 0000000..680c130
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Size4-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Typewriter-Regular.ttf b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Typewriter-Regular.ttf
new file mode 100644
index 0000000..c83252c
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Typewriter-Regular.ttf differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Typewriter-Regular.woff b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Typewriter-Regular.woff
new file mode 100644
index 0000000..2432419
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Typewriter-Regular.woff differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Typewriter-Regular.woff2 b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Typewriter-Regular.woff2
new file mode 100644
index 0000000..771f1af
Binary files /dev/null and b/oxr/server/demo/vendor/deps/katex_fonts/KaTeX_Typewriter-Regular.woff2 differ
diff --git a/oxr/server/demo/vendor/deps/katex_fonts/OFL.txt b/oxr/server/demo/vendor/deps/katex_fonts/OFL.txt
new file mode 100644
index 0000000..0e6abe5
--- /dev/null
+++ b/oxr/server/demo/vendor/deps/katex_fonts/OFL.txt
@@ -0,0 +1,138 @@
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_AMS.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Caligraphic.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Fraktur.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Main.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Math.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_SansSerif.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Script.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Size1.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Size2.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Size3.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Size4.
+
+Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
+Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>),
+with Reserved Font Name KaTeX_Typewriter.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+The notices above are retained from the bundled fonts' name-table metadata.
+The license below is from https://openfontlicense.org/documents/OFL.txt
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/oxr/server/demo/vendor/somarkdown/VERSION b/oxr/server/demo/vendor/somarkdown/VERSION
new file mode 100644
index 0000000..f0bb29e
--- /dev/null
+++ b/oxr/server/demo/vendor/somarkdown/VERSION
@@ -0,0 +1 @@
+1.3.0
diff --git a/oxr/server/demo/vendor/somarkdown/somarkdown.css b/oxr/server/demo/vendor/somarkdown/somarkdown.css
new file mode 100644
index 0000000..8d873c0
--- /dev/null
+++ b/oxr/server/demo/vendor/somarkdown/somarkdown.css
@@ -0,0 +1,591 @@
+@charset "UTF-8";
+.somarkdown-container {
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
+ line-height: 1.6;
+ word-wrap: break-word;
+}
+.somarkdown-container h1, .somarkdown-container h2, .somarkdown-container h3, .somarkdown-container h4, .somarkdown-container h5, .somarkdown-container h6 {
+ margin-top: 24px;
+ margin-bottom: 16px;
+ font-weight: 600;
+ line-height: 1.25;
+ color: var(--text-color);
+}
+.somarkdown-container h1 {
+ font-size: 2em;
+ padding-bottom: 0.3em;
+ border-bottom: 1px solid var(--h1-border-color);
+}
+.somarkdown-container h2 {
+ font-size: 1.5em;
+ padding-bottom: 0.3em;
+ border-bottom: 1px solid var(--h2-border-color);
+}
+.somarkdown-container h3 {
+ font-size: 1.25em;
+}
+.somarkdown-container h4 {
+ font-size: 1em;
+}
+.somarkdown-container h5 {
+ font-size: 0.875em;
+}
+.somarkdown-container h6 {
+ font-size: 0.85em;
+ color: var(--h6-color);
+}
+.somarkdown-container blockquote {
+ margin: 0;
+ padding: 0 1em;
+ color: var(--blockquote-text-color);
+ border-left: 0.25em solid var(--blockquote-border-color);
+}
+.somarkdown-container hr {
+ border: none;
+ height: 1px;
+ background-color: var(--hr-bg-color);
+}
+.somarkdown-container table {
+ display: block;
+ width: max-content;
+ max-width: 100%;
+ margin: 1rem auto;
+ overflow-x: auto;
+ border-collapse: collapse;
+}
+.somarkdown-container table th, .somarkdown-container table td {
+ border: 1px solid var(--table-border-color);
+ padding: 0.5rem 1rem;
+}
+.somarkdown-container img {
+ max-width: 100%;
+ width: var(--img-width);
+ margin: 0 auto;
+ display: block;
+ transition: transform 0.3s ease, box-shadow 0.3s ease, border-radius 0.3s ease;
+}
+.somarkdown-container img:hover {
+ transform: scale(var(--img-hover-scale));
+ box-shadow: var(--img-hover-shadow);
+ border-radius: var(--img-hover-radius);
+}
+.somarkdown-container p img {
+ display: inline-block;
+ max-width: var(--img-width);
+ vertical-align: middle;
+ margin: 0 0.2em;
+}
+.somarkdown-container ul, .somarkdown-container ol {
+ padding-left: 2em;
+}
+.somarkdown-container ul li::marker, .somarkdown-container ol li::marker {
+ color: var(--list-marker-color);
+}
+.somarkdown-container a {
+ text-decoration: none;
+ color: var(--link-color);
+}
+.somarkdown-container a:visited {
+ color: var(--link-color);
+}
+.somarkdown-container a:hover {
+ text-decoration: underline;
+}
+
+/* Katex styles are imported via CDN or standard css in the example,
+ but we should provide overrides or base structure if needed */
+.katex-block {
+ overflow-x: auto;
+ overflow-y: hidden;
+ text-align: center;
+}
+
+.table-of-contents ul {
+ list-style: none;
+ padding-left: 1.5em;
+}
+.table-of-contents li {
+ margin-bottom: 0.5em;
+ position: relative;
+ padding-left: 1.2em;
+}
+.table-of-contents li::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: 0.4em;
+ width: 6px;
+ height: 6px;
+ border: 1px solid var(--toc-marker-color);
+ border-radius: 50%;
+ box-shadow: var(--toc-marker-glow);
+ background: transparent;
+}
+.table-of-contents a {
+ text-decoration: none;
+ color: var(--toc-text-color);
+}
+.table-of-contents a:visited {
+ color: var(--toc-text-color);
+}
+.table-of-contents a:hover {
+ text-decoration: underline;
+}
+
+.somarkdown-container code, .somarkdown-container kbd, .somarkdown-container pre {
+ font-family: var(--code-font-family);
+ font-size: 1em;
+}
+.somarkdown-container code {
+ padding: 0.2em 0.4em;
+ margin: 0;
+ font-size: 85%;
+ background-color: var(--code-bg-color);
+ border-radius: 6px;
+}
+.somarkdown-container pre {
+ margin-top: 0;
+ margin-bottom: 16px;
+ word-wrap: normal;
+ padding: 16px;
+ background-color: var(--pre-bg-color);
+ border-radius: 6px;
+ font-size: 85%;
+ line-height: 1.45;
+ overflow-x: auto;
+ position: relative;
+}
+.somarkdown-container pre code {
+ padding: 0;
+ margin: 0;
+ font-size: 100%;
+ word-break: normal;
+ white-space: pre;
+ background: transparent;
+ border: 0;
+}
+.somarkdown-container pre code.hljs {
+ display: block;
+ overflow-x: auto;
+ padding: 0;
+ background-color: transparent;
+ border-radius: 0;
+ font-size: 100%;
+ line-height: inherit;
+}
+.somarkdown-container {
+ /* Language Tag Base Style */
+}
+.somarkdown-container pre code.language-makefile::before, .somarkdown-container pre code.language-diff::before, .somarkdown-container pre code.language-markdown::before, .somarkdown-container pre code.language-md::before, .somarkdown-container pre code.language-latex::before, .somarkdown-container pre code.language-tex::before, .somarkdown-container pre code.language-dockerfile::before, .somarkdown-container pre code.language-docker::before, .somarkdown-container pre code.language-shell::before, .somarkdown-container pre code.language-sh::before, .somarkdown-container pre code.language-bash::before, .somarkdown-container pre code.language-sql::before, .somarkdown-container pre code.language-xml::before, .somarkdown-container pre code.language-yml::before, .somarkdown-container pre code.language-yaml::before, .somarkdown-container pre code.language-json::before, .somarkdown-container pre code.language-less::before, .somarkdown-container pre code.language-sass::before, .somarkdown-container pre code.language-scss::before, .somarkdown-container pre code.language-css::before, .somarkdown-container pre code.language-html::before, .somarkdown-container pre code.language-rs::before, .somarkdown-container pre code.language-rust::before, .somarkdown-container pre code.language-golang::before, .somarkdown-container pre code.language-go::before, .somarkdown-container pre code.language-c\#::before, .somarkdown-container pre code.language-csharp::before, .somarkdown-container pre code.language-cs::before, .somarkdown-container pre code.language-c\+\+::before, .somarkdown-container pre code.language-cpp::before, .somarkdown-container pre code.language-c::before, .somarkdown-container pre code.language-java::before, .somarkdown-container pre code.language-ruby::before, .somarkdown-container pre code.language-rb::before, .somarkdown-container pre code.language-python::before, .somarkdown-container pre code.language-py::before, .somarkdown-container pre code.language-typescript::before, .somarkdown-container pre code.language-ts::before, .somarkdown-container pre code.language-javascript::before, .somarkdown-container pre code.language-js::before {
+ position: absolute;
+ top: 16px;
+ right: 16px;
+ left: auto;
+ padding: 4px 10px;
+ font-size: 12px;
+ font-family: var(--code-font-family);
+ font-weight: 600;
+ line-height: 1;
+ color: var(--code-tag-text-color);
+ background-color: var(--code-tag-bg);
+ border-radius: 6px;
+ z-index: 1;
+ pointer-events: none;
+}
+.somarkdown-container {
+ /* Language Tag Content Mapping */
+}
+.somarkdown-container pre code.language-js::before {
+ content: "js";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-javascript::before {
+ content: "js";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-ts::before {
+ content: "ts";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-typescript::before {
+ content: "ts";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-py::before {
+ content: "py";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-python::before {
+ content: "py";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-rb::before {
+ content: "rb";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-ruby::before {
+ content: "rb";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-java::before {
+ content: "java";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-c::before {
+ content: "c";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-cpp::before {
+ content: "cpp";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-c\+\+::before {
+ content: "cpp";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-cs::before {
+ content: "c#";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-csharp::before {
+ content: "c#";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-c\#::before {
+ content: "c#";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-go::before {
+ content: "go";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-golang::before {
+ content: "go";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-rust::before {
+ content: "rust";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-rs::before {
+ content: "rust";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-html::before {
+ content: "html";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-css::before {
+ content: "css";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-scss::before {
+ content: "scss";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-sass::before {
+ content: "sass";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-less::before {
+ content: "less";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-json::before {
+ content: "json";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-yaml::before {
+ content: "yaml";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-yml::before {
+ content: "yaml";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-xml::before {
+ content: "xml";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-sql::before {
+ content: "sql";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-bash::before {
+ content: "bash";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-sh::before {
+ content: "sh";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-shell::before {
+ content: "shell";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-docker::before {
+ content: "docker";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-dockerfile::before {
+ content: "docker";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-tex::before {
+ content: "tex";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-latex::before {
+ content: "latex";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-md::before {
+ content: "md";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-markdown::before {
+ content: "md";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-diff::before {
+ content: "diff";
+ text-transform: uppercase;
+}
+.somarkdown-container pre code.language-makefile::before {
+ content: "make";
+ text-transform: uppercase;
+}
+
+.somarkdown-container caption {
+ caption-side: top;
+ text-align: center;
+ color: var(--caption-color);
+ font-size: var(--caption-font-size);
+ margin-bottom: 0.5em;
+ padding: 0.5em;
+}
+.somarkdown-container figure {
+ margin: 1em auto;
+ display: table;
+ max-width: 100%;
+ text-align: center;
+}
+.somarkdown-container figure img {
+ display: block;
+ margin: 0 auto;
+ max-width: 100%;
+}
+.somarkdown-container figure figcaption {
+ display: block;
+ text-align: center;
+ color: var(--caption-color);
+ font-size: var(--caption-font-size);
+ margin-top: 0.5em;
+}
+
+.somarkdown-container p.img-frame, .somarkdown-container figure.img-frame {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ min-width: 80%;
+ max-width: 100%;
+ width: fit-content;
+ margin: 2.5em auto;
+ padding: 1.5em;
+ border: 1px solid var(--img-frame-border-color); /* Thinner border, neutral color */
+ border-radius: 6px; /* Rounded corners */
+ position: relative;
+ box-sizing: border-box;
+ color: var(--img-frame-color);
+}
+.somarkdown-container p.img-frame::before, .somarkdown-container figure.img-frame::before {
+ content: "图片理解";
+ position: absolute;
+ top: -0.9em;
+ left: 2em;
+ background-color: var(--img-frame-label-bg);
+ color: var(--img-frame-color);
+ padding: 0.2em 0.8em;
+ border-radius: 4px;
+ font-size: 0.9em;
+ font-weight: normal; /* Removed bold */
+ line-height: 1.4;
+ white-space: nowrap;
+ z-index: 1; /* Ensure it's above border */
+}
+.somarkdown-container p.img-frame::after, .somarkdown-container figure.img-frame::after {
+ content: attr(data-alt);
+ display: block;
+ width: 100%;
+ margin-bottom: 1em;
+ order: 1;
+ text-align: left;
+ font-size: 1em;
+ line-height: 1.6;
+ white-space: pre-wrap;
+}
+.somarkdown-container p.img-frame img, .somarkdown-container figure.img-frame img {
+ order: 2;
+ margin: 0;
+}
+.somarkdown-container p.img-frame figcaption, .somarkdown-container figure.img-frame figcaption {
+ order: 3;
+ width: 100%;
+ margin-top: 0.5em;
+}
+
+/* Variables should be defined in _variables.scss */
+/* Solid Very Light Orange */
+/* Solid Dark Orange-ish for Dark Mode */
+/* Default Theme */
+:root {
+ --text-color: #24292e;
+ --bg-color: #ffffff;
+ --table-border-color: #dfe2e5;
+ --caption-color: #6a737d;
+ --caption-font-size: 0.9em;
+ --img-width: 30%;
+ --img-hover-scale: 1.02;
+ --img-hover-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
+ --img-hover-radius: 4px;
+ --code-bg-color: rgba(27, 31, 35, 0.05);
+ --pre-bg-color: #f6f8fa;
+ --blockquote-text-color: #6a737d;
+ --blockquote-border-color: #dfe2e5;
+ --code-font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;
+ --h1-border-color: #eaecef;
+ --h2-border-color: #eaecef;
+ --h6-color: #6a737d;
+ --list-marker-color: #EF871B;
+ --toc-marker-color: #EF871B;
+ --toc-marker-glow: 0 0 5px rgba(239, 135, 27, 0.4);
+ --toc-text-color: #EF871B;
+ --link-color: #EF871B;
+ --hr-bg-color: rgba(0, 0, 0, 0.5019607843);
+ --code-tag-bg: #ffffff;
+ --code-tag-text-color: #EF871B;
+ --somarkdown-smiles-theme: light;
+ --img-frame-color: #EF871B;
+ --img-frame-border-color: #dfe2e5;
+ --img-frame-label-bg: #FFF5EB;
+}
+
+.somarkdown-container {
+ color: var(--text-color);
+ background-color: var(--bg-color);
+ --somarkdown-smiles-color-text: var(--text-color);
+}
+
+/* Light Theme */
+.theme-light {
+ --text-color: #24292e;
+ --bg-color: #ffffff;
+ --table-border-color: #dfe2e5;
+ --caption-color: #6a737d;
+ --caption-font-size: 0.9em;
+ --img-width: 30%;
+ --img-hover-scale: 1.02;
+ --img-hover-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
+ --img-hover-radius: 4px;
+ --code-bg-color: rgba(27, 31, 35, 0.05);
+ --pre-bg-color: #f6f8fa;
+ --blockquote-text-color: #6a737d;
+ --blockquote-border-color: #dfe2e5;
+ --code-font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;
+ --h1-border-color: #eaecef;
+ --h2-border-color: #eaecef;
+ --h6-color: #6a737d;
+ --list-marker-color: #EF871B;
+ --toc-marker-color: #EF871B;
+ --toc-marker-glow: 0 0 5px rgba(239, 135, 27, 0.4);
+ --toc-text-color: #EF871B;
+ --link-color: #EF871B;
+ --hr-bg-color: rgba(0, 0, 0, 0.5019607843);
+ --code-tag-bg: #ffffff;
+ --code-tag-text-color: #EF871B;
+ --somarkdown-smiles-theme: light;
+ --img-frame-color: #EF871B;
+ --img-frame-border-color: #dfe2e5;
+ --img-frame-label-bg: #FFF5EB;
+ color: var(--text-color);
+ background-color: var(--bg-color);
+}
+
+/* Dark Theme */
+.theme-dark {
+ --text-color: #c9d1d9;
+ --bg-color: #0d1117;
+ --table-border-color: #30363d;
+ --caption-color: #8b949e;
+ --caption-font-size: 0.9em;
+ --img-width: 30%;
+ --img-hover-scale: 1.02;
+ --img-hover-shadow: 0 0 10px rgba(255, 255, 255, 0.6);
+ --img-hover-radius: 4px;
+ --code-bg-color: rgba(110, 118, 129, 0.4);
+ --pre-bg-color: #161b22;
+ --blockquote-text-color: #8b949e;
+ --blockquote-border-color: #30363d;
+ --code-font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;
+ --h1-border-color: #21262d;
+ --h2-border-color: #21262d;
+ --h6-color: #8b949e;
+ --list-marker-color: #EF871B;
+ --toc-marker-color: #EF871B;
+ --toc-marker-glow: 0 0 5px rgba(239, 135, 27, 0.4);
+ --toc-text-color: #EF871B;
+ --link-color: #EF871B;
+ --hr-bg-color: rgba(255, 255, 255, 0.5019607843);
+ --code-tag-bg: #0d1117;
+ --code-tag-text-color: #EF871B;
+ --somarkdown-smiles-theme: dark;
+ --img-frame-color: #EF871B;
+ --img-frame-border-color: #30363d;
+ --img-frame-label-bg: #3E2C1E;
+ color: var(--text-color);
+ background-color: var(--bg-color);
+}
+
+/* Academic Theme - Serif fonts, more formal */
+.theme-academic {
+ --text-color: #333;
+ --bg-color: #fff;
+ --table-border-color: #dfe2e5;
+ --caption-color: #6a737d;
+ --caption-font-size: 0.9em;
+ --img-width: 30%;
+ --img-hover-scale: 1.02;
+ --img-hover-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
+ --img-hover-radius: 4px;
+ --code-bg-color: rgba(27, 31, 35, 0.05);
+ --pre-bg-color: #f6f8fa;
+ --blockquote-text-color: #6a737d;
+ --blockquote-border-color: #dfe2e5;
+ --code-font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;
+ --h1-border-color: #eaecef;
+ --h2-border-color: #eaecef;
+ --h6-color: #000000;
+ --list-marker-color: #000000;
+ --toc-marker-color: #000000;
+ --toc-marker-glow: none;
+ --toc-text-color: #000000;
+ --link-color: #0969da;
+ --hr-bg-color: rgba(0, 0, 0, 0.5019607843);
+ --code-tag-bg: #ffffff;
+ --code-tag-text-color: #EF871B;
+ --somarkdown-smiles-theme: light;
+ --img-frame-color: #EF871B;
+ --img-frame-border-color: #dfe2e5;
+ --img-frame-label-bg: #FFF5EB;
+ font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
+ color: var(--text-color);
+ background-color: var(--bg-color);
+}
+.theme-academic h1, .theme-academic h2, .theme-academic h3 {
+ border-bottom: 1px solid #eaecef;
+ padding-bottom: 0.3em;
+}
+.theme-academic h1 {
+ text-align: center;
+}
+/*# sourceMappingURL=somarkdown.css.map */
\ No newline at end of file
diff --git a/oxr/server/demo/vendor/somarkdown/somarkdown.umd.min.js b/oxr/server/demo/vendor/somarkdown/somarkdown.umd.min.js
new file mode 100644
index 0000000..a90c9f4
--- /dev/null
+++ b/oxr/server/demo/vendor/somarkdown/somarkdown.umd.min.js
@@ -0,0 +1,59 @@
+!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).SoMarkDown=t()}(this,function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t,r){return t&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,d(n.key),n)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function n(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=u(e))||t){r&&(e=r);var n=0,a=function(){};return{s:a,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==r.return||r.return()}finally{if(s)throw i}}}}function a(e,t,r){return(t=d(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function o(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?i(Object(r),!0).forEach(function(t){a(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function s(e,t){return s=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},s(e,t)}function l(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,i,o,s=[],l=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t);else for(;!(l=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);l=!0);}catch(e){c=!0,a=e}finally{try{if(!l&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(c)throw a}}return s}}(e,t)||u(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||u(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function u(t,r){if(t){if("string"==typeof t)return e(t,r);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?e(t,r):void 0}}function p(){p=function(e,t){return new r(e,void 0,t)};var e=RegExp.prototype,t=new WeakMap;function r(e,n,a){var i=RegExp(e,n);return t.set(i,a||t.get(e)),s(i,r.prototype)}function n(e,r){var n=t.get(r);return Object.keys(n).reduce(function(t,r){var a=n[r];if("number"==typeof a)t[r]=e[a];else{for(var i=0;void 0===e[a[i]]&&i+1<a.length;)i++;t[r]=e[a[i]]}return t},Object.create(null))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&s(e,t)}(r,RegExp),r.prototype.exec=function(t){var r=e.exec.call(this,t);if(r){r.groups=n(r,this);var a=r.indices;a&&(a.groups=n(a,this))}return r},r.prototype[Symbol.replace]=function(r,a){if("string"==typeof a){var i=t.get(this);return e[Symbol.replace].call(this,r,a.replace(/\$<([^>]+)(>|$)/g,function(e,t,r){if(""===r)return e;var n=i[t];return Array.isArray(n)?"$"+n.join("$"):"number"==typeof n?"$"+n:""}))}if("function"==typeof a){var o=this;return e[Symbol.replace].call(this,r,function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(n(e,o)),a.apply(this,e)})}return e[Symbol.replace].call(this,r,a)},p.apply(this,arguments)}const _={};function m(e,t){"string"!=typeof t&&(t=m.defaultChars);const r=function(e){let t=_[e];if(t)return t;t=_[e]=[];for(let e=0;e<128;e++){const r=String.fromCharCode(e);t.push(r)}for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);t[n]="%"+("0"+n.toString(16).toUpperCase()).slice(-2)}return t}(t);return e.replace(/(%[a-f0-9]{2})+/gi,function(e){let t="";for(let n=0,a=e.length;n<a;n+=3){const i=parseInt(e.slice(n+1,n+3),16);if(i<128)t+=r[i];else{if(192==(224&i)&&n+3<a){const r=parseInt(e.slice(n+4,n+6),16);if(128==(192&r)){const e=i<<6&1984|63&r;t+=e<128?"��":String.fromCharCode(e),n+=3;continue}}if(224==(240&i)&&n+6<a){const r=parseInt(e.slice(n+4,n+6),16),a=parseInt(e.slice(n+7,n+9),16);if(128==(192&r)&&128==(192&a)){const e=i<<12&61440|r<<6&4032|63&a;t+=e<2048||e>=55296&&e<=57343?"���":String.fromCharCode(e),n+=6;continue}}if(240==(248&i)&&n+9<a){const r=parseInt(e.slice(n+4,n+6),16),a=parseInt(e.slice(n+7,n+9),16),o=parseInt(e.slice(n+10,n+12),16);if(128==(192&r)&&128==(192&a)&&128==(192&o)){let e=i<<18&1835008|r<<12&258048|a<<6&4032|63&o;e<65536||e>1114111?t+="����":(e-=65536,t+=String.fromCharCode(55296+(e>>10),56320+(1023&e))),n+=9;continue}}t+="�"}}return t})}m.defaultChars=";/?:@&=+$,#",m.componentChars="";const g={};function h(e,t,r){"string"!=typeof t&&(r=t,t=h.defaultChars),void 0===r&&(r=!0);const n=function(e){let t=g[e];if(t)return t;t=g[e]=[];for(let e=0;e<128;e++){const r=String.fromCharCode(e);/^[0-9a-z]$/i.test(r)?t.push(r):t.push("%"+("0"+e.toString(16).toUpperCase()).slice(-2))}for(let r=0;r<e.length;r++)t[e.charCodeAt(r)]=e[r];return t}(t);let a="";for(let t=0,i=e.length;t<i;t++){const o=e.charCodeAt(t);if(r&&37===o&&t+2<i&&/^[0-9a-f]{2}$/i.test(e.slice(t+1,t+3)))a+=e.slice(t,t+3),t+=2;else if(o<128)a+=n[o];else if(o>=55296&&o<=57343){if(o>=55296&&o<=56319&&t+1<i){const r=e.charCodeAt(t+1);if(r>=56320&&r<=57343){a+=encodeURIComponent(e[t]+e[t+1]),t++;continue}}a+="%EF%BF%BD"}else a+=encodeURIComponent(e[t])}return a}function f(e){let t="";return t+=e.protocol||"",t+=e.slashes?"//":"",t+=e.auth?e.auth+"@":"",e.hostname&&-1!==e.hostname.indexOf(":")?t+="["+e.hostname+"]":t+=e.hostname||"",t+=e.port?":"+e.port:"",t+=e.pathname||"",t+=e.search||"",t+=e.hash||"",t}function E(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null}h.defaultChars=";/?:@&=+$,-_.!~*'()#",h.componentChars="-_.!~*'()";const b=/^([a-z0-9.+-]+:)/i,S=/:[0-9]*$/,v=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,T=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),y=["'"].concat(T),C=["%","/","?",";","#"].concat(y),N=["/","?","#"],R=/^[+a-z0-9A-Z_-]{0,63}$/,A=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,O={javascript:!0,"javascript:":!0},I={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function x(e,t){if(e&&e instanceof E)return e;const r=new E;return r.parse(e,t),r}E.prototype.parse=function(e,t){let r,n,a,i=e;if(i=i.trim(),!t&&1===e.split("#").length){const e=v.exec(i);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let o=b.exec(i);if(o&&(o=o[0],r=o.toLowerCase(),this.protocol=o,i=i.substr(o.length)),(t||o||i.match(/^\/\/[^@\/]+@[^@\/]+/))&&(a="//"===i.substr(0,2),!a||o&&O[o]||(i=i.substr(2),this.slashes=!0)),!O[o]&&(a||o&&!I[o])){let e,t,r=-1;for(let e=0;e<N.length;e++)n=i.indexOf(N[e]),-1!==n&&(-1===r||n<r)&&(r=n);t=-1===r?i.lastIndexOf("@"):i.lastIndexOf("@",r),-1!==t&&(e=i.slice(0,t),i=i.slice(t+1),this.auth=e),r=-1;for(let e=0;e<C.length;e++)n=i.indexOf(C[e]),-1!==n&&(-1===r||n<r)&&(r=n);-1===r&&(r=i.length),":"===i[r-1]&&r--;const a=i.slice(0,r);i=i.slice(r),this.parseHost(a),this.hostname=this.hostname||"";const o="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!o){const e=this.hostname.split(/\./);for(let t=0,r=e.length;t<r;t++){const r=e[t];if(r&&!r.match(R)){let n="";for(let e=0,t=r.length;e<t;e++)r.charCodeAt(e)>127?n+="x":n+=r[e];if(!n.match(R)){const n=e.slice(0,t),a=e.slice(t+1),o=r.match(A);o&&(n.push(o[1]),a.unshift(o[2])),a.length&&(i=a.join(".")+i),this.hostname=n.join(".");break}}}}this.hostname.length>255&&(this.hostname=""),o&&(this.hostname=this.hostname.substr(1,this.hostname.length-2))}const s=i.indexOf("#");-1!==s&&(this.hash=i.substr(s),i=i.slice(0,s));const l=i.indexOf("?");return-1!==l&&(this.search=i.substr(l),i=i.slice(0,l)),i&&(this.pathname=i),I[r]&&this.hostname&&!this.pathname&&(this.pathname=""),this},E.prototype.parseHost=function(e){let t=S.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var w,D=Object.freeze({__proto__:null,decode:m,encode:h,format:f,parse:x}),M=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,k=/[\0-\x1F\x7F-\x9F]/,L=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/,P=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/,F=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,B=Object.freeze({__proto__:null,Any:M,Cc:k,Cf:/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,P:L,S:P,Z:F}),U=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),G=new Uint16Array("Ȁaglq\tɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(e=>e.charCodeAt(0)));const z=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),Y=null!==(w=String.fromCodePoint)&&void 0!==w?w:function(e){let t="";return e>65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|1023&e),t+=String.fromCharCode(e),t};var q;!function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"}(q||(q={}));var H,V,$;function W(e){return e>=q.ZERO&&e<=q.NINE}function j(e){return e>=q.UPPER_A&&e<=q.UPPER_F||e>=q.LOWER_A&&e<=q.LOWER_F}function Q(e){return e===q.EQUALS||function(e){return e>=q.UPPER_A&&e<=q.UPPER_Z||e>=q.LOWER_A&&e<=q.LOWER_Z||W(e)}(e)}!function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"}(H||(H={})),function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"}(V||(V={})),function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"}($||($={}));class K{constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r,this.state=V.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=$.Strict}startEntity(e){this.decodeMode=e,this.state=V.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case V.EntityStart:return e.charCodeAt(t)===q.NUM?(this.state=V.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=V.NamedEntity,this.stateNamedEntity(e,t));case V.NumericStart:return this.stateNumericStart(e,t);case V.NumericDecimal:return this.stateNumericDecimal(e,t);case V.NumericHex:return this.stateNumericHex(e,t);case V.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(32|e.charCodeAt(t))===q.LOWER_X?(this.state=V.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=V.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,r,n){if(t!==r){const a=r-t;this.result=this.result*Math.pow(n,a)+parseInt(e.substr(t,a),n),this.consumed+=a}}stateNumericHex(e,t){const r=t;for(;t<e.length;){const n=e.charCodeAt(t);if(!W(n)&&!j(n))return this.addToNumericResult(e,r,t,16),this.emitNumericEntity(n,3);t+=1}return this.addToNumericResult(e,r,t,16),-1}stateNumericDecimal(e,t){const r=t;for(;t<e.length;){const n=e.charCodeAt(t);if(!W(n))return this.addToNumericResult(e,r,t,10),this.emitNumericEntity(n,2);t+=1}return this.addToNumericResult(e,r,t,10),-1}emitNumericEntity(e,t){var r;if(this.consumed<=t)return null===(r=this.errors)||void 0===r||r.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===q.SEMI)this.consumed+=1;else if(this.decodeMode===$.Strict)return 0;return this.emitCodePoint(function(e){var t;return e>=55296&&e<=57343||e>1114111?65533:null!==(t=z.get(e))&&void 0!==t?t:e}(this.result),this.consumed),this.errors&&(e!==q.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(e,t){const{decodeTree:r}=this;let n=r[this.treeIndex],a=(n&H.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const i=e.charCodeAt(t);if(this.treeIndex=Z(r,n,this.treeIndex+Math.max(1,a),i),this.treeIndex<0)return 0===this.result||this.decodeMode===$.Attribute&&(0===a||Q(i))?0:this.emitNotTerminatedNamedEntity();if(n=r[this.treeIndex],a=(n&H.VALUE_LENGTH)>>14,0!==a){if(i===q.SEMI)return this.emitNamedEntityData(this.treeIndex,a,this.consumed+this.excess);this.decodeMode!==$.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:r}=this,n=(r[t]&H.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,n,this.consumed),null===(e=this.errors)||void 0===e||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){const{decodeTree:n}=this;return this.emitCodePoint(1===t?n[e]&~H.VALUE_LENGTH:n[e+1],r),3===t&&this.emitCodePoint(n[e+2],r),r}end(){var e;switch(this.state){case V.NamedEntity:return 0===this.result||this.decodeMode===$.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case V.NumericDecimal:return this.emitNumericEntity(0,2);case V.NumericHex:return this.emitNumericEntity(0,3);case V.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case V.EntityStart:return 0}}}function X(e){let t="";const r=new K(e,e=>t+=Y(e));return function(e,n){let a=0,i=0;for(;(i=e.indexOf("&",i))>=0;){t+=e.slice(a,i),r.startEntity(n);const o=r.write(e,i+1);if(o<0){a=i+r.end();break}a=i+o,i=0===o?a+1:a}const o=t+e.slice(a);return t="",o}}function Z(e,t,r,n){const a=(t&H.BRANCH_LENGTH)>>7,i=t&H.JUMP_TABLE;if(0===a)return 0!==i&&n===i?r:-1;if(i){const t=n-i;return t<0||t>=a?-1:e[r+t]-1}let o=r,s=o+a-1;for(;o<=s;){const t=o+s>>>1,r=e[t];if(r<n)o=t+1;else{if(!(r>n))return e[t+a];s=t-1}}return-1}const J=X(U);function ee(e,t=$.Legacy){return J(e,t)}function te(e){return"[object String]"===function(e){return Object.prototype.toString.call(e)}(e)}X(G);const re=Object.prototype.hasOwnProperty;function ne(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){if(t){if("object"!=typeof t)throw new TypeError(t+"must be object");Object.keys(t).forEach(function(r){e[r]=t[r]})}}),e}function ae(e,t,r){return[].concat(e.slice(0,t),r,e.slice(t+1))}function ie(e){return!(e>=55296&&e<=57343)&&(!(e>=64976&&e<=65007)&&(!!(65535&~e&&65534!=(65535&e))&&(!(e>=0&&e<=8)&&(11!==e&&(!(e>=14&&e<=31)&&(!(e>=127&&e<=159)&&!(e>1114111)))))))}function oe(e){if(e>65535){const t=55296+((e-=65536)>>10),r=56320+(1023&e);return String.fromCharCode(t,r)}return String.fromCharCode(e)}const se=/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,le=new RegExp(se.source+"|"+/&([a-z#][a-z0-9]{1,31});/gi.source,"gi"),ce=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;function de(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(le,function(e,t,r){return t||function(e,t){if(35===t.charCodeAt(0)&&ce.test(t)){const r="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return ie(r)?oe(r):e}const r=ee(e);return r!==e?r:e}(e,r)})}const ue=/[&<>"]/,pe=/[&<>"]/g,_e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function me(e){return _e[e]}function ge(e){return ue.test(e)?e.replace(pe,me):e}const he=/[.?*+^$[\]\\(){}|-]/g;function fe(e){switch(e){case 9:case 32:return!0}return!1}function Ee(e){if(e>=8192&&e<=8202)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:return!0}return!1}function be(e){return L.test(e)||P.test(e)}function Se(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return!0;default:return!1}}function ve(e){return e=e.trim().replace(/\s+/g," "),"Ṿ"==="ẞ".toLowerCase()&&(e=e.replace(/ẞ/g,"ß")),e.toLowerCase().toUpperCase()}const Te={mdurl:D,ucmicro:B};var ye=Object.freeze({__proto__:null,arrayReplaceAt:ae,assign:ne,escapeHtml:ge,escapeRE:function(e){return e.replace(he,"\\$&")},fromCodePoint:oe,has:function(e,t){return re.call(e,t)},isMdAsciiPunct:Se,isPunctChar:be,isSpace:fe,isString:te,isValidEntityCode:ie,isWhiteSpace:Ee,lib:Te,normalizeReference:ve,unescapeAll:de,unescapeMd:function(e){return e.indexOf("\\")<0?e:e.replace(se,"$1")}});var Ce=Object.freeze({__proto__:null,parseLinkDestination:function(e,t,r){let n,a=t;const i={ok:!1,pos:0,str:""};if(60===e.charCodeAt(a)){for(a++;a<r;){if(n=e.charCodeAt(a),10===n)return i;if(60===n)return i;if(62===n)return i.pos=a+1,i.str=de(e.slice(t+1,a)),i.ok=!0,i;92===n&&a+1<r?a+=2:a++}return i}let o=0;for(;a<r&&(n=e.charCodeAt(a),32!==n)&&!(n<32||127===n);)if(92===n&&a+1<r){if(32===e.charCodeAt(a+1))break;a+=2}else{if(40===n&&(o++,o>32))return i;if(41===n){if(0===o)break;o--}a++}return t===a||0!==o||(i.str=de(e.slice(t,a)),i.pos=a,i.ok=!0),i},parseLinkLabel:function(e,t,r){let n,a,i,o;const s=e.posMax,l=e.pos;for(e.pos=t+1,n=1;e.pos<s;){if(i=e.src.charCodeAt(e.pos),93===i&&(n--,0===n)){a=!0;break}if(o=e.pos,e.md.inline.skipToken(e),91===i)if(o===e.pos-1)n++;else if(r)return e.pos=l,-1}let c=-1;return a&&(c=e.pos),e.pos=l,c},parseLinkTitle:function(e,t,r,n){let a,i=t;const o={ok:!1,can_continue:!1,pos:0,str:"",marker:0};if(n)o.str=n.str,o.marker=n.marker;else{if(i>=r)return o;let n=e.charCodeAt(i);if(34!==n&&39!==n&&40!==n)return o;t++,i++,40===n&&(n=41),o.marker=n}for(;i<r;){if(a=e.charCodeAt(i),a===o.marker)return o.pos=i+1,o.str+=de(e.slice(t,i)),o.ok=!0,o;if(40===a&&41===o.marker)return o;92===a&&i+1<r&&i++,i++}return o.can_continue=!0,o.str+=de(e.slice(t,i)),o}});const Ne={};function Re(){this.rules=ne({},Ne)}function Ae(){this.__rules__=[],this.__cache__=null}function Oe(e,t,r){this.type=e,this.tag=t,this.attrs=null,this.map=null,this.nesting=r,this.level=0,this.children=null,this.content="",this.markup="",this.info="",this.meta=null,this.block=!1,this.hidden=!1}function Ie(e,t,r){this.src=e,this.env=r,this.tokens=[],this.inlineMode=!1,this.md=t}Ne.code_inline=function(e,t,r,n,a){const i=e[t];return"<code"+a.renderAttrs(i)+">"+ge(i.content)+"</code>"},Ne.code_block=function(e,t,r,n,a){const i=e[t];return"<pre"+a.renderAttrs(i)+"><code>"+ge(e[t].content)+"</code></pre>\n"},Ne.fence=function(e,t,r,n,a){const i=e[t],o=i.info?de(i.info).trim():"";let s,l="",c="";if(o){const e=o.split(/(\s+)/g);l=e[0],c=e.slice(2).join("")}if(s=r.highlight&&r.highlight(i.content,l,c)||ge(i.content),0===s.indexOf("<pre"))return s+"\n";if(o){const e=i.attrIndex("class"),t=i.attrs?i.attrs.slice():[];e<0?t.push(["class",r.langPrefix+l]):(t[e]=t[e].slice(),t[e][1]+=" "+r.langPrefix+l);const n={attrs:t};return`<pre><code${a.renderAttrs(n)}>${s}</code></pre>\n`}return`<pre><code${a.renderAttrs(i)}>${s}</code></pre>\n`},Ne.image=function(e,t,r,n,a){const i=e[t];return i.attrs[i.attrIndex("alt")][1]=a.renderInlineAsText(i.children,r,n),a.renderToken(e,t,r)},Ne.hardbreak=function(e,t,r){return r.xhtmlOut?"<br />\n":"<br>\n"},Ne.softbreak=function(e,t,r){return r.breaks?r.xhtmlOut?"<br />\n":"<br>\n":"\n"},Ne.text=function(e,t){return ge(e[t].content)},Ne.html_block=function(e,t){return e[t].content},Ne.html_inline=function(e,t){return e[t].content},Re.prototype.renderAttrs=function(e){let t,r,n;if(!e.attrs)return"";for(n="",t=0,r=e.attrs.length;t<r;t++)n+=" "+ge(e.attrs[t][0])+'="'+ge(e.attrs[t][1])+'"';return n},Re.prototype.renderToken=function(e,t,r){const n=e[t];let a="";if(n.hidden)return"";n.block&&-1!==n.nesting&&t&&e[t-1].hidden&&(a+="\n"),a+=(-1===n.nesting?"</":"<")+n.tag,a+=this.renderAttrs(n),0===n.nesting&&r.xhtmlOut&&(a+=" /");let i=!1;if(n.block&&(i=!0,1===n.nesting&&t+1<e.length)){const r=e[t+1];("inline"===r.type||r.hidden||-1===r.nesting&&r.tag===n.tag)&&(i=!1)}return a+=i?">\n":">",a},Re.prototype.renderInline=function(e,t,r){let n="";const a=this.rules;for(let i=0,o=e.length;i<o;i++){const o=e[i].type;void 0!==a[o]?n+=a[o](e,i,t,r,this):n+=this.renderToken(e,i,t)}return n},Re.prototype.renderInlineAsText=function(e,t,r){let n="";for(let a=0,i=e.length;a<i;a++)switch(e[a].type){case"text":case"html_inline":case"html_block":n+=e[a].content;break;case"image":n+=this.renderInlineAsText(e[a].children,t,r);break;case"softbreak":case"hardbreak":n+="\n"}return n},Re.prototype.render=function(e,t,r){let n="";const a=this.rules;for(let i=0,o=e.length;i<o;i++){const o=e[i].type;"inline"===o?n+=this.renderInline(e[i].children,t,r):void 0!==a[o]?n+=a[o](e,i,t,r,this):n+=this.renderToken(e,i,t,r)}return n},Ae.prototype.__find__=function(e){for(let t=0;t<this.__rules__.length;t++)if(this.__rules__[t].name===e)return t;return-1},Ae.prototype.__compile__=function(){const e=this,t=[""];e.__rules__.forEach(function(e){e.enabled&&e.alt.forEach(function(e){t.indexOf(e)<0&&t.push(e)})}),e.__cache__={},t.forEach(function(t){e.__cache__[t]=[],e.__rules__.forEach(function(r){r.enabled&&(t&&r.alt.indexOf(t)<0||e.__cache__[t].push(r.fn))})})},Ae.prototype.at=function(e,t,r){const n=this.__find__(e),a=r||{};if(-1===n)throw new Error("Parser rule not found: "+e);this.__rules__[n].fn=t,this.__rules__[n].alt=a.alt||[],this.__cache__=null},Ae.prototype.before=function(e,t,r,n){const a=this.__find__(e),i=n||{};if(-1===a)throw new Error("Parser rule not found: "+e);this.__rules__.splice(a,0,{name:t,enabled:!0,fn:r,alt:i.alt||[]}),this.__cache__=null},Ae.prototype.after=function(e,t,r,n){const a=this.__find__(e),i=n||{};if(-1===a)throw new Error("Parser rule not found: "+e);this.__rules__.splice(a+1,0,{name:t,enabled:!0,fn:r,alt:i.alt||[]}),this.__cache__=null},Ae.prototype.push=function(e,t,r){const n=r||{};this.__rules__.push({name:e,enabled:!0,fn:t,alt:n.alt||[]}),this.__cache__=null},Ae.prototype.enable=function(e,t){Array.isArray(e)||(e=[e]);const r=[];return e.forEach(function(e){const n=this.__find__(e);if(n<0){if(t)return;throw new Error("Rules manager: invalid rule name "+e)}this.__rules__[n].enabled=!0,r.push(e)},this),this.__cache__=null,r},Ae.prototype.enableOnly=function(e,t){Array.isArray(e)||(e=[e]),this.__rules__.forEach(function(e){e.enabled=!1}),this.enable(e,t)},Ae.prototype.disable=function(e,t){Array.isArray(e)||(e=[e]);const r=[];return e.forEach(function(e){const n=this.__find__(e);if(n<0){if(t)return;throw new Error("Rules manager: invalid rule name "+e)}this.__rules__[n].enabled=!1,r.push(e)},this),this.__cache__=null,r},Ae.prototype.getRules=function(e){return null===this.__cache__&&this.__compile__(),this.__cache__[e]||[]},Oe.prototype.attrIndex=function(e){if(!this.attrs)return-1;const t=this.attrs;for(let r=0,n=t.length;r<n;r++)if(t[r][0]===e)return r;return-1},Oe.prototype.attrPush=function(e){this.attrs?this.attrs.push(e):this.attrs=[e]},Oe.prototype.attrSet=function(e,t){const r=this.attrIndex(e),n=[e,t];r<0?this.attrPush(n):this.attrs[r]=n},Oe.prototype.attrGet=function(e){const t=this.attrIndex(e);let r=null;return t>=0&&(r=this.attrs[t][1]),r},Oe.prototype.attrJoin=function(e,t){const r=this.attrIndex(e);r<0?this.attrPush([e,t]):this.attrs[r][1]=this.attrs[r][1]+" "+t},Ie.prototype.Token=Oe;const xe=/\r\n?|\n/g,we=/\0/g;function De(e){return/^<a[>\s]/i.test(e)}function Me(e){return/^<\/a\s*>/i.test(e)}const ke=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,Le=/\((c|tm|r)\)/i,Pe=/\((c|tm|r)\)/gi,Fe={c:"©",r:"®",tm:"™"};function Be(e,t){return Fe[t.toLowerCase()]}function Ue(e){let t=0;for(let r=e.length-1;r>=0;r--){const n=e[r];"text"!==n.type||t||(n.content=n.content.replace(Pe,Be)),"link_open"===n.type&&"auto"===n.info&&t--,"link_close"===n.type&&"auto"===n.info&&t++}}function Ge(e){let t=0;for(let r=e.length-1;r>=0;r--){const n=e[r];"text"!==n.type||t||ke.test(n.content)&&(n.content=n.content.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/gm,"$1—").replace(/(^|\s)--(?=\s|$)/gm,"$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/gm,"$1–")),"link_open"===n.type&&"auto"===n.info&&t--,"link_close"===n.type&&"auto"===n.info&&t++}}const ze=/['"]/,Ye=/['"]/g;function qe(e,t,r){return e.slice(0,t)+r+e.slice(t+1)}function He(e,t){let r;const n=[];for(let a=0;a<e.length;a++){const i=e[a],o=e[a].level;for(r=n.length-1;r>=0&&!(n[r].level<=o);r--);if(n.length=r+1,"text"!==i.type)continue;let s=i.content,l=0,c=s.length;e:for(;l<c;){Ye.lastIndex=l;const d=Ye.exec(s);if(!d)break;let u=!0,p=!0;l=d.index+1;const _="'"===d[0];let m=32;if(d.index-1>=0)m=s.charCodeAt(d.index-1);else for(r=a-1;r>=0&&("softbreak"!==e[r].type&&"hardbreak"!==e[r].type);r--)if(e[r].content){m=e[r].content.charCodeAt(e[r].content.length-1);break}let g=32;if(l<c)g=s.charCodeAt(l);else for(r=a+1;r<e.length&&("softbreak"!==e[r].type&&"hardbreak"!==e[r].type);r++)if(e[r].content){g=e[r].content.charCodeAt(0);break}const h=Se(m)||be(String.fromCharCode(m)),f=Se(g)||be(String.fromCharCode(g)),E=Ee(m),b=Ee(g);if(b?u=!1:f&&(E||h||(u=!1)),E?p=!1:h&&(b||f||(p=!1)),34===g&&'"'===d[0]&&m>=48&&m<=57&&(p=u=!1),u&&p&&(u=h,p=f),u||p){if(p)for(r=n.length-1;r>=0;r--){let u=n[r];if(n[r].level<o)break;if(u.single===_&&n[r].level===o){let o,p;u=n[r],_?(o=t.md.options.quotes[2],p=t.md.options.quotes[3]):(o=t.md.options.quotes[0],p=t.md.options.quotes[1]),i.content=qe(i.content,d.index,p),e[u.token].content=qe(e[u.token].content,u.pos,o),l+=p.length-1,u.token===a&&(l+=o.length-1),s=i.content,c=s.length,n.length=r;continue e}}u?n.push({token:a,pos:d.index,single:_,level:o}):p&&_&&(i.content=qe(i.content,d.index,"’"))}else _&&(i.content=qe(i.content,d.index,"’"))}}}const Ve=[["normalize",function(e){let t;t=e.src.replace(xe,"\n"),t=t.replace(we,"�"),e.src=t}],["block",function(e){let t;e.inlineMode?(t=new e.Token("inline","",0),t.content=e.src,t.map=[0,1],t.children=[],e.tokens.push(t)):e.md.block.parse(e.src,e.md,e.env,e.tokens)}],["inline",function(e){const t=e.tokens;for(let r=0,n=t.length;r<n;r++){const n=t[r];"inline"===n.type&&e.md.inline.parse(n.content,e.md,e.env,n.children)}}],["linkify",function(e){const t=e.tokens;if(e.md.options.linkify)for(let r=0,n=t.length;r<n;r++){if("inline"!==t[r].type||!e.md.linkify.pretest(t[r].content))continue;let n=t[r].children,a=0;for(let i=n.length-1;i>=0;i--){const o=n[i];if("link_close"!==o.type){if("html_inline"===o.type&&(De(o.content)&&a>0&&a--,Me(o.content)&&a++),!(a>0)&&"text"===o.type&&e.md.linkify.test(o.content)){const a=o.content;let s=e.md.linkify.match(a);const l=[];let c=o.level,d=0;s.length>0&&0===s[0].index&&i>0&&"text_special"===n[i-1].type&&(s=s.slice(1));for(let t=0;t<s.length;t++){const r=s[t].url,n=e.md.normalizeLink(r);if(!e.md.validateLink(n))continue;let i=s[t].text;i=s[t].schema?"mailto:"!==s[t].schema||/^mailto:/i.test(i)?e.md.normalizeLinkText(i):e.md.normalizeLinkText("mailto:"+i).replace(/^mailto:/,""):e.md.normalizeLinkText("http://"+i).replace(/^http:\/\//,"");const o=s[t].index;if(o>d){const t=new e.Token("text","",0);t.content=a.slice(d,o),t.level=c,l.push(t)}const u=new e.Token("link_open","a",1);u.attrs=[["href",n]],u.level=c++,u.markup="linkify",u.info="auto",l.push(u);const p=new e.Token("text","",0);p.content=i,p.level=c,l.push(p);const _=new e.Token("link_close","a",-1);_.level=--c,_.markup="linkify",_.info="auto",l.push(_),d=s[t].lastIndex}if(d<a.length){const t=new e.Token("text","",0);t.content=a.slice(d),t.level=c,l.push(t)}t[r].children=n=ae(n,i,l)}}else for(i--;n[i].level!==o.level&&"link_open"!==n[i].type;)i--}}}],["replacements",function(e){let t;if(e.md.options.typographer)for(t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&(Le.test(e.tokens[t].content)&&Ue(e.tokens[t].children),ke.test(e.tokens[t].content)&&Ge(e.tokens[t].children))}],["smartquotes",function(e){if(e.md.options.typographer)for(let t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&ze.test(e.tokens[t].content)&&He(e.tokens[t].children,e)}],["text_join",function(e){let t,r;const n=e.tokens,a=n.length;for(let e=0;e<a;e++){if("inline"!==n[e].type)continue;const a=n[e].children,i=a.length;for(t=0;t<i;t++)"text_special"===a[t].type&&(a[t].type="text");for(t=r=0;t<i;t++)"text"===a[t].type&&t+1<i&&"text"===a[t+1].type?a[t+1].content=a[t].content+a[t+1].content:(t!==r&&(a[r]=a[t]),r++);t!==r&&(a.length=r)}}]];function $e(){this.ruler=new Ae;for(let e=0;e<Ve.length;e++)this.ruler.push(Ve[e][0],Ve[e][1])}function We(e,t,r,n){this.src=e,this.md=t,this.env=r,this.tokens=n,this.bMarks=[],this.eMarks=[],this.tShift=[],this.sCount=[],this.bsCount=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.ddIndent=-1,this.listIndent=-1,this.parentType="root",this.level=0;const a=this.src;for(let e=0,t=0,r=0,n=0,i=a.length,o=!1;t<i;t++){const s=a.charCodeAt(t);if(!o){if(fe(s)){r++,9===s?n+=4-n%4:n++;continue}o=!0}10!==s&&t!==i-1||(10!==s&&t++,this.bMarks.push(e),this.eMarks.push(t),this.tShift.push(r),this.sCount.push(n),this.bsCount.push(0),o=!1,r=0,n=0,e=t+1)}this.bMarks.push(a.length),this.eMarks.push(a.length),this.tShift.push(0),this.sCount.push(0),this.bsCount.push(0),this.lineMax=this.bMarks.length-1}$e.prototype.process=function(e){const t=this.ruler.getRules("");for(let r=0,n=t.length;r<n;r++)t[r](e)},$e.prototype.State=Ie,We.prototype.push=function(e,t,r){const n=new Oe(e,t,r);return n.block=!0,r<0&&this.level--,n.level=this.level,r>0&&this.level++,this.tokens.push(n),n},We.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},We.prototype.skipEmptyLines=function(e){for(let t=this.lineMax;e<t&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e},We.prototype.skipSpaces=function(e){for(let t=this.src.length;e<t;e++){if(!fe(this.src.charCodeAt(e)))break}return e},We.prototype.skipSpacesBack=function(e,t){if(e<=t)return e;for(;e>t;)if(!fe(this.src.charCodeAt(--e)))return e+1;return e},We.prototype.skipChars=function(e,t){for(let r=this.src.length;e<r&&this.src.charCodeAt(e)===t;e++);return e},We.prototype.skipCharsBack=function(e,t,r){if(e<=r)return e;for(;e>r;)if(t!==this.src.charCodeAt(--e))return e+1;return e},We.prototype.getLines=function(e,t,r,n){if(e>=t)return"";const a=new Array(t-e);for(let i=0,o=e;o<t;o++,i++){let e=0;const s=this.bMarks[o];let l,c=s;for(l=o+1<t||n?this.eMarks[o]+1:this.eMarks[o];c<l&&e<r;){const t=this.src.charCodeAt(c);if(fe(t))9===t?e+=4-(e+this.bsCount[o])%4:e++;else{if(!(c-s<this.tShift[o]))break;e++}c++}a[i]=e>r?new Array(e-r+1).join(" ")+this.src.slice(c,l):this.src.slice(c,l)}return a.join("")},We.prototype.Token=Oe;function je(e,t){const r=e.bMarks[t]+e.tShift[t],n=e.eMarks[t];return e.src.slice(r,n)}function Qe(e){const t=[],r=e.length;let n=0,a=e.charCodeAt(n),i=!1,o=0,s="";for(;n<r;)124===a&&(i?(s+=e.substring(o,n-1),o=n):(t.push(s+e.substring(o,n)),s="",o=n+1)),i=92===a,n++,a=e.charCodeAt(n);return t.push(s+e.substring(o)),t}function Ke(e,t){const r=e.eMarks[t];let n=e.bMarks[t]+e.tShift[t];const a=e.src.charCodeAt(n++);if(42!==a&&45!==a&&43!==a)return-1;if(n<r){if(!fe(e.src.charCodeAt(n)))return-1}return n}function Xe(e,t){const r=e.bMarks[t]+e.tShift[t],n=e.eMarks[t];let a=r;if(a+1>=n)return-1;let i=e.src.charCodeAt(a++);if(i<48||i>57)return-1;for(;;){if(a>=n)return-1;if(i=e.src.charCodeAt(a++),!(i>=48&&i<=57)){if(41===i||46===i)break;return-1}if(a-r>=10)return-1}return a<n&&(i=e.src.charCodeAt(a),!fe(i))?-1:a}const Ze="<[A-Za-z][A-Za-z0-9\\-]*(?:\\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\\s*=\\s*(?:[^\"'=<>`\\x00-\\x20]+|'[^']*'|\"[^\"]*\"))?)*\\s*\\/?>",Je="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",et=new RegExp("^(?:"+Ze+"|"+Je+"|\x3c!---?>|\x3c!--(?:[^-]|-[^-]|--[^>])*--\x3e|<[?][\\s\\S]*?[?]>|<![A-Za-z][^>]*>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>)"),tt=new RegExp("^(?:"+Ze+"|"+Je+")"),rt=[[/^<(script|pre|style|textarea)(?=(\s|>|$))/i,/<\/(script|pre|style|textarea)>/i,!0],[/^<!--/,/-->/,!0],[/^<\?/,/\?>/,!0],[/^<![A-Z]/,/>/,!0],[/^<!\[CDATA\[/,/\]\]>/,!0],[new RegExp("^</?("+["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"].join("|")+")(?=(\\s|/?>|$))","i"),/^$/,!0],[new RegExp(tt.source+"\\s*$"),/^$/,!1]];const nt=[["table",function(e,t,r,n){if(t+2>r)return!1;let a=t+1;if(e.sCount[a]<e.blkIndent)return!1;if(e.sCount[a]-e.blkIndent>=4)return!1;let i=e.bMarks[a]+e.tShift[a];if(i>=e.eMarks[a])return!1;const o=e.src.charCodeAt(i++);if(124!==o&&45!==o&&58!==o)return!1;if(i>=e.eMarks[a])return!1;const s=e.src.charCodeAt(i++);if(124!==s&&45!==s&&58!==s&&!fe(s))return!1;if(45===o&&fe(s))return!1;for(;i<e.eMarks[a];){const t=e.src.charCodeAt(i);if(124!==t&&45!==t&&58!==t&&!fe(t))return!1;i++}let l=je(e,t+1),c=l.split("|");const d=[];for(let e=0;e<c.length;e++){const t=c[e].trim();if(!t){if(0===e||e===c.length-1)continue;return!1}if(!/^:?-+:?$/.test(t))return!1;58===t.charCodeAt(t.length-1)?d.push(58===t.charCodeAt(0)?"center":"right"):58===t.charCodeAt(0)?d.push("left"):d.push("")}if(l=je(e,t).trim(),-1===l.indexOf("|"))return!1;if(e.sCount[t]-e.blkIndent>=4)return!1;c=Qe(l),c.length&&""===c[0]&&c.shift(),c.length&&""===c[c.length-1]&&c.pop();const u=c.length;if(0===u||u!==d.length)return!1;if(n)return!0;const p=e.parentType;e.parentType="table";const _=e.md.block.ruler.getRules("blockquote"),m=[t,0];e.push("table_open","table",1).map=m,e.push("thead_open","thead",1).map=[t,t+1],e.push("tr_open","tr",1).map=[t,t+1];for(let t=0;t<c.length;t++){const r=e.push("th_open","th",1);d[t]&&(r.attrs=[["style","text-align:"+d[t]]]);const n=e.push("inline","",0);n.content=c[t].trim(),n.children=[],e.push("th_close","th",-1)}let g;e.push("tr_close","tr",-1),e.push("thead_close","thead",-1);let h=0;for(a=t+2;a<r&&!(e.sCount[a]<e.blkIndent);a++){let n=!1;for(let t=0,i=_.length;t<i;t++)if(_[t](e,a,r,!0)){n=!0;break}if(n)break;if(l=je(e,a).trim(),!l)break;if(e.sCount[a]-e.blkIndent>=4)break;if(c=Qe(l),c.length&&""===c[0]&&c.shift(),c.length&&""===c[c.length-1]&&c.pop(),h+=u-c.length,h>65536)break;if(a===t+2){e.push("tbody_open","tbody",1).map=g=[t+2,0]}e.push("tr_open","tr",1).map=[a,a+1];for(let t=0;t<u;t++){const r=e.push("td_open","td",1);d[t]&&(r.attrs=[["style","text-align:"+d[t]]]);const n=e.push("inline","",0);n.content=c[t]?c[t].trim():"",n.children=[],e.push("td_close","td",-1)}e.push("tr_close","tr",-1)}return g&&(e.push("tbody_close","tbody",-1),g[1]=a),e.push("table_close","table",-1),m[1]=a,e.parentType=p,e.line=a,!0},["paragraph","reference"]],["code",function(e,t,r){if(e.sCount[t]-e.blkIndent<4)return!1;let n=t+1,a=n;for(;n<r;)if(e.isEmpty(n))n++;else{if(!(e.sCount[n]-e.blkIndent>=4))break;n++,a=n}e.line=a;const i=e.push("code_block","code",0);return i.content=e.getLines(t,a,4+e.blkIndent,!1)+"\n",i.map=[t,e.line],!0}],["fence",function(e,t,r,n){let a=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;if(a+3>i)return!1;const o=e.src.charCodeAt(a);if(126!==o&&96!==o)return!1;let s=a;a=e.skipChars(a,o);let l=a-s;if(l<3)return!1;const c=e.src.slice(s,a),d=e.src.slice(a,i);if(96===o&&d.indexOf(String.fromCharCode(o))>=0)return!1;if(n)return!0;let u=t,p=!1;for(;(u++,!(u>=r))&&(a=s=e.bMarks[u]+e.tShift[u],i=e.eMarks[u],!(a<i&&e.sCount[u]<e.blkIndent));)if(e.src.charCodeAt(a)===o&&!(e.sCount[u]-e.blkIndent>=4||(a=e.skipChars(a,o),a-s<l||(a=e.skipSpaces(a),a<i)))){p=!0;break}l=e.sCount[t],e.line=u+(p?1:0);const _=e.push("fence","code",0);return _.info=d,_.content=e.getLines(t+1,u,l,!0),_.markup=c,_.map=[t,e.line],!0},["paragraph","reference","blockquote","list"]],["blockquote",function(e,t,r,n){let a=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];const o=e.lineMax;if(e.sCount[t]-e.blkIndent>=4)return!1;if(62!==e.src.charCodeAt(a))return!1;if(n)return!0;const s=[],l=[],c=[],d=[],u=e.md.block.ruler.getRules("blockquote"),p=e.parentType;e.parentType="blockquote";let _,m=!1;for(_=t;_<r;_++){const t=e.sCount[_]<e.blkIndent;if(a=e.bMarks[_]+e.tShift[_],i=e.eMarks[_],a>=i)break;if(62===e.src.charCodeAt(a++)&&!t){let t,r,n=e.sCount[_]+1;32===e.src.charCodeAt(a)?(a++,n++,r=!1,t=!0):9===e.src.charCodeAt(a)?(t=!0,(e.bsCount[_]+n)%4==3?(a++,n++,r=!1):r=!0):t=!1;let o=n;for(s.push(e.bMarks[_]),e.bMarks[_]=a;a<i;){const t=e.src.charCodeAt(a);if(!fe(t))break;9===t?o+=4-(o+e.bsCount[_]+(r?1:0))%4:o++,a++}m=a>=i,l.push(e.bsCount[_]),e.bsCount[_]=e.sCount[_]+1+(t?1:0),c.push(e.sCount[_]),e.sCount[_]=o-n,d.push(e.tShift[_]),e.tShift[_]=a-e.bMarks[_];continue}if(m)break;let n=!1;for(let t=0,a=u.length;t<a;t++)if(u[t](e,_,r,!0)){n=!0;break}if(n){e.lineMax=_,0!==e.blkIndent&&(s.push(e.bMarks[_]),l.push(e.bsCount[_]),d.push(e.tShift[_]),c.push(e.sCount[_]),e.sCount[_]-=e.blkIndent);break}s.push(e.bMarks[_]),l.push(e.bsCount[_]),d.push(e.tShift[_]),c.push(e.sCount[_]),e.sCount[_]=-1}const g=e.blkIndent;e.blkIndent=0;const h=e.push("blockquote_open","blockquote",1);h.markup=">";const f=[t,0];h.map=f,e.md.block.tokenize(e,t,_),e.push("blockquote_close","blockquote",-1).markup=">",e.lineMax=o,e.parentType=p,f[1]=e.line;for(let r=0;r<d.length;r++)e.bMarks[r+t]=s[r],e.tShift[r+t]=d[r],e.sCount[r+t]=c[r],e.bsCount[r+t]=l[r];return e.blkIndent=g,!0},["paragraph","reference","blockquote","list"]],["hr",function(e,t,r,n){const a=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;let i=e.bMarks[t]+e.tShift[t];const o=e.src.charCodeAt(i++);if(42!==o&&45!==o&&95!==o)return!1;let s=1;for(;i<a;){const t=e.src.charCodeAt(i++);if(t!==o&&!fe(t))return!1;t===o&&s++}if(s<3)return!1;if(n)return!0;e.line=t+1;const l=e.push("hr","hr",0);return l.map=[t,e.line],l.markup=Array(s+1).join(String.fromCharCode(o)),!0},["paragraph","reference","blockquote","list"]],["list",function(e,t,r,n){let a,i,o,s,l=t,c=!0;if(e.sCount[l]-e.blkIndent>=4)return!1;if(e.listIndent>=0&&e.sCount[l]-e.listIndent>=4&&e.sCount[l]<e.blkIndent)return!1;let d,u,p,_=!1;if(n&&"paragraph"===e.parentType&&e.sCount[l]>=e.blkIndent&&(_=!0),(p=Xe(e,l))>=0){if(d=!0,o=e.bMarks[l]+e.tShift[l],u=Number(e.src.slice(o,p-1)),_&&1!==u)return!1}else{if(!((p=Ke(e,l))>=0))return!1;d=!1}if(_&&e.skipSpaces(p)>=e.eMarks[l])return!1;if(n)return!0;const m=e.src.charCodeAt(p-1),g=e.tokens.length;d?(s=e.push("ordered_list_open","ol",1),1!==u&&(s.attrs=[["start",u]])):s=e.push("bullet_list_open","ul",1);const h=[l,0];s.map=h,s.markup=String.fromCharCode(m);let f=!1;const E=e.md.block.ruler.getRules("list"),b=e.parentType;for(e.parentType="list";l<r;){i=p,a=e.eMarks[l];const t=e.sCount[l]+p-(e.bMarks[l]+e.tShift[l]);let n=t;for(;i<a;){const t=e.src.charCodeAt(i);if(9===t)n+=4-(n+e.bsCount[l])%4;else{if(32!==t)break;n++}i++}const u=i;let _;_=u>=a?1:n-t,_>4&&(_=1);const g=t+_;s=e.push("list_item_open","li",1),s.markup=String.fromCharCode(m);const h=[l,0];s.map=h,d&&(s.info=e.src.slice(o,p-1));const b=e.tight,S=e.tShift[l],v=e.sCount[l],T=e.listIndent;if(e.listIndent=e.blkIndent,e.blkIndent=g,e.tight=!0,e.tShift[l]=u-e.bMarks[l],e.sCount[l]=n,u>=a&&e.isEmpty(l+1)?e.line=Math.min(e.line+2,r):e.md.block.tokenize(e,l,r,!0),e.tight&&!f||(c=!1),f=e.line-l>1&&e.isEmpty(e.line-1),e.blkIndent=e.listIndent,e.listIndent=T,e.tShift[l]=S,e.sCount[l]=v,e.tight=b,s=e.push("list_item_close","li",-1),s.markup=String.fromCharCode(m),l=e.line,h[1]=l,l>=r)break;if(e.sCount[l]<e.blkIndent)break;if(e.sCount[l]-e.blkIndent>=4)break;let y=!1;for(let t=0,n=E.length;t<n;t++)if(E[t](e,l,r,!0)){y=!0;break}if(y)break;if(d){if(p=Xe(e,l),p<0)break;o=e.bMarks[l]+e.tShift[l]}else if(p=Ke(e,l),p<0)break;if(m!==e.src.charCodeAt(p-1))break}return s=d?e.push("ordered_list_close","ol",-1):e.push("bullet_list_close","ul",-1),s.markup=String.fromCharCode(m),h[1]=l,e.line=l,e.parentType=b,c&&function(e,t){const r=e.level+2;for(let n=t+2,a=e.tokens.length-2;n<a;n++)e.tokens[n].level===r&&"paragraph_open"===e.tokens[n].type&&(e.tokens[n+2].hidden=!0,e.tokens[n].hidden=!0,n+=2)}(e,g),!0},["paragraph","reference","blockquote"]],["reference",function(e,t,r,n){let a=e.bMarks[t]+e.tShift[t],i=e.eMarks[t],o=t+1;if(e.sCount[t]-e.blkIndent>=4)return!1;if(91!==e.src.charCodeAt(a))return!1;function s(t){const r=e.lineMax;if(t>=r||e.isEmpty(t))return null;let n=!1;if(e.sCount[t]-e.blkIndent>3&&(n=!0),e.sCount[t]<0&&(n=!0),!n){const n=e.md.block.ruler.getRules("reference"),a=e.parentType;e.parentType="reference";let i=!1;for(let a=0,o=n.length;a<o;a++)if(n[a](e,t,r,!0)){i=!0;break}if(e.parentType=a,i)return null}const a=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];return e.src.slice(a,i+1)}let l=e.src.slice(a,i+1);i=l.length;let c=-1;for(a=1;a<i;a++){const e=l.charCodeAt(a);if(91===e)return!1;if(93===e){c=a;break}if(10===e){const e=s(o);null!==e&&(l+=e,i=l.length,o++)}else if(92===e&&(a++,a<i&&10===l.charCodeAt(a))){const e=s(o);null!==e&&(l+=e,i=l.length,o++)}}if(c<0||58!==l.charCodeAt(c+1))return!1;for(a=c+2;a<i;a++){const e=l.charCodeAt(a);if(10===e){const e=s(o);null!==e&&(l+=e,i=l.length,o++)}else if(!fe(e))break}const d=e.md.helpers.parseLinkDestination(l,a,i);if(!d.ok)return!1;const u=e.md.normalizeLink(d.str);if(!e.md.validateLink(u))return!1;a=d.pos;const p=a,_=o,m=a;for(;a<i;a++){const e=l.charCodeAt(a);if(10===e){const e=s(o);null!==e&&(l+=e,i=l.length,o++)}else if(!fe(e))break}let g,h=e.md.helpers.parseLinkTitle(l,a,i);for(;h.can_continue;){const t=s(o);if(null===t)break;l+=t,a=i,i=l.length,o++,h=e.md.helpers.parseLinkTitle(l,a,i,h)}for(a<i&&m!==a&&h.ok?(g=h.str,a=h.pos):(g="",a=p,o=_);a<i;){if(!fe(l.charCodeAt(a)))break;a++}if(a<i&&10!==l.charCodeAt(a)&&g)for(g="",a=p,o=_;a<i;){if(!fe(l.charCodeAt(a)))break;a++}if(a<i&&10!==l.charCodeAt(a))return!1;const f=ve(l.slice(1,c));return!!f&&(n||(void 0===e.env.references&&(e.env.references={}),void 0===e.env.references[f]&&(e.env.references[f]={title:g,href:u}),e.line=o),!0)}],["html_block",function(e,t,r,n){let a=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;if(!e.md.options.html)return!1;if(60!==e.src.charCodeAt(a))return!1;let o=e.src.slice(a,i),s=0;for(;s<rt.length&&!rt[s][0].test(o);s++);if(s===rt.length)return!1;if(n)return rt[s][2];let l=t+1;if(!rt[s][1].test(o))for(;l<r&&!(e.sCount[l]<e.blkIndent);l++)if(a=e.bMarks[l]+e.tShift[l],i=e.eMarks[l],o=e.src.slice(a,i),rt[s][1].test(o)){0!==o.length&&l++;break}e.line=l;const c=e.push("html_block","",0);return c.map=[t,l],c.content=e.getLines(t,l,e.blkIndent,!0),!0},["paragraph","reference","blockquote"]],["heading",function(e,t,r,n){let a=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return!1;let o=e.src.charCodeAt(a);if(35!==o||a>=i)return!1;let s=1;for(o=e.src.charCodeAt(++a);35===o&&a<i&&s<=6;)s++,o=e.src.charCodeAt(++a);if(s>6||a<i&&!fe(o))return!1;if(n)return!0;i=e.skipSpacesBack(i,a);const l=e.skipCharsBack(i,35,a);l>a&&fe(e.src.charCodeAt(l-1))&&(i=l),e.line=t+1;const c=e.push("heading_open","h"+String(s),1);c.markup="########".slice(0,s),c.map=[t,e.line];const d=e.push("inline","",0);return d.content=e.src.slice(a,i).trim(),d.map=[t,e.line],d.children=[],e.push("heading_close","h"+String(s),-1).markup="########".slice(0,s),!0},["paragraph","reference","blockquote"]],["lheading",function(e,t,r){const n=e.md.block.ruler.getRules("paragraph");if(e.sCount[t]-e.blkIndent>=4)return!1;const a=e.parentType;e.parentType="paragraph";let i,o=0,s=t+1;for(;s<r&&!e.isEmpty(s);s++){if(e.sCount[s]-e.blkIndent>3)continue;if(e.sCount[s]>=e.blkIndent){let t=e.bMarks[s]+e.tShift[s];const r=e.eMarks[s];if(t<r&&(i=e.src.charCodeAt(t),(45===i||61===i)&&(t=e.skipChars(t,i),t=e.skipSpaces(t),t>=r))){o=61===i?1:2;break}}if(e.sCount[s]<0)continue;let t=!1;for(let a=0,i=n.length;a<i;a++)if(n[a](e,s,r,!0)){t=!0;break}if(t)break}if(!o)return!1;const l=e.getLines(t,s,e.blkIndent,!1).trim();e.line=s+1;const c=e.push("heading_open","h"+String(o),1);c.markup=String.fromCharCode(i),c.map=[t,e.line];const d=e.push("inline","",0);return d.content=l,d.map=[t,e.line-1],d.children=[],e.push("heading_close","h"+String(o),-1).markup=String.fromCharCode(i),e.parentType=a,!0}],["paragraph",function(e,t,r){const n=e.md.block.ruler.getRules("paragraph"),a=e.parentType;let i=t+1;for(e.parentType="paragraph";i<r&&!e.isEmpty(i);i++){if(e.sCount[i]-e.blkIndent>3)continue;if(e.sCount[i]<0)continue;let t=!1;for(let a=0,o=n.length;a<o;a++)if(n[a](e,i,r,!0)){t=!0;break}if(t)break}const o=e.getLines(t,i,e.blkIndent,!1).trim();e.line=i,e.push("paragraph_open","p",1).map=[t,e.line];const s=e.push("inline","",0);return s.content=o,s.map=[t,e.line],s.children=[],e.push("paragraph_close","p",-1),e.parentType=a,!0}]];function at(){this.ruler=new Ae;for(let e=0;e<nt.length;e++)this.ruler.push(nt[e][0],nt[e][1],{alt:(nt[e][2]||[]).slice()})}function it(e,t,r,n){this.src=e,this.env=r,this.md=t,this.tokens=n,this.tokens_meta=Array(n.length),this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache={},this.delimiters=[],this._prev_delimiters=[],this.backticks={},this.backticksScanned=!1,this.linkLevel=0}function ot(e){switch(e){case 10:case 33:case 35:case 36:case 37:case 38:case 42:case 43:case 45:case 58:case 60:case 61:case 62:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 125:case 126:return!0;default:return!1}}at.prototype.tokenize=function(e,t,r){const n=this.ruler.getRules(""),a=n.length,i=e.md.options.maxNesting;let o=t,s=!1;for(;o<r&&(e.line=o=e.skipEmptyLines(o),!(o>=r))&&!(e.sCount[o]<e.blkIndent);){if(e.level>=i){e.line=r;break}const t=e.line;let l=!1;for(let i=0;i<a;i++)if(l=n[i](e,o,r,!1),l){if(t>=e.line)throw new Error("block rule didn't increment state.line");break}if(!l)throw new Error("none of the block rules matched");e.tight=!s,e.isEmpty(e.line-1)&&(s=!0),o=e.line,o<r&&e.isEmpty(o)&&(s=!0,o++,e.line=o)}},at.prototype.parse=function(e,t,r,n){if(!e)return;const a=new this.State(e,t,r,n);this.tokenize(a,a.line,a.lineMax)},at.prototype.State=We,it.prototype.pushPending=function(){const e=new Oe("text","",0);return e.content=this.pending,e.level=this.pendingLevel,this.tokens.push(e),this.pending="",e},it.prototype.push=function(e,t,r){this.pending&&this.pushPending();const n=new Oe(e,t,r);let a=null;return r<0&&(this.level--,this.delimiters=this._prev_delimiters.pop()),n.level=this.level,r>0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],a={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(n),this.tokens_meta.push(a),n},it.prototype.scanDelims=function(e,t){const r=this.posMax,n=this.src.charCodeAt(e),a=e>0?this.src.charCodeAt(e-1):32;let i=e;for(;i<r&&this.src.charCodeAt(i)===n;)i++;const o=i-e,s=i<r?this.src.charCodeAt(i):32,l=Se(a)||be(String.fromCharCode(a)),c=Se(s)||be(String.fromCharCode(s)),d=Ee(a),u=Ee(s),p=!u&&(!c||d||l),_=!d&&(!l||u||c);return{can_open:p&&(t||!_||l),can_close:_&&(t||!p||c),length:o}},it.prototype.Token=Oe;const st=/(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;const lt=[];for(let e=0;e<256;e++)lt.push(0);function ct(e,t){let r;const n=[],a=t.length;for(let i=0;i<a;i++){const a=t[i];if(126!==a.marker)continue;if(-1===a.end)continue;const o=t[a.end];r=e.tokens[a.token],r.type="s_open",r.tag="s",r.nesting=1,r.markup="~~",r.content="",r=e.tokens[o.token],r.type="s_close",r.tag="s",r.nesting=-1,r.markup="~~",r.content="","text"===e.tokens[o.token-1].type&&"~"===e.tokens[o.token-1].content&&n.push(o.token-1)}for(;n.length;){const t=n.pop();let a=t+1;for(;a<e.tokens.length&&"s_close"===e.tokens[a].type;)a++;a--,t!==a&&(r=e.tokens[a],e.tokens[a]=e.tokens[t],e.tokens[t]=r)}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(e){lt[e.charCodeAt(0)]=1});var dt={tokenize:function(e,t){const r=e.pos,n=e.src.charCodeAt(r);if(t)return!1;if(126!==n)return!1;const a=e.scanDelims(e.pos,!0);let i=a.length;const o=String.fromCharCode(n);if(i<2)return!1;let s;i%2&&(s=e.push("text","",0),s.content=o,i--);for(let t=0;t<i;t+=2)s=e.push("text","",0),s.content=o+o,e.delimiters.push({marker:n,length:0,token:e.tokens.length-1,end:-1,open:a.can_open,close:a.can_close});return e.pos+=a.length,!0},postProcess:function(e){const t=e.tokens_meta,r=e.tokens_meta.length;ct(e,e.delimiters);for(let n=0;n<r;n++)t[n]&&t[n].delimiters&&ct(e,t[n].delimiters)}};function ut(e,t){for(let r=t.length-1;r>=0;r--){const n=t[r];if(95!==n.marker&&42!==n.marker)continue;if(-1===n.end)continue;const a=t[n.end],i=r>0&&t[r-1].end===n.end+1&&t[r-1].marker===n.marker&&t[r-1].token===n.token-1&&t[n.end+1].token===a.token+1,o=String.fromCharCode(n.marker),s=e.tokens[n.token];s.type=i?"strong_open":"em_open",s.tag=i?"strong":"em",s.nesting=1,s.markup=i?o+o:o,s.content="";const l=e.tokens[a.token];l.type=i?"strong_close":"em_close",l.tag=i?"strong":"em",l.nesting=-1,l.markup=i?o+o:o,l.content="",i&&(e.tokens[t[r-1].token].content="",e.tokens[t[n.end+1].token].content="",r--)}}var pt={tokenize:function(e,t){const r=e.pos,n=e.src.charCodeAt(r);if(t)return!1;if(95!==n&&42!==n)return!1;const a=e.scanDelims(e.pos,42===n);for(let t=0;t<a.length;t++){e.push("text","",0).content=String.fromCharCode(n),e.delimiters.push({marker:n,length:a.length,token:e.tokens.length-1,end:-1,open:a.can_open,close:a.can_close})}return e.pos+=a.length,!0},postProcess:function(e){const t=e.tokens_meta,r=e.tokens_meta.length;ut(e,e.delimiters);for(let n=0;n<r;n++)t[n]&&t[n].delimiters&&ut(e,t[n].delimiters)}};const _t=/^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/,mt=/^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;const gt=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,ht=/^&([a-z][a-z0-9]{1,31});/i;function ft(e){const t={},r=e.length;if(!r)return;let n=0,a=-2;const i=[];for(let o=0;o<r;o++){const r=e[o];if(i.push(0),e[n].marker===r.marker&&a===r.token-1||(n=o),a=r.token,r.length=r.length||0,!r.close)continue;t.hasOwnProperty(r.marker)||(t[r.marker]=[-1,-1,-1,-1,-1,-1]);const s=t[r.marker][(r.open?3:0)+r.length%3];let l=n-i[n]-1,c=l;for(;l>s;l-=i[l]+1){const t=e[l];if(t.marker===r.marker&&(t.open&&t.end<0)){let n=!1;if((t.close||r.open)&&(t.length+r.length)%3==0&&(t.length%3==0&&r.length%3==0||(n=!0)),!n){const n=l>0&&!e[l-1].open?i[l-1]+1:0;i[o]=o-l+n,i[l]=n,r.open=!1,t.end=o,t.close=!1,c=-1,a=-2;break}}}-1!==c&&(t[r.marker][(r.open?3:0)+(r.length||0)%3]=c)}}const Et=[["text",function(e,t){let r=e.pos;for(;r<e.posMax&&!ot(e.src.charCodeAt(r));)r++;return r!==e.pos&&(t||(e.pending+=e.src.slice(e.pos,r)),e.pos=r,!0)}],["linkify",function(e,t){if(!e.md.options.linkify)return!1;if(e.linkLevel>0)return!1;const r=e.pos;if(r+3>e.posMax)return!1;if(58!==e.src.charCodeAt(r))return!1;if(47!==e.src.charCodeAt(r+1))return!1;if(47!==e.src.charCodeAt(r+2))return!1;const n=e.pending.match(st);if(!n)return!1;const a=n[1],i=e.md.linkify.matchAtStart(e.src.slice(r-a.length));if(!i)return!1;let o=i.url;if(o.length<=a.length)return!1;o=o.replace(/\*+$/,"");const s=e.md.normalizeLink(o);if(!e.md.validateLink(s))return!1;if(!t){e.pending=e.pending.slice(0,-a.length);const t=e.push("link_open","a",1);t.attrs=[["href",s]],t.markup="linkify",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(o);const r=e.push("link_close","a",-1);r.markup="linkify",r.info="auto"}return e.pos+=o.length-a.length,!0}],["newline",function(e,t){let r=e.pos;if(10!==e.src.charCodeAt(r))return!1;const n=e.pending.length-1,a=e.posMax;if(!t)if(n>=0&&32===e.pending.charCodeAt(n))if(n>=1&&32===e.pending.charCodeAt(n-1)){let t=n-1;for(;t>=1&&32===e.pending.charCodeAt(t-1);)t--;e.pending=e.pending.slice(0,t),e.push("hardbreak","br",0)}else e.pending=e.pending.slice(0,-1),e.push("softbreak","br",0);else e.push("softbreak","br",0);for(r++;r<a&&fe(e.src.charCodeAt(r));)r++;return e.pos=r,!0}],["escape",function(e,t){let r=e.pos;const n=e.posMax;if(92!==e.src.charCodeAt(r))return!1;if(r++,r>=n)return!1;let a=e.src.charCodeAt(r);if(10===a){for(t||e.push("hardbreak","br",0),r++;r<n&&(a=e.src.charCodeAt(r),fe(a));)r++;return e.pos=r,!0}let i=e.src[r];if(a>=55296&&a<=56319&&r+1<n){const t=e.src.charCodeAt(r+1);t>=56320&&t<=57343&&(i+=e.src[r+1],r++)}const o="\\"+i;if(!t){const t=e.push("text_special","",0);a<256&&0!==lt[a]?t.content=i:t.content=o,t.markup=o,t.info="escape"}return e.pos=r+1,!0}],["backticks",function(e,t){let r=e.pos;if(96!==e.src.charCodeAt(r))return!1;const n=r;r++;const a=e.posMax;for(;r<a&&96===e.src.charCodeAt(r);)r++;const i=e.src.slice(n,r),o=i.length;if(e.backticksScanned&&(e.backticks[o]||0)<=n)return t||(e.pending+=i),e.pos+=o,!0;let s,l=r;for(;-1!==(s=e.src.indexOf("`",l));){for(l=s+1;l<a&&96===e.src.charCodeAt(l);)l++;const n=l-s;if(n===o){if(!t){const t=e.push("code_inline","code",0);t.markup=i,t.content=e.src.slice(r,s).replace(/\n/g," ").replace(/^ (.+) $/,"$1")}return e.pos=l,!0}e.backticks[n]=s}return e.backticksScanned=!0,t||(e.pending+=i),e.pos+=o,!0}],["strikethrough",dt.tokenize],["emphasis",pt.tokenize],["link",function(e,t){let r,n,a,i,o="",s="",l=e.pos,c=!0;if(91!==e.src.charCodeAt(e.pos))return!1;const d=e.pos,u=e.posMax,p=e.pos+1,_=e.md.helpers.parseLinkLabel(e,e.pos,!0);if(_<0)return!1;let m=_+1;if(m<u&&40===e.src.charCodeAt(m)){for(c=!1,m++;m<u&&(r=e.src.charCodeAt(m),fe(r)||10===r);m++);if(m>=u)return!1;if(l=m,a=e.md.helpers.parseLinkDestination(e.src,m,e.posMax),a.ok){for(o=e.md.normalizeLink(a.str),e.md.validateLink(o)?m=a.pos:o="",l=m;m<u&&(r=e.src.charCodeAt(m),fe(r)||10===r);m++);if(a=e.md.helpers.parseLinkTitle(e.src,m,e.posMax),m<u&&l!==m&&a.ok)for(s=a.str,m=a.pos;m<u&&(r=e.src.charCodeAt(m),fe(r)||10===r);m++);}(m>=u||41!==e.src.charCodeAt(m))&&(c=!0),m++}if(c){if(void 0===e.env.references)return!1;if(m<u&&91===e.src.charCodeAt(m)?(l=m+1,m=e.md.helpers.parseLinkLabel(e,m),m>=0?n=e.src.slice(l,m++):m=_+1):m=_+1,n||(n=e.src.slice(p,_)),i=e.env.references[ve(n)],!i)return e.pos=d,!1;o=i.href,s=i.title}if(!t){e.pos=p,e.posMax=_;const t=[["href",o]];e.push("link_open","a",1).attrs=t,s&&t.push(["title",s]),e.linkLevel++,e.md.inline.tokenize(e),e.linkLevel--,e.push("link_close","a",-1)}return e.pos=m,e.posMax=u,!0}],["image",function(e,t){let r,n,a,i,o,s,l,c,d="";const u=e.pos,p=e.posMax;if(33!==e.src.charCodeAt(e.pos))return!1;if(91!==e.src.charCodeAt(e.pos+1))return!1;const _=e.pos+2,m=e.md.helpers.parseLinkLabel(e,e.pos+1,!1);if(m<0)return!1;if(i=m+1,i<p&&40===e.src.charCodeAt(i)){for(i++;i<p&&(r=e.src.charCodeAt(i),fe(r)||10===r);i++);if(i>=p)return!1;for(c=i,s=e.md.helpers.parseLinkDestination(e.src,i,e.posMax),s.ok&&(d=e.md.normalizeLink(s.str),e.md.validateLink(d)?i=s.pos:d=""),c=i;i<p&&(r=e.src.charCodeAt(i),fe(r)||10===r);i++);if(s=e.md.helpers.parseLinkTitle(e.src,i,e.posMax),i<p&&c!==i&&s.ok)for(l=s.str,i=s.pos;i<p&&(r=e.src.charCodeAt(i),fe(r)||10===r);i++);else l="";if(i>=p||41!==e.src.charCodeAt(i))return e.pos=u,!1;i++}else{if(void 0===e.env.references)return!1;if(i<p&&91===e.src.charCodeAt(i)?(c=i+1,i=e.md.helpers.parseLinkLabel(e,i),i>=0?a=e.src.slice(c,i++):i=m+1):i=m+1,a||(a=e.src.slice(_,m)),o=e.env.references[ve(a)],!o)return e.pos=u,!1;d=o.href,l=o.title}if(!t){n=e.src.slice(_,m);const t=[];e.md.inline.parse(n,e.md,e.env,t);const r=e.push("image","img",0),a=[["src",d],["alt",""]];r.attrs=a,r.children=t,r.content=n,l&&a.push(["title",l])}return e.pos=i,e.posMax=p,!0}],["autolink",function(e,t){let r=e.pos;if(60!==e.src.charCodeAt(r))return!1;const n=e.pos,a=e.posMax;for(;;){if(++r>=a)return!1;const t=e.src.charCodeAt(r);if(60===t)return!1;if(62===t)break}const i=e.src.slice(n+1,r);if(mt.test(i)){const r=e.md.normalizeLink(i);if(!e.md.validateLink(r))return!1;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",r]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(i);const n=e.push("link_close","a",-1);n.markup="autolink",n.info="auto"}return e.pos+=i.length+2,!0}if(_t.test(i)){const r=e.md.normalizeLink("mailto:"+i);if(!e.md.validateLink(r))return!1;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",r]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(i);const n=e.push("link_close","a",-1);n.markup="autolink",n.info="auto"}return e.pos+=i.length+2,!0}return!1}],["html_inline",function(e,t){if(!e.md.options.html)return!1;const r=e.posMax,n=e.pos;if(60!==e.src.charCodeAt(n)||n+2>=r)return!1;const a=e.src.charCodeAt(n+1);if(33!==a&&63!==a&&47!==a&&!function(e){const t=32|e;return t>=97&&t<=122}(a))return!1;const i=e.src.slice(n).match(et);if(!i)return!1;if(!t){const t=e.push("html_inline","",0);t.content=i[0],o=t.content,/^<a[>\s]/i.test(o)&&e.linkLevel++,function(e){return/^<\/a\s*>/i.test(e)}(t.content)&&e.linkLevel--}var o;return e.pos+=i[0].length,!0}],["entity",function(e,t){const r=e.pos,n=e.posMax;if(38!==e.src.charCodeAt(r))return!1;if(r+1>=n)return!1;if(35===e.src.charCodeAt(r+1)){const n=e.src.slice(r).match(gt);if(n){if(!t){const t="x"===n[1][0].toLowerCase()?parseInt(n[1].slice(1),16):parseInt(n[1],10),r=e.push("text_special","",0);r.content=ie(t)?oe(t):oe(65533),r.markup=n[0],r.info="entity"}return e.pos+=n[0].length,!0}}else{const n=e.src.slice(r).match(ht);if(n){const r=ee(n[0]);if(r!==n[0]){if(!t){const t=e.push("text_special","",0);t.content=r,t.markup=n[0],t.info="entity"}return e.pos+=n[0].length,!0}}}return!1}]],bt=[["balance_pairs",function(e){const t=e.tokens_meta,r=e.tokens_meta.length;ft(e.delimiters);for(let e=0;e<r;e++)t[e]&&t[e].delimiters&&ft(t[e].delimiters)}],["strikethrough",dt.postProcess],["emphasis",pt.postProcess],["fragments_join",function(e){let t,r,n=0;const a=e.tokens,i=e.tokens.length;for(t=r=0;t<i;t++)a[t].nesting<0&&n--,a[t].level=n,a[t].nesting>0&&n++,"text"===a[t].type&&t+1<i&&"text"===a[t+1].type?a[t+1].content=a[t].content+a[t+1].content:(t!==r&&(a[r]=a[t]),r++);t!==r&&(a.length=r)}]];function St(){this.ruler=new Ae;for(let e=0;e<Et.length;e++)this.ruler.push(Et[e][0],Et[e][1]);this.ruler2=new Ae;for(let e=0;e<bt.length;e++)this.ruler2.push(bt[e][0],bt[e][1])}function vt(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){t&&Object.keys(t).forEach(function(r){e[r]=t[r]})}),e}function Tt(e){return Object.prototype.toString.call(e)}function yt(e){return"[object Function]"===Tt(e)}function Ct(e){return e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}St.prototype.skipToken=function(e){const t=e.pos,r=this.ruler.getRules(""),n=r.length,a=e.md.options.maxNesting,i=e.cache;if(void 0!==i[t])return void(e.pos=i[t]);let o=!1;if(e.level<a){for(let a=0;a<n;a++)if(e.level++,o=r[a](e,!0),e.level--,o){if(t>=e.pos)throw new Error("inline rule didn't increment state.pos");break}}else e.pos=e.posMax;o||e.pos++,i[t]=e.pos},St.prototype.tokenize=function(e){const t=this.ruler.getRules(""),r=t.length,n=e.posMax,a=e.md.options.maxNesting;for(;e.pos<n;){const i=e.pos;let o=!1;if(e.level<a)for(let n=0;n<r;n++)if(o=t[n](e,!1),o){if(i>=e.pos)throw new Error("inline rule didn't increment state.pos");break}if(o){if(e.pos>=n)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()},St.prototype.parse=function(e,t,r,n){const a=new this.State(e,t,r,n);this.tokenize(a);const i=this.ruler2.getRules(""),o=i.length;for(let e=0;e<o;e++)i[e](a)},St.prototype.State=it;const Nt={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};const Rt={"http:":{validate:function(e,t,r){const n=e.slice(t);return r.re.http||(r.re.http=new RegExp("^\\/\\/"+r.re.src_auth+r.re.src_host_port_strict+r.re.src_path,"i")),r.re.http.test(n)?n.match(r.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(e,t,r){const n=e.slice(t);return r.re.no_http||(r.re.no_http=new RegExp("^"+r.re.src_auth+"(?:localhost|(?:(?:"+r.re.src_domain+")\\.)+"+r.re.src_domain_root+")"+r.re.src_port+r.re.src_host_terminator+r.re.src_path,"i")),r.re.no_http.test(n)?t>=3&&":"===e[t-3]||t>=3&&"/"===e[t-3]?0:n.match(r.re.no_http)[0].length:0}},"mailto:":{validate:function(e,t,r){const n=e.slice(t);return r.re.mailto||(r.re.mailto=new RegExp("^"+r.re.src_email_name+"@"+r.re.src_host_strict,"i")),r.re.mailto.test(n)?n.match(r.re.mailto)[0].length:0}}},At="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function Ot(e){const t=e.re=function(e){const t={};e=e||{},t.src_Any=M.source,t.src_Cc=k.source,t.src_Z=F.source,t.src_P=L.source,t.src_ZPCc=[t.src_Z,t.src_P,t.src_Cc].join("|"),t.src_ZCc=[t.src_Z,t.src_Cc].join("|");const r="[><|]";return t.src_pseudo_letter="(?:(?![><|]|"+t.src_ZPCc+")"+t.src_Any+")",t.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",t.src_auth="(?:(?:(?!"+t.src_ZCc+"|[@/\\[\\]()]).)+@)?",t.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",t.src_host_terminator="(?=$|[><|]|"+t.src_ZPCc+")(?!"+(e["---"]?"-(?!--)|":"-|")+"_|:\\d|\\.-|\\.(?!$|"+t.src_ZPCc+"))",t.src_path="(?:[/?#](?:(?!"+t.src_ZCc+"|"+r+"|[()[\\]{}.,\"'?!\\-;]).|\\[(?:(?!"+t.src_ZCc+"|\\]).)*\\]|\\((?:(?!"+t.src_ZCc+"|[)]).)*\\)|\\{(?:(?!"+t.src_ZCc+'|[}]).)*\\}|\\"(?:(?!'+t.src_ZCc+'|["]).)+\\"|\\\'(?:(?!'+t.src_ZCc+"|[']).)+\\'|\\'(?="+t.src_pseudo_letter+"|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!"+t.src_ZCc+"|[.]|$)|"+(e["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+",(?!"+t.src_ZCc+"|$)|;(?!"+t.src_ZCc+"|$)|\\!+(?!"+t.src_ZCc+"|[!]|$)|\\?(?!"+t.src_ZCc+"|[?]|$))+|\\/)?",t.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*',t.src_xn="xn--[a-z0-9\\-]{1,59}",t.src_domain_root="(?:"+t.src_xn+"|"+t.src_pseudo_letter+"{1,63})",t.src_domain="(?:"+t.src_xn+"|(?:"+t.src_pseudo_letter+")|(?:"+t.src_pseudo_letter+"(?:-|"+t.src_pseudo_letter+"){0,61}"+t.src_pseudo_letter+"))",t.src_host="(?:(?:(?:(?:"+t.src_domain+")\\.)*"+t.src_domain+"))",t.tpl_host_fuzzy="(?:"+t.src_ip4+"|(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%)))",t.tpl_host_no_ip_fuzzy="(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%))",t.src_host_strict=t.src_host+t.src_host_terminator,t.tpl_host_fuzzy_strict=t.tpl_host_fuzzy+t.src_host_terminator,t.src_host_port_strict=t.src_host+t.src_port+t.src_host_terminator,t.tpl_host_port_fuzzy_strict=t.tpl_host_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_port_no_ip_fuzzy_strict=t.tpl_host_no_ip_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_fuzzy_test="localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:"+t.src_ZPCc+"|>|$))",t.tpl_email_fuzzy='(^|[><|]|"|\\(|'+t.src_ZCc+")("+t.src_email_name+"@"+t.tpl_host_fuzzy_strict+")",t.tpl_link_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`||]|"+t.src_ZPCc+"))((?![$+<=>^`||])"+t.tpl_host_port_fuzzy_strict+t.src_path+")",t.tpl_link_no_ip_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`||]|"+t.src_ZPCc+"))((?![$+<=>^`||])"+t.tpl_host_port_no_ip_fuzzy_strict+t.src_path+")",t}(e.__opts__),r=e.__tlds__.slice();function n(e){return e.replace("%TLDS%",t.src_tlds)}e.onCompile(),e.__tlds_replaced__||r.push("a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]"),r.push(t.src_xn),t.src_tlds=r.join("|"),t.email_fuzzy=RegExp(n(t.tpl_email_fuzzy),"i"),t.link_fuzzy=RegExp(n(t.tpl_link_fuzzy),"i"),t.link_no_ip_fuzzy=RegExp(n(t.tpl_link_no_ip_fuzzy),"i"),t.host_fuzzy_test=RegExp(n(t.tpl_host_fuzzy_test),"i");const a=[];function i(e,t){throw new Error('(LinkifyIt) Invalid schema "'+e+'": '+t)}e.__compiled__={},Object.keys(e.__schemas__).forEach(function(t){const r=e.__schemas__[t];if(null===r)return;const n={validate:null,link:null};if(e.__compiled__[t]=n,"[object Object]"===Tt(r))return!function(e){return"[object RegExp]"===Tt(e)}(r.validate)?yt(r.validate)?n.validate=r.validate:i(t,r):n.validate=function(e){return function(t,r){const n=t.slice(r);return e.test(n)?n.match(e)[0].length:0}}(r.validate),void(yt(r.normalize)?n.normalize=r.normalize:r.normalize?i(t,r):n.normalize=function(e,t){t.normalize(e)});!function(e){return"[object String]"===Tt(e)}(r)?i(t,r):a.push(t)}),a.forEach(function(t){e.__compiled__[e.__schemas__[t]]&&(e.__compiled__[t].validate=e.__compiled__[e.__schemas__[t]].validate,e.__compiled__[t].normalize=e.__compiled__[e.__schemas__[t]].normalize)}),e.__compiled__[""]={validate:null,normalize:function(e,t){t.normalize(e)}};const o=Object.keys(e.__compiled__).filter(function(t){return t.length>0&&e.__compiled__[t]}).map(Ct).join("|");e.re.schema_test=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+o+")","i"),e.re.schema_search=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+o+")","ig"),e.re.schema_at_start=RegExp("^"+e.re.schema_search.source,"i"),e.re.pretest=RegExp("("+e.re.schema_test.source+")|("+e.re.host_fuzzy_test.source+")|@","i"),function(e){e.__index__=-1,e.__text_cache__=""}(e)}function It(e,t){const r=e.__index__,n=e.__last_index__,a=e.__text_cache__.slice(r,n);this.schema=e.__schema__.toLowerCase(),this.index=r+t,this.lastIndex=n+t,this.raw=a,this.text=a,this.url=a}function xt(e,t){const r=new It(e,t);return e.__compiled__[r.schema].normalize(r,e),r}function wt(e,t){if(!(this instanceof wt))return new wt(e,t);var r;t||(r=e,Object.keys(r||{}).reduce(function(e,t){return e||Nt.hasOwnProperty(t)},!1)&&(t=e,e={})),this.__opts__=vt({},Nt,t),this.__index__=-1,this.__last_index__=-1,this.__schema__="",this.__text_cache__="",this.__schemas__=vt({},Rt,e),this.__compiled__={},this.__tlds__=At,this.__tlds_replaced__=!1,this.re={},Ot(this)}wt.prototype.add=function(e,t){return this.__schemas__[e]=t,Ot(this),this},wt.prototype.set=function(e){return this.__opts__=vt(this.__opts__,e),this},wt.prototype.test=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return!1;let t,r,n,a,i,o,s,l,c;if(this.re.schema_test.test(e))for(s=this.re.schema_search,s.lastIndex=0;null!==(t=s.exec(e));)if(a=this.testSchemaAt(e,t[2],s.lastIndex),a){this.__schema__=t[2],this.__index__=t.index+t[1].length,this.__last_index__=t.index+t[0].length+a;break}return this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&(l=e.search(this.re.host_fuzzy_test),l>=0&&(this.__index__<0||l<this.__index__)&&null!==(r=e.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy))&&(i=r.index+r[1].length,(this.__index__<0||i<this.__index__)&&(this.__schema__="",this.__index__=i,this.__last_index__=r.index+r[0].length))),this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&(c=e.indexOf("@"),c>=0&&null!==(n=e.match(this.re.email_fuzzy))&&(i=n.index+n[1].length,o=n.index+n[0].length,(this.__index__<0||i<this.__index__||i===this.__index__&&o>this.__last_index__)&&(this.__schema__="mailto:",this.__index__=i,this.__last_index__=o))),this.__index__>=0},wt.prototype.pretest=function(e){return this.re.pretest.test(e)},wt.prototype.testSchemaAt=function(e,t,r){return this.__compiled__[t.toLowerCase()]?this.__compiled__[t.toLowerCase()].validate(e,r,this):0},wt.prototype.match=function(e){const t=[];let r=0;this.__index__>=0&&this.__text_cache__===e&&(t.push(xt(this,r)),r=this.__last_index__);let n=r?e.slice(r):e;for(;this.test(n);)t.push(xt(this,r)),n=n.slice(this.__last_index__),r+=this.__last_index__;return t.length?t:null},wt.prototype.matchAtStart=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return null;const t=this.re.schema_at_start.exec(e);if(!t)return null;const r=this.testSchemaAt(e,t[2],t[0].length);return r?(this.__schema__=t[2],this.__index__=t.index+t[1].length,this.__last_index__=t.index+t[0].length+r,xt(this,0)):null},wt.prototype.tlds=function(e,t){return e=Array.isArray(e)?e:[e],t?(this.__tlds__=this.__tlds__.concat(e).sort().filter(function(e,t,r){return e!==r[t-1]}).reverse(),Ot(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=!0,Ot(this),this)},wt.prototype.normalize=function(e){e.schema||(e.url="http://"+e.url),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url="mailto:"+e.url)},wt.prototype.onCompile=function(){};const Dt=2147483647,Mt=36,kt=/^xn--/,Lt=/[^\0-\x7F]/,Pt=/[\x2E\u3002\uFF0E\uFF61]/g,Ft={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},Bt=Math.floor,Ut=String.fromCharCode;function Gt(e){throw new RangeError(Ft[e])}function zt(e,t){const r=e.split("@");let n="";r.length>1&&(n=r[0]+"@",e=r[1]);const a=function(e,t){const r=[];let n=e.length;for(;n--;)r[n]=t(e[n]);return r}((e=e.replace(Pt,".")).split("."),t).join(".");return n+a}function Yt(e){const t=[];let r=0;const n=e.length;for(;r<n;){const a=e.charCodeAt(r++);if(a>=55296&&a<=56319&&r<n){const n=e.charCodeAt(r++);56320==(64512&n)?t.push(((1023&a)<<10)+(1023&n)+65536):(t.push(a),r--)}else t.push(a)}return t}const qt=function(e){return e>=48&&e<58?e-48+26:e>=65&&e<91?e-65:e>=97&&e<123?e-97:Mt},Ht=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},Vt=function(e,t,r){let n=0;for(e=r?Bt(e/700):e>>1,e+=Bt(e/t);e>455;n+=Mt)e=Bt(e/35);return Bt(n+36*e/(e+38))},$t=function(e){const t=[],r=e.length;let n=0,a=128,i=72,o=e.lastIndexOf("-");o<0&&(o=0);for(let r=0;r<o;++r)e.charCodeAt(r)>=128&&Gt("not-basic"),t.push(e.charCodeAt(r));for(let s=o>0?o+1:0;s<r;){const o=n;for(let t=1,a=Mt;;a+=Mt){s>=r&&Gt("invalid-input");const o=qt(e.charCodeAt(s++));o>=Mt&&Gt("invalid-input"),o>Bt((Dt-n)/t)&&Gt("overflow"),n+=o*t;const l=a<=i?1:a>=i+26?26:a-i;if(o<l)break;const c=Mt-l;t>Bt(Dt/c)&&Gt("overflow"),t*=c}const l=t.length+1;i=Vt(n-o,l,0==o),Bt(n/l)>Dt-a&&Gt("overflow"),a+=Bt(n/l),n%=l,t.splice(n++,0,a)}return String.fromCodePoint(...t)},Wt=function(e){const t=[],r=(e=Yt(e)).length;let n=128,a=0,i=72;for(const r of e)r<128&&t.push(Ut(r));const o=t.length;let s=o;for(o&&t.push("-");s<r;){let r=Dt;for(const t of e)t>=n&&t<r&&(r=t);const l=s+1;r-n>Bt((Dt-a)/l)&&Gt("overflow"),a+=(r-n)*l,n=r;for(const r of e)if(r<n&&++a>Dt&&Gt("overflow"),r===n){let e=a;for(let r=Mt;;r+=Mt){const n=r<=i?1:r>=i+26?26:r-i;if(e<n)break;const a=e-n,o=Mt-n;t.push(Ut(Ht(n+a%o,0))),e=Bt(a/o)}t.push(Ut(Ht(e,0))),i=Vt(a,l,s===o),a=0,++s}++a,++n}return t.join("")},jt=function(e){return zt(e,function(e){return Lt.test(e)?"xn--"+Wt(e):e})},Qt=function(e){return zt(e,function(e){return kt.test(e)?$t(e.slice(4).toLowerCase()):e})};const Kt={default:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:100},components:{core:{},block:{},inline:{}}},zero:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["paragraph"]},inline:{rules:["text"],rules2:["balance_pairs","fragments_join"]}}},commonmark:{options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["blockquote","code","fence","heading","hr","html_block","lheading","list","reference","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","html_inline","image","link","newline","text"],rules2:["balance_pairs","emphasis","fragments_join"]}}}},Xt=/^(vbscript|javascript|file|data):/,Zt=/^data:image\/(gif|png|jpeg|webp);/;function Jt(e){const t=e.trim().toLowerCase();return!Xt.test(t)||Zt.test(t)}const er=["http:","https:","mailto:"];function tr(e){const t=x(e,!0);if(t.hostname&&(!t.protocol||er.indexOf(t.protocol)>=0))try{t.hostname=jt(t.hostname)}catch(e){}return h(f(t))}function rr(e){const t=x(e,!0);if(t.hostname&&(!t.protocol||er.indexOf(t.protocol)>=0))try{t.hostname=Qt(t.hostname)}catch(e){}return m(f(t),m.defaultChars+"%")}function nr(e,t){if(!(this instanceof nr))return new nr(e,t);t||te(e)||(t=e||{},e="default"),this.inline=new St,this.block=new at,this.core=new $e,this.renderer=new Re,this.linkify=new wt,this.validateLink=Jt,this.normalizeLink=tr,this.normalizeLinkText=rr,this.utils=ye,this.helpers=ne({},Ce),this.options={},this.configure(e),t&&this.set(t)}nr.prototype.set=function(e){return ne(this.options,e),this},nr.prototype.configure=function(e){const t=this;if(te(e)){const t=e;if(!(e=Kt[t]))throw new Error('Wrong `markdown-it` preset "'+t+'", check name')}if(!e)throw new Error("Wrong `markdown-it` preset, can't be empty");return e.options&&t.set(e.options),e.components&&Object.keys(e.components).forEach(function(r){e.components[r].rules&&t[r].ruler.enableOnly(e.components[r].rules),e.components[r].rules2&&t[r].ruler2.enableOnly(e.components[r].rules2)}),this},nr.prototype.enable=function(e,t){let r=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){r=r.concat(this[t].ruler.enable(e,!0))},this),r=r.concat(this.inline.ruler2.enable(e,!0));const n=e.filter(function(e){return r.indexOf(e)<0});if(n.length&&!t)throw new Error("MarkdownIt. Failed to enable unknown rule(s): "+n);return this},nr.prototype.disable=function(e,t){let r=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){r=r.concat(this[t].ruler.disable(e,!0))},this),r=r.concat(this.inline.ruler2.disable(e,!0));const n=e.filter(function(e){return r.indexOf(e)<0});if(n.length&&!t)throw new Error("MarkdownIt. Failed to disable unknown rule(s): "+n);return this},nr.prototype.use=function(e){const t=[this].concat(Array.prototype.slice.call(arguments,1));return e.apply(e,t),this},nr.prototype.parse=function(e,t){if("string"!=typeof e)throw new Error("Input data should be a String");const r=new this.core.State(e,this,t);return this.core.process(r),r.tokens},nr.prototype.render=function(e,t){return t=t||{},this.renderer.render(this.parse(e,t),this.options,t)},nr.prototype.parseInline=function(e,t){const r=new this.core.State(e,this,t);return r.inlineMode=!0,this.core.process(r),r.tokens},nr.prototype.renderInline=function(e,t){return t=t||{},this.renderer.render(this.parseInline(e,t),this.options,t)};const ar=/\\([ \\!"#$%&'()*+,./:;<=>?@[\]^_`{|}~-])/g;function ir(e,t){const r=e.posMax,n=e.pos;if(94!==e.src.charCodeAt(n))return!1;if(t)return!1;if(n+2>=r)return!1;e.pos=n+1;let a=!1;for(;e.pos<r;){if(94===e.src.charCodeAt(e.pos)){a=!0;break}e.md.inline.skipToken(e)}if(!a||n+1===e.pos)return e.pos=n,!1;const i=e.src.slice(n+1,e.pos);if(i.match(/(^|[^\\])(\\\\)*\s/))return e.pos=n,!1;e.posMax=e.pos,e.pos=n+1;e.push("sup_open","sup",1).markup="^";e.push("text","",0).content=i.replace(ar,"$1");return e.push("sup_close","sup",-1).markup="^",e.pos=e.posMax+1,e.posMax=r,!0}function or(e){e.inline.ruler.after("emphasis","sup",ir)}const sr=/\\([ \\!"#$%&'()*+,./:;<=>?@[\]^_`{|}~-])/g;function lr(e,t){const r=e.posMax,n=e.pos;if(126!==e.src.charCodeAt(n))return!1;if(t)return!1;if(n+2>=r)return!1;e.pos=n+1;let a=!1;for(;e.pos<r;){if(126===e.src.charCodeAt(e.pos)){a=!0;break}e.md.inline.skipToken(e)}if(!a||n+1===e.pos)return e.pos=n,!1;const i=e.src.slice(n+1,e.pos);if(i.match(/(^|[^\\])(\\\\)*\s/))return e.pos=n,!1;e.posMax=e.pos,e.pos=n+1;e.push("sub_open","sub",1).markup="~";e.push("text","",0).content=i.replace(sr,"$1");return e.push("sub_close","sub",-1).markup="~",e.pos=e.posMax+1,e.posMax=r,!0}function cr(e){e.inline.ruler.after("emphasis","sub",lr)}function dr(e){function t(e,t){const r=[],n=t.length;for(let a=0;a<n;a++){const n=t[a];if(61!==n.marker)continue;if(-1===n.end)continue;const i=t[n.end],o=e.tokens[n.token];o.type="mark_open",o.tag="mark",o.nesting=1,o.markup="==",o.content="";const s=e.tokens[i.token];s.type="mark_close",s.tag="mark",s.nesting=-1,s.markup="==",s.content="","text"===e.tokens[i.token-1].type&&"="===e.tokens[i.token-1].content&&r.push(i.token-1)}for(;r.length;){const t=r.pop();let n=t+1;for(;n<e.tokens.length&&"mark_close"===e.tokens[n].type;)n++;if(n--,t!==n){const r=e.tokens[n];e.tokens[n]=e.tokens[t],e.tokens[t]=r}}}e.inline.ruler.before("emphasis","mark",function(e,t){const r=e.pos,n=e.src.charCodeAt(r);if(t)return!1;if(61!==n)return!1;const a=e.scanDelims(e.pos,!0);let i=a.length;const o=String.fromCharCode(n);if(i<2)return!1;if(i%2){e.push("text","",0).content=o,i--}for(let t=0;t<i;t+=2){e.push("text","",0).content=o+o,(a.can_open||a.can_close)&&e.delimiters.push({marker:n,length:0,jump:t/2,token:e.tokens.length-1,end:-1,open:a.can_open,close:a.can_close})}return e.pos+=a.length,!0}),e.inline.ruler2.before("emphasis","mark",function(e){let r;const n=e.tokens_meta,a=(e.tokens_meta||[]).length;for(t(e,e.delimiters),r=0;r<a;r++)n[r]&&n[r].delimiters&&t(e,n[r].delimiters)})}var ur={html:!0,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!0,typographer:!0,imgDescEnabled:!0,katex:{throwOnError:!1,errorColor:"#cc0000",enableBareBlocks:!0,enableMathBlockInHtml:!0,enableMathInlineInHtml:!0,strict:"ignore",trust:!0},toc:{includeLevel:[1,2,3]},smiles:{disableColors:!1,width:150,height:150},lineNumbers:{enable:!1,nested:!0}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function pr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _r=class e{static clone(t){let r=Array.isArray(t)?Array():{};for(let n in t){let a=t[n];"function"==typeof a.clone?r[n]=a.clone():r[n]="object"==typeof a?e.clone(a):a}return r}static equals(e,t){if(e.length!==t.length)return!1;let r=e.slice().sort(),n=t.slice().sort();for(var a=0;a<r.length;a++)if(r[a]!==n[a])return!1;return!0}static print(e){if(0==e.length)return"";let t="(";for(let r=0;r<e.length;r++)t+=e[r].id?e[r].id+", ":e[r]+", ";return t=t.substring(0,t.length-2),t+")"}static each(e,t){for(let r=0;r<e.length;r++)t(e[r])}static get(e,t,r){for(let n=0;n<e.length;n++)if(e[n][t]==r)return e[n]}static contains(e,t){if(t.property||t.func){if(t.func){for(let r=0;r<e.length;r++)if(t.func(e[r]))return!0}else for(let r=0;r<e.length;r++)if(e[r][t.property]==t.value)return!0}else for(let r=0;r<e.length;r++)if(e[r]==t.value)return!0;return!1}static intersection(e,t){let r=new Array;for(let n=0;n<e.length;n++)for(let a=0;a<t.length;a++)e[n]===t[a]&&r.push(e[n]);return r}static unique(e){let t={};return e.filter(function(e){return void 0===t[e]&&(t[e]=!0)})}static count(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}static toggle(e,t){let r=Array(),n=!1;for(let a=0;a<e.length;a++)e[a]!==t?r.push(e[a]):n=!0;return n||r.push(t),r}static remove(e,t){let r=Array();for(let n=0;n<e.length;n++)e[n]!==t&&r.push(e[n]);return r}static removeUnique(e,t){let r=e.indexOf(t);return r>-1&&e.splice(r,1),e}static removeAll(e,t){return e.filter(function(e){return-1===t.indexOf(e)})}static merge(e,t){let r=new Array(e.length+t.length);for(let t=0;t<e.length;t++)r[t]=e[t];for(let n=0;n<t.length;n++)r[e.length+n]=t[n];return r}static containsAll(e,t){let r=0;for(let n=0;n<e.length;n++)for(let a=0;a<t.length;a++)e[n]===t[a]&&r++;return r===t.length}static sortByAtomicNumberDesc(e){let t=e.map(function(e,t){return{index:t,value:e.atomicNumber.split(".").map(Number)}});return t.sort(function(e,t){let r=Math.min(t.value.length,e.value.length),n=0;for(;n<r&&t.value[n]===e.value[n];)n++;return n===r?t.value.length-e.value.length:t.value[n]-e.value[n]}),t.map(function(t){return e[t.index]})}static deepCopy(t){let r=Array();for(let n=0;n<t.length;n++){let a=t[n];r[n]=a instanceof Array?e.deepCopy(a):a}return r}};var mr=class e{static round(e,t){return t=t||1,Number(Math.round(e+"e"+t)+"e-"+t)}static meanAngle(e){let t=0,r=0;for(var n=0;n<e.length;n++)t+=Math.sin(e[n]),r+=Math.cos(e[n]);return Math.atan2(t/e.length,r/e.length)}static innerAngle(t){return e.toRad(180*(t-2)/t)}static polyCircumradius(e,t){return e/(2*Math.sin(Math.PI/t))}static apothem(e,t){return e*Math.cos(Math.PI/t)}static apothemFromSideLength(t,r){let n=e.polyCircumradius(t,r);return e.apothem(n,r)}static centralAngle(t){return e.toRad(360/t)}static toDeg(t){return t*e.degFactor}static toRad(t){return t*e.radFactor}static parityOfPermutation(e){let t=new Uint8Array(e.length),r=0,n=function(r,a=0){return 1===t[r]?a:(a++,t[r]=1,n(e[r],a))};for(var a=0;a<e.length;a++){if(1===t[a])continue;r+=1-n(a)%2}return r%2?-1:1}static get radFactor(){return Math.PI/180}static get degFactor(){return 180/Math.PI}static get twoPI(){return 2*Math.PI}};var gr,hr,fr,Er,br,Sr,vr,Tr,yr=class e{constructor(e,t){0==arguments.length?(this.x=0,this.y=0):1==arguments.length?(this.x=e.x,this.y=e.y):(this.x=e,this.y=t)}clone(){return new e(this.x,this.y)}toString(){return"("+this.x+","+this.y+")"}add(e){return this.x+=e.x,this.y+=e.y,this}subtract(e){return this.x-=e.x,this.y-=e.y,this}divide(e){return this.x/=e,this.y/=e,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}invert(){return this.x=-this.x,this.y=-this.y,this}angle(){return Math.atan2(this.y,this.x)}distance(e){return Math.sqrt((e.x-this.x)*(e.x-this.x)+(e.y-this.y)*(e.y-this.y))}distanceSq(e){return(e.x-this.x)*(e.x-this.x)+(e.y-this.y)*(e.y-this.y)}clockwise(e){let t=this.y*e.x,r=this.x*e.y;return t>r?-1:t===r?0:1}relativeClockwise(e,t){let r=(this.y-e.y)*(t.x-e.x),n=(this.x-e.x)*(t.y-e.y);return r>n?-1:r===n?0:1}rotate(t){let r=new e(0,0),n=Math.cos(t),a=Math.sin(t);return r.x=this.x*n-this.y*a,r.y=this.x*a+this.y*n,this.x=r.x,this.y=r.y,this}rotateAround(e,t){let r=Math.sin(e),n=Math.cos(e);this.x-=t.x,this.y-=t.y;let a=this.x*n-this.y*r,i=this.x*r+this.y*n;return this.x=a+t.x,this.y=i+t.y,this}rotateTo(t,r,n=0){this.x+=.001,this.y-=.001;let a=e.subtract(this,r),i=e.subtract(t,r),o=e.angle(i,a);return this.rotateAround(o+n,r),this}rotateAwayFrom(e,t,r){this.rotateAround(r,t);let n=this.distanceSq(e);this.rotateAround(-2*r,t),this.distanceSq(e)<n&&this.rotateAround(2*r,t)}getRotateAwayFromAngle(e,t,r){let n=this.clone();n.rotateAround(r,t);let a=n.distanceSq(e);return n.rotateAround(-2*r,t),n.distanceSq(e)<a?r:-r}getRotateTowardsAngle(e,t,r){let n=this.clone();n.rotateAround(r,t);let a=n.distanceSq(e);return n.rotateAround(-2*r,t),n.distanceSq(e)>a?r:-r}getRotateToAngle(t,r){let n=e.subtract(this,r),a=e.subtract(t,r),i=e.angle(a,n);return Number.isNaN(i)?0:i}isInPolygon(e){let t=!1;for(let r=0,n=e.length-1;r<e.length;n=r++)e[r].y>this.y!=e[n].y>this.y&&this.x<(e[n].x-e[r].x)*(this.y-e[r].y)/(e[n].y-e[r].y)+e[r].x&&(t=!t);return t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSq(){return this.x*this.x+this.y*this.y}normalize(){return this.divide(this.length()),this}normalized(){return e.divideScalar(this,this.length())}whichSide(e,t){return(this.x-e.x)*(t.y-e.y)-(this.y-e.y)*(t.x-e.x)}sameSideAs(e,t,r){let n=this.whichSide(e,t),a=r.whichSide(e,t);return n<0&&a<0||0==n&&0==a||n>0&&a>0}static add(t,r){return new e(t.x+r.x,t.y+r.y)}static subtract(t,r){return new e(t.x-r.x,t.y-r.y)}static multiply(t,r){return new e(t.x*r.x,t.y*r.y)}static multiplyScalar(t,r){return new e(t.x,t.y).multiplyScalar(r)}static midpoint(t,r){return new e((t.x+r.x)/2,(t.y+r.y)/2)}static normals(t,r){let n=e.subtract(r,t);return[new e(-n.y,n.x),new e(n.y,-n.x)]}static units(t,r){let n=e.subtract(r,t);return[new e(-n.y,n.x).normalize(),new e(n.y,-n.x).normalize()]}static divide(t,r){return new e(t.x/r.x,t.y/r.y)}static divideScalar(t,r){return new e(t.x/r,t.y/r)}static dot(e,t){return e.x*t.x+e.y*t.y}static angle(t,r){let n=e.dot(t,r);return Math.acos(n/(t.length()*r.length()))}static threePointangle(t,r,n){let a=e.subtract(r,t),i=e.subtract(n,r),o=t.distance(r),s=r.distance(n);return Math.acos(e.dot(a,i)/(o*s))}static scalarProjection(t,r){let n=r.normalized();return e.dot(t,n)}static averageDirection(t){let r=new e(0,0);for(var n=0;n<t.length;n++){let e=t[n];r.add(e)}return r.normalize()}};function Cr(){if(hr)return gr;hr=1;const e=mr,t=_r,r=yr;Ar();class n{constructor(e,t=0,n=0){this.id=null,this.value=e,this.position=new r(t||0,n||0),this.previousPosition=new r(0,0),this.parentVertexId=null,this.children=Array(),this.spanningTreeChildren=Array(),this.edges=Array(),this.positioned=!1,this.angle=null,this.dir=1,this.neighbourCount=0,this.neighbours=Array(),this.neighbouringElements=Array(),this.forcePositioned=!1}setPosition(e,t){this.position.x=e,this.position.y=t}setPositionFromVector(e){this.position.x=e.x,this.position.y=e.y}addChild(e){this.children.push(e),this.neighbours.push(e),this.neighbourCount++}addRingbondChild(e,t){if(this.children.push(e),this.value.bracket){let r=1;0===this.id&&0===this.value.bracket.hcount&&(r=0),1===this.value.bracket.hcount&&0===t&&(r=2),1===this.value.bracket.hcount&&1===t&&(r=this.neighbours.length<3?2:3),null===this.value.bracket.hcount&&0===t&&(r=1),null===this.value.bracket.hcount&&1===t&&(r=this.neighbours.length<3?1:2),this.neighbours.splice(r,0,e)}else this.neighbours.push(e);this.neighbourCount++}setParentVertexId(e){this.neighbourCount++,this.parentVertexId=e,this.neighbours.push(e)}isTerminal(){return!!this.value.hasAttachedPseudoElements||(null===this.parentVertexId&&this.children.length<2||0===this.children.length)}clone(){let e=new n(this.value,this.position.x,this.position.y);return e.id=this.id,e.previousPosition=new r(this.previousPosition.x,this.previousPosition.y),e.parentVertexId=this.parentVertexId,e.children=t.clone(this.children),e.spanningTreeChildren=t.clone(this.spanningTreeChildren),e.edges=t.clone(this.edges),e.positioned=this.positioned,e.angle=this.angle,e.forcePositioned=this.forcePositioned,e}equals(e){return this.id===e.id}getAngle(t=null,n=!1){let a=null;return a=t?r.subtract(this.position,t):r.subtract(this.position,this.previousPosition),n?e.toDeg(a.angle()):a.angle()}getTextDirection(t,r=!1){let n=this.getDrawnNeighbours(t),a=Array();if(1===t.length)return"right";for(let e=0;e<n.length;e++)a.push(this.getAngle(t[n[e]].position));let i=e.meanAngle(a);if(this.isTerminal()||r)Math.round(100*i)/100==1.57&&(i-=.2),i=Math.round(Math.round(i/Math.PI)*Math.PI);else{let e=Math.PI/2;i=Math.round(Math.round(i/e)*e)}return 2===i?"down":-2===i?"up":0===i||-0===i?"right":3===i||-3===i?"left":"down"}getNeighbours(e=null){if(null===e)return this.neighbours.slice();let t=Array();for(let r=0;r<this.neighbours.length;r++)this.neighbours[r]!==e&&t.push(this.neighbours[r]);return t}getDrawnNeighbours(e){let t=Array();for(let r=0;r<this.neighbours.length;r++)e[this.neighbours[r]].value.isDrawn&&t.push(this.neighbours[r]);return t}getNeighbourCount(){return this.neighbourCount}getSpanningTreeNeighbours(e=null){let t=Array();for(let r=0;r<this.spanningTreeChildren.length;r++)void 0!==e&&e==this.spanningTreeChildren[r]||t.push(this.spanningTreeChildren[r]);return null!=this.parentVertexId&&(void 0!==e&&e==this.parentVertexId||t.push(this.parentVertexId)),t}getNextInRing(e,r,n){let a=this.getNeighbours();for(let i=0;i<a.length;i++)if(t.contains(e[a[i]].value.rings,{value:r})&&a[i]!=n)return a[i];return null}}return gr=n}function Nr(){if(Er)return fr;Er=1,Cr(),Rr();return fr=class{constructor(e,t){this.id=null,this.firstRingId=e.id,this.secondRingId=t.id,this.vertices=new Set;for(var r=0;r<e.members.length;r++){let n=e.members[r];for(let e=0;e<t.members.length;e++){n===t.members[e]&&this.addVertex(n)}}}addVertex(e){this.vertices.add(e)}updateOther(e,t){this.firstRingId===t?this.secondRingId=e:this.firstRingId=e}containsRing(e){return this.firstRingId===e||this.secondRingId===e}isBridge(e){if(this.vertices.size>2)return!0;for(let t of this.vertices)if(e[t].value.rings.length>2)return!0;return!1}static isBridge(e,t,r,n){let a=null;for(let i=0;i<e.length;i++)if(a=e[i],a.firstRingId===r&&a.secondRingId===n||a.firstRingId===n&&a.secondRingId===r)return a.isBridge(t);return!1}static getNeighbours(e,t){let r=[];for(let n=0;n<e.length;n++){let a=e[n];a.firstRingId===t?r.push(a.secondRingId):a.secondRingId===t&&r.push(a.firstRingId)}return r}static getVertices(e,t,r){for(let n=0;n<e.length;n++){let a=e[n];if(a.firstRingId===t&&a.secondRingId===r||a.firstRingId===r&&a.secondRingId===t)return[...a.vertices]}}},fr}function Rr(){if(Sr)return br;Sr=1;const e=_r,t=yr;Cr();const r=Nr();class n{constructor(e){this.id=null,this.members=e,this.edges=[],this.insiders=[],this.neighbours=[],this.positioned=!1,this.center=new t(0,0),this.rings=[],this.isBridged=!1,this.isPartOfBridged=!1,this.isSpiro=!1,this.isFused=!1,this.centralAngle=0,this.canFlip=!0}clone(){let t=new n(this.members);return t.id=this.id,t.insiders=e.clone(this.insiders),t.neighbours=e.clone(this.neighbours),t.positioned=this.positioned,t.center=this.center.clone(),t.rings=e.clone(this.rings),t.isBridged=this.isBridged,t.isPartOfBridged=this.isPartOfBridged,t.isSpiro=this.isSpiro,t.isFused=this.isFused,t.centralAngle=this.centralAngle,t.canFlip=this.canFlip,t}getSize(){return this.members.length}getPolygon(e){let t=[];for(let r=0;r<this.members.length;r++)t.push(e[this.members[r]].position);return t}getAngle(){return Math.PI-this.centralAngle}eachMember(e,t,r,n){let a=r=r||0===r?r:this.members[0],i=0;for(;null!=a&&i<100;){let o=a;t(o),a=e[a].getNextInRing(e,this.id,n),n=o,a==r&&(a=null),i++}}getOrderedNeighbours(e){let t=Array(this.neighbours.length);for(let n=0;n<this.neighbours.length;n++){let a=r.getVertices(e,this.id,this.neighbours[n]);t[n]={n:a.length,neighbour:this.neighbours[n]}}return t.sort(function(e,t){return t.n-e.n}),t}isBenzeneLike(e){let t=this.getDoubleBondCount(e),r=this.members.length;return 3===t&&6===r||2===t&&5===r}getDoubleBondCount(e){let t=0;for(let r=0;r<this.members.length;r++){let n=e[this.members[r]].value;"="!==n.bondType&&"="!==n.branchBond||t++}return t}contains(e){for(let t=0;t<this.members.length;t++)if(this.members[t]==e)return!0;return!1}}return br=n}function Ar(){if(Tr)return vr;Tr=1;const e=_r;Cr(),Rr();class t{constructor(e,t="-"){this.idx=null,this.element=1===e.length?e.toUpperCase():e,this.drawExplicit=!1,this.ringbonds=Array(),this.rings=Array(),this.bondType=t,this.branchBond=null,this.isBridge=!1,this.isBridgeNode=!1,this.originalRings=Array(),this.bridgedRing=null,this.anchoredRings=Array(),this.bracket=null,this.plane=0,this.attachedPseudoElements={},this.hasAttachedPseudoElements=!1,this.isDrawn=!0,this.isConnectedToRing=!1,this.neighbouringElements=Array(),this.isPartOfAromaticRing=e!==this.element,this.bondCount=0,this.chirality="",this.isStereoCenter=!1,this.priority=0,this.mainChain=!1,this.hydrogenDirection="down",this.subtreeDepth=1,this.hasHydrogen=!1,this.class=void 0}addNeighbouringElement(e){this.neighbouringElements.push(e)}attachPseudoElement(e,t,r=0,n=0){null===r&&(r=0),null===n&&(n=0);let a=r+e+n;this.attachedPseudoElements[a]?this.attachedPseudoElements[a].count+=1:this.attachedPseudoElements[a]={element:e,count:1,hydrogenCount:r,previousElement:t,charge:n},this.hasAttachedPseudoElements=!0}getAttachedPseudoElements(){let e={},t=this;return Object.keys(this.attachedPseudoElements).sort().forEach(function(r){e[r]=t.attachedPseudoElements[r]}),e}getAttachedPseudoElementsCount(){return Object.keys(this.attachedPseudoElements).length}isHeteroAtom(){return"C"!==this.element&&"H"!==this.element}addAnchoredRing(t){e.contains(this.anchoredRings,{value:t})||this.anchoredRings.push(t)}getRingbondCount(){return this.ringbonds.length}backupRings(){this.originalRings=Array(this.rings.length);for(let e=0;e<this.rings.length;e++)this.originalRings[e]=this.rings[e]}restoreRings(){this.rings=Array(this.originalRings.length);for(let e=0;e<this.originalRings.length;e++)this.rings[e]=this.originalRings[e]}haveCommonRingbond(e,t){for(let r=0;r<e.ringbonds.length;r++)for(let n=0;n<t.ringbonds.length;n++)if(e.ringbonds[r].id==t.ringbonds[n].id)return!0;return!1}neighbouringElementsEqual(e){if(e.length!==this.neighbouringElements.length)return!1;e.sort(),this.neighbouringElements.sort();for(var t=0;t<this.neighbouringElements.length;t++)if(e[t]!==this.neighbouringElements[t])return!1;return!0}getAtomicNumber(){return t.atomicNumbers[this.element]}getMaxBonds(){return t.maxBonds[this.element]}static get maxBonds(){return{H:1,C:4,N:3,O:2,P:3,S:2,B:3,F:1,I:1,Cl:1,Br:1}}static get atomicNumbers(){return{H:1,He:2,Li:3,Be:4,B:5,b:5,C:6,c:6,N:7,n:7,O:8,o:8,F:9,Ne:10,Na:11,Mg:12,Al:13,Si:14,P:15,p:15,S:16,s:16,Cl:17,Ar:18,K:19,Ca:20,Sc:21,Ti:22,V:23,Cr:24,Mn:25,Fe:26,Co:27,Ni:28,Cu:29,Zn:30,Ga:31,Ge:32,As:33,Se:34,Br:35,Kr:36,Rb:37,Sr:38,Y:39,Zr:40,Nb:41,Mo:42,Tc:43,Ru:44,Rh:45,Pd:46,Ag:47,Cd:48,In:49,Sn:50,Sb:51,Te:52,I:53,Xe:54,Cs:55,Ba:56,La:57,Ce:58,Pr:59,Nd:60,Pm:61,Sm:62,Eu:63,Gd:64,Tb:65,Dy:66,Ho:67,Er:68,Tm:69,Yb:70,Lu:71,Hf:72,Ta:73,W:74,Re:75,Os:76,Ir:77,Pt:78,Au:79,Hg:80,Tl:81,Pb:82,Bi:83,Po:84,At:85,Rn:86,Fr:87,Ra:88,Ac:89,Th:90,Pa:91,U:92,Np:93,Pu:94,Am:95,Cm:96,Bk:97,Cf:98,Es:99,Fm:100,Md:101,No:102,Lr:103,Rf:104,Db:105,Sg:106,Bh:107,Hs:108,Mt:109,Ds:110,Rg:111,Cn:112,Uut:113,Uuq:114,Uup:115,Uuh:116,Uus:117,Uuo:118}}static get mass(){return{H:1,He:2,Li:3,Be:4,B:5,b:5,C:6,c:6,N:7,n:7,O:8,o:8,F:9,Ne:10,Na:11,Mg:12,Al:13,Si:14,P:15,p:15,S:16,s:16,Cl:17,Ar:18,K:19,Ca:20,Sc:21,Ti:22,V:23,Cr:24,Mn:25,Fe:26,Co:27,Ni:28,Cu:29,Zn:30,Ga:31,Ge:32,As:33,Se:34,Br:35,Kr:36,Rb:37,Sr:38,Y:39,Zr:40,Nb:41,Mo:42,Tc:43,Ru:44,Rh:45,Pd:46,Ag:47,Cd:48,In:49,Sn:50,Sb:51,Te:52,I:53,Xe:54,Cs:55,Ba:56,La:57,Ce:58,Pr:59,Nd:60,Pm:61,Sm:62,Eu:63,Gd:64,Tb:65,Dy:66,Ho:67,Er:68,Tm:69,Yb:70,Lu:71,Hf:72,Ta:73,W:74,Re:75,Os:76,Ir:77,Pt:78,Au:79,Hg:80,Tl:81,Pb:82,Bi:83,Po:84,At:85,Rn:86,Fr:87,Ra:88,Ac:89,Th:90,Pa:91,U:92,Np:93,Pu:94,Am:95,Cm:96,Bk:97,Cf:98,Es:99,Fm:100,Md:101,No:102,Lr:103,Rf:104,Db:105,Sg:106,Bh:107,Hs:108,Mt:109,Ds:110,Rg:111,Cn:112,Uut:113,Uuq:114,Uup:115,Uuh:116,Uus:117,Uuo:118}}}return vr=t}const Or=yr;var Ir=class e{constructor(e=new Or(0,0),t=new Or(0,0),r=null,n=null,a=!1,i=!1){this.from=e,this.to=t,this.elementFrom=r,this.elementTo=n,this.chiralFrom=a,this.chiralTo=i}clone(){return new e(this.from.clone(),this.to.clone(),this.elementFrom,this.elementTo)}getLength(){return Math.sqrt(Math.pow(this.to.x-this.from.x,2)+Math.pow(this.to.y-this.from.y,2))}getAngle(){return Or.subtract(this.getRightVector(),this.getLeftVector()).angle()}getRightVector(){return this.from.x<this.to.x?this.to:this.from}getLeftVector(){return this.from.x<this.to.x?this.from:this.to}getRightElement(){return this.from.x<this.to.x?this.elementTo:this.elementFrom}getLeftElement(){return this.from.x<this.to.x?this.elementFrom:this.elementTo}getRightChiral(){return this.from.x<this.to.x?this.chiralTo:this.chiralFrom}getLeftChiral(){return this.from.x<this.to.x?this.chiralFrom:this.chiralTo}setRightVector(e,t){return this.from.x<this.to.x?(this.to.x=e,this.to.y=t):(this.from.x=e,this.from.y=t),this}setLeftVector(e,t){return this.from.x<this.to.x?(this.from.x=e,this.from.y=t):(this.to.x=e,this.to.y=t),this}rotateToXAxis(){let e=this.getLeftVector();return this.setRightVector(e.x+this.getLength(),e.y),this}rotate(e){let t=this.getLeftVector(),r=this.getRightVector(),n=Math.sin(e),a=Math.cos(e),i=a*(r.x-t.x)-n*(r.y-t.y)+t.x,o=n*(r.x-t.x)-a*(r.y-t.y)+t.y;return this.setRightVector(i,o),this}shortenFrom(e){let t=Or.subtract(this.to,this.from);return t.normalize(),t.multiplyScalar(e),this.from.add(t),this}shortenTo(e){let t=Or.subtract(this.from,this.to);return t.normalize(),t.multiplyScalar(e),this.to.add(t),this}shortenRight(e){return this.from.x<this.to.x?this.shortenTo(e):this.shortenFrom(e),this}shortenLeft(e){return this.from.x<this.to.x?this.shortenFrom(e):this.shortenTo(e),this}shorten(e){let t=Or.subtract(this.from,this.to);return t.normalize(),t.multiplyScalar(e/2),this.to.add(t),this.from.subtract(t),this}};var xr=class e{constructor(e,t,r=1){this.id=null,this.sourceId=e,this.targetId=t,this.weight=r,this.bondType="-",this.isPartOfAromaticRing=!1,this.center=!1,this.wedge=""}setBondType(t){this.bondType=t,this.weight=e.bonds[t]}static get bonds(){return{"-":1,"/":1,"\\":1,"=":2,"#":3,$:4}}};var wr={getChargeText:function(e){return 1===e?"+":2===e?"2+":-1===e?"-":-2===e?"2-":""}};const Dr=mr,Mr=yr;Cr(),Rr();const{getChargeText:kr}=wr;var Lr=class{constructor(e,t,r){this.canvas="string"==typeof e||e instanceof String?document.getElementById(e):e,this.ctx=this.canvas.getContext("2d"),this.themeManager=t,this.opts=r,this.drawingWidth=0,this.drawingHeight=0,this.offsetX=0,this.offsetY=0,this.fontLarge=this.opts.fontSizeLarge+"pt Helvetica, Arial, sans-serif",this.fontSmall=this.opts.fontSizeSmall+"pt Helvetica, Arial, sans-serif",this.updateSize(this.opts.width,this.opts.height),this.ctx.font=this.fontLarge,this.hydrogenWidth=this.ctx.measureText("H").width,this.halfHydrogenWidth=this.hydrogenWidth/2,this.halfBondThickness=this.opts.bondThickness/2}updateSize(e,t){this.devicePixelRatio=window.devicePixelRatio||1,this.backingStoreRatio=this.ctx.webkitBackingStorePixelRatio||this.ctx.mozBackingStorePixelRatio||this.ctx.msBackingStorePixelRatio||this.ctx.oBackingStorePixelRatio||this.ctx.backingStorePixelRatio||1,this.ratio=this.devicePixelRatio/this.backingStoreRatio,1!==this.ratio?(this.canvas.width=e*this.ratio,this.canvas.height=t*this.ratio,this.canvas.style.width=e+"px",this.canvas.style.height=t+"px",this.ctx.setTransform(this.ratio,0,0,this.ratio,0,0)):(this.canvas.width=e*this.ratio,this.canvas.height=t*this.ratio)}setTheme(e){this.colors=e}scale(e){let t=-Number.MAX_VALUE,r=-Number.MAX_VALUE,n=Number.MAX_VALUE,a=Number.MAX_VALUE;for(var i=0;i<e.length;i++){if(!e[i].value.isDrawn)continue;let o=e[i].position;t<o.x&&(t=o.x),r<o.y&&(r=o.y),n>o.x&&(n=o.x),a>o.y&&(a=o.y)}var o=this.opts.padding;t+=o,r+=o,n-=o,a-=o,this.drawingWidth=t-n,this.drawingHeight=r-a;var s=this.canvas.offsetWidth/this.drawingWidth,l=this.canvas.offsetHeight/this.drawingHeight,c=s<l?s:l;this.ctx.scale(c,c),this.offsetX=-n,this.offsetY=-a,s<l?this.offsetY+=this.canvas.offsetHeight/(2*c)-this.drawingHeight/2:this.offsetX+=this.canvas.offsetWidth/(2*c)-this.drawingWidth/2}reset(){this.ctx.setTransform(1,0,0,1,0,0)}getColor(e){return(e=e.toUpperCase())in this.colors?this.colors[e]:this.colors.C}drawCircle(e,t,r,n,a=!0,i=!1,o=""){let s=this.ctx,l=this.offsetX,c=this.offsetY;s.save(),s.lineWidth=1.5,s.beginPath(),s.arc(e+l,t+c,r,0,Dr.twoPI,!0),s.closePath(),i?(a?(s.fillStyle="#f00",s.fill()):(s.strokeStyle="#f00",s.stroke()),this.drawDebugText(e,t,o)):a?(s.fillStyle=n,s.fill()):(s.strokeStyle=n,s.stroke()),s.restore()}drawLine(e,t=!1,r=1){let n=this.ctx,a=this.offsetX,i=this.offsetY,o=e.clone().shorten(4),s=o.getLeftVector().clone(),l=o.getRightVector().clone();s.x+=a,s.y+=i,l.x+=a,l.y+=i,t||(n.save(),n.globalCompositeOperation="destination-out",n.beginPath(),n.moveTo(s.x,s.y),n.lineTo(l.x,l.y),n.lineCap="round",n.lineWidth=this.opts.bondThickness+1.2,n.strokeStyle=this.themeManager.getColor("BACKGROUND"),n.stroke(),n.globalCompositeOperation="source-over",n.restore()),s=e.getLeftVector().clone(),l=e.getRightVector().clone(),s.x+=a,s.y+=i,l.x+=a,l.y+=i,n.save(),n.beginPath(),n.moveTo(s.x,s.y),n.lineTo(l.x,l.y),n.lineCap="round",n.lineWidth=this.opts.bondThickness;let c=this.ctx.createLinearGradient(s.x,s.y,l.x,l.y);c.addColorStop(.4,this.themeManager.getColor(e.getLeftElement())||this.themeManager.getColor("C")),c.addColorStop(.6,this.themeManager.getColor(e.getRightElement())||this.themeManager.getColor("C")),t&&(n.setLineDash([1,1.5]),n.lineWidth=this.opts.bondThickness/1.5),r<1&&(n.globalAlpha=r),n.strokeStyle=c,n.stroke(),n.restore()}drawWedge(e,t=1){if(isNaN(e.from.x)||isNaN(e.from.y)||isNaN(e.to.x)||isNaN(e.to.y))return;let r=this.ctx,n=this.offsetX,a=this.offsetY,i=e.clone().shorten(5),o=i.getLeftVector().clone(),s=i.getRightVector().clone();o.x+=n,o.y+=a,s.x+=n,s.y+=a,o=e.getLeftVector().clone(),s=e.getRightVector().clone(),o.x+=n,o.y+=a,s.x+=n,s.y+=a,r.save();let l=Mr.normals(o,s);l[0].normalize(),l[1].normalize();let c=o,d=s;e.getRightChiral()&&(c=s,d=o);let u=Mr.add(c,Mr.multiplyScalar(l[0],this.halfBondThickness)),p=Mr.add(d,Mr.multiplyScalar(l[0],1.5+this.halfBondThickness)),_=Mr.add(d,Mr.multiplyScalar(l[1],1.5+this.halfBondThickness)),m=Mr.add(c,Mr.multiplyScalar(l[1],this.halfBondThickness));r.beginPath(),r.moveTo(u.x,u.y),r.lineTo(p.x,p.y),r.lineTo(_.x,_.y),r.lineTo(m.x,m.y);let g=this.ctx.createRadialGradient(s.x,s.y,this.opts.bondLength,s.x,s.y,0);g.addColorStop(.4,this.themeManager.getColor(e.getLeftElement())||this.themeManager.getColor("C")),g.addColorStop(.6,this.themeManager.getColor(e.getRightElement())||this.themeManager.getColor("C")),r.fillStyle=g,r.fill(),r.restore()}drawDashedWedge(e){if(isNaN(e.from.x)||isNaN(e.from.y)||isNaN(e.to.x)||isNaN(e.to.y))return;let t=this.ctx,r=this.offsetX,n=this.offsetY,a=e.getLeftVector().clone(),i=e.getRightVector().clone();a.x+=r,a.y+=n,i.x+=r,i.y+=n,t.save();let o=Mr.normals(a,i);o[0].normalize(),o[1].normalize();let s,l,c,d,u=e.getRightChiral(),p=e.clone();u?(s=i,l=a,p.shortenRight(1),c=p.getRightVector().clone(),d=p.getLeftVector().clone()):(s=a,l=i,p.shortenLeft(1),c=p.getLeftVector().clone(),d=p.getRightVector().clone()),c.x+=r,c.y+=n,d.x+=r,d.y+=n;let _=Mr.subtract(l,s).normalize();t.strokeStyle=this.themeManager.getColor("C"),t.lineCap="round",t.lineWidth=this.opts.bondThickness,t.beginPath();let m=e.getLength(),g=1.25/(m/(3*this.opts.bondThickness)),h=!1;for(var f=0;f<1;f+=g){let r=Mr.multiplyScalar(_,f*m),n=Mr.add(s,r),a=1.5*f,i=Mr.multiplyScalar(o[0],a);!h&&f>.5&&(t.stroke(),t.beginPath(),t.strokeStyle=this.themeManager.getColor(e.getRightElement())||this.themeManager.getColor("C"),h=!0),n.subtract(i),t.moveTo(n.x,n.y),n.add(Mr.multiplyScalar(i,2)),t.lineTo(n.x,n.y)}t.stroke(),t.restore()}drawDebugText(e,t,r){let n=this.ctx;n.save(),n.font="5px Droid Sans, sans-serif",n.textAlign="start",n.textBaseline="top",n.fillStyle="#ff0000",n.fillText(r,e+this.offsetX,t+this.offsetY),n.restore()}drawBall(e,t,r){let n=this.ctx;n.save(),n.beginPath(),n.arc(e+this.offsetX,t+this.offsetY,this.opts.bondLength/4.5,0,Dr.twoPI,!1),n.fillStyle=this.themeManager.getColor(r),n.fill(),n.restore()}drawPoint(e,t,r){let n=this.ctx,a=this.offsetX,i=this.offsetY;n.save(),n.globalCompositeOperation="destination-out",n.beginPath(),n.arc(e+a,t+i,1.5,0,Dr.twoPI,!0),n.closePath(),n.fill(),n.globalCompositeOperation="source-over",n.beginPath(),n.arc(e+this.offsetX,t+this.offsetY,.75,0,Dr.twoPI,!1),n.fillStyle=this.themeManager.getColor(r),n.fill(),n.restore()}drawText(e,t,r,n,a,i,o,s,l,c={}){let d=this.ctx,u=this.offsetX,p=this.offsetY;d.save(),d.textAlign="start",d.textBaseline="alphabetic";let _="",m=0;o&&(_=kr(o),d.font=this.fontSmall,m=d.measureText(_).width);let g="0",h=0;s>0&&(g=s.toString(),d.font=this.fontSmall,h=d.measureText(g).width),1===o&&"N"===r&&c.hasOwnProperty("0O")&&c.hasOwnProperty("0O-1")&&(c={"0O":{element:"O",count:2,hydrogenCount:0,previousElement:"C",charge:""}},o=0),d.font=this.fontLarge,d.fillStyle=this.themeManager.getColor("BACKGROUND");let f=d.measureText(r);f.totalWidth=f.width+m,f.height=parseInt(this.fontLarge,10);let E=f.width>this.opts.fontSizeLarge?f.width:this.opts.fontSizeLarge;E/=1.5,d.globalCompositeOperation="destination-out",d.beginPath(),d.arc(e+u,t+p,E,0,Dr.twoPI,!0),d.closePath(),d.fill(),d.globalCompositeOperation="source-over";let b=-f.width/2,S=-f.width/2;d.fillStyle=this.themeManager.getColor(r),d.fillText(r,e+u+b,t+this.opts.halfFontSizeLarge+p),b+=f.width,o&&(d.font=this.fontSmall,d.fillText(_,e+u+b,t-this.opts.fifthFontSizeSmall+p),b+=m),s>0&&(d.font=this.fontSmall,d.fillText(g,e+u+S-h,t-this.opts.fifthFontSizeSmall+p),S-=h),d.font=this.fontLarge;let v=0,T=0;if(1===n){let r=e+u,n=t+p+this.opts.halfFontSizeLarge;v=this.hydrogenWidth,S-=v,"left"===a?r+=S:"right"===a||"up"===a&&i||"down"===a&&i?r+=b:"up"!==a||i?"down"!==a||i||(n+=this.opts.fontSizeLarge+this.opts.quarterFontSizeLarge,r-=this.halfHydrogenWidth):(n-=this.opts.fontSizeLarge+this.opts.quarterFontSizeLarge,r-=this.halfHydrogenWidth),d.fillText("H",r,n),b+=v}else if(n>1){let r=e+u,o=t+p+this.opts.halfFontSizeLarge;v=this.hydrogenWidth,d.font=this.fontSmall,T=d.measureText(n).width,S-=v+T,"left"===a?r+=S:"right"===a||"up"===a&&i||"down"===a&&i?r+=b:"up"!==a||i?"down"!==a||i||(o+=this.opts.fontSizeLarge+this.opts.quarterFontSizeLarge,r-=this.halfHydrogenWidth):(o-=this.opts.fontSizeLarge+this.opts.quarterFontSizeLarge,r-=this.halfHydrogenWidth),d.font=this.fontLarge,d.fillText("H",r,o),d.font=this.fontSmall,d.fillText(n,r+this.halfHydrogenWidth+T,o+this.opts.fifthFontSizeSmall),b+=v+this.halfHydrogenWidth+T}for(let r in c){if(!c.hasOwnProperty(r))continue;let n=0,i=0,o=c[r].element,s=c[r].count,l=c[r].hydrogenCount,_=c[r].charge;d.font=this.fontLarge,s>1&&l>0&&(n=d.measureText("(").width,i=d.measureText(")").width);let m=d.measureText(o).width,g=0,h="",f=0;v=0,l>0&&(v=this.hydrogenWidth),d.font=this.fontSmall,s>1&&(g=d.measureText(s).width),0!==_&&(h=kr(_),f=d.measureText(h).width),T=0,l>1&&(T=d.measureText(l).width),d.font=this.fontLarge;let E=e+u,y=t+p+this.opts.halfFontSizeLarge;d.fillStyle=this.themeManager.getColor(o),s>0&&(S-=g),s>1&&l>0&&("left"===a?(S-=i,d.fillText(")",E+S,y)):(d.fillText("(",E+b,y),b+=n)),"left"===a?(S-=m,d.fillText(o,E+S,y)):(d.fillText(o,E+b,y),b+=m),l>0&&("left"===a?(S-=v+T,d.fillText("H",E+S,y),l>1&&(d.font=this.fontSmall,d.fillText(l,E+S+v,y+this.opts.fifthFontSizeSmall))):(d.fillText("H",E+b,y),b+=v,l>1&&(d.font=this.fontSmall,d.fillText(l,E+b,y+this.opts.fifthFontSizeSmall),b+=T))),d.font=this.fontLarge,s>1&&l>0&&("left"===a?(S-=n,d.fillText("(",E+S,y)):(d.fillText(")",E+b,y),b+=i)),d.font=this.fontSmall,s>1&&("left"===a?d.fillText(s,E+S+n+i+v+T+m,y+this.opts.fifthFontSizeSmall):(d.fillText(s,E+b,y+this.opts.fifthFontSizeSmall),b+=g)),0!==_&&("left"===a?d.fillText(h,E+S+n+i+v+T+m,t-this.opts.fifthFontSizeSmall+p):(d.fillText(h,E+b,t-this.opts.fifthFontSizeSmall+p),b+=f))}d.restore()}getChargeText(e){return 1===e?"+":2===e?"2+":-1===e?"-":-2===e?"2-":""}drawDebugPoint(e,t,r="",n="#f00"){this.drawCircle(e,t,2,n,!0,!0,r)}drawAromaticityRing(e){let t=this.ctx,r=Dr.apothemFromSideLength(this.opts.bondLength,e.getSize());t.save(),t.strokeStyle=this.themeManager.getColor("C"),t.lineWidth=this.opts.bondThickness,t.beginPath(),t.arc(e.center.x+this.offsetX,e.center.y+this.offsetY,r-this.opts.bondSpacing,0,2*Math.PI,!0),t.closePath(),t.stroke(),t.restore()}clear(){this.ctx.clearRect(0,0,this.canvas.offsetWidth,this.canvas.offsetHeight)}};const Pr=mr,Fr=Cr(),Br=xr;Rr();const Ur=Ar();var Gr=class e{constructor(e,t=!1){this.vertices=Array(),this.edges=Array(),this.atomIdxToVertexId=Array(),this.vertexIdsToEdgeId={},this.isomeric=t,this._atomIdx=0,this._time=0,this._init(e)}_init(e,t=0,r=null,n=!1){const a=e.atom.element?e.atom.element:e.atom;let i=new Ur(a,e.bond);("H"!==a||!e.hasNext&&null===r)&&(i.idx=this._atomIdx,this._atomIdx++),i.branchBond=e.branchBond,i.ringbonds=e.ringbonds,i.bracket=e.atom.element?e.atom:null,i.class=e.atom.class;let o=new Fr(i),s=this.vertices[r];if(this.addVertex(o),null!==i.idx&&this.atomIdxToVertexId.push(o.id),null!==r){o.setParentVertexId(r),o.value.addNeighbouringElement(s.value.element),s.addChild(o.id),s.value.addNeighbouringElement(i.element),s.spanningTreeChildren.push(o.id);let e=new Br(r,o.id,1);n?(e.setBondType(o.value.branchBond||"-"),o.id,e.setBondType(o.value.branchBond||"-"),o.id):(e.setBondType(s.value.bondType||"-"),s.id),this.addEdge(e)}let l=e.ringbondCount+1;i.bracket&&(l+=i.bracket.hcount);let c=0;if(i.bracket&&i.bracket.chirality){i.isStereoCenter=!0,c=i.bracket.hcount;for(var d=0;d<c;d++)this._init({atom:"H",isBracket:"false",branches:Array(),branchCount:0,ringbonds:Array(),ringbondCount:!1,next:null,hasNext:!1,bond:"-"},d,o.id,!0)}for(d=0;d<e.branchCount;d++)this._init(e.branches[d],d+l,o.id,!0);e.hasNext&&this._init(e.next,e.branchCount+l,o.id)}clear(){this.vertices=Array(),this.edges=Array(),this.vertexIdsToEdgeId={}}addVertex(e){return e.id=this.vertices.length,this.vertices.push(e),e.id}addEdge(e){let t=this.vertices[e.sourceId],r=this.vertices[e.targetId];return e.id=this.edges.length,this.edges.push(e),this.vertexIdsToEdgeId[e.sourceId+"_"+e.targetId]=e.id,this.vertexIdsToEdgeId[e.targetId+"_"+e.sourceId]=e.id,e.isPartOfAromaticRing=t.value.isPartOfAromaticRing&&r.value.isPartOfAromaticRing,t.value.bondCount+=e.weight,r.value.bondCount+=e.weight,t.edges.push(e.id),r.edges.push(e.id),e.id}getEdge(e,t){let r=this.vertexIdsToEdgeId[e+"_"+t];return void 0===r?null:this.edges[r]}getEdges(e){let t=Array(),r=this.vertices[e];for(var n=0;n<r.neighbours.length;n++)t.push(this.vertexIdsToEdgeId[e+"_"+r.neighbours[n]]);return t}hasEdge(e,t){return void 0!==this.vertexIdsToEdgeId[e+"_"+t]}getVertexList(){let e=[this.vertices.length];for(var t=0;t<this.vertices.length;t++)e[t]=this.vertices[t].id;return e}getEdgeList(){let e=Array(this.edges.length);for(var t=0;t<this.edges.length;t++)e[t]=[this.edges[t].sourceId,this.edges[t].targetId];return e}getAdjacencyMatrix(){let e=this.vertices.length,t=Array(e);for(var r=0;r<e;r++)t[r]=new Array(e),t[r].fill(0);for(r=0;r<this.edges.length;r++){let e=this.edges[r];t[e.sourceId][e.targetId]=1,t[e.targetId][e.sourceId]=1}return t}getComponentsAdjacencyMatrix(){let e=this.vertices.length,t=Array(e),r=this.getBridges();for(var n=0;n<e;n++)t[n]=new Array(e),t[n].fill(0);for(n=0;n<this.edges.length;n++){let e=this.edges[n];t[e.sourceId][e.targetId]=1,t[e.targetId][e.sourceId]=1}for(n=0;n<r.length;n++)t[r[n][0]][r[n][1]]=0,t[r[n][1]][r[n][0]]=0;return t}getSubgraphAdjacencyMatrix(e){let t=e.length,r=Array(t);for(var n=0;n<t;n++){r[n]=new Array(t),r[n].fill(0);for(var a=0;a<t;a++)n!==a&&this.hasEdge(e[n],e[a])&&(r[n][a]=1)}return r}getDistanceMatrix(){let e=this.vertices.length,t=this.getAdjacencyMatrix(),r=Array(e);for(var n=0;n<e;n++)r[n]=Array(e),r[n].fill(1/0);for(n=0;n<e;n++)for(var a=0;a<e;a++)1===t[n][a]&&(r[n][a]=1);for(var i=0;i<e;i++)for(n=0;n<e;n++)for(a=0;a<e;a++)r[n][a]>r[n][i]+r[i][a]&&(r[n][a]=r[n][i]+r[i][a]);return r}getSubgraphDistanceMatrix(e){let t=e.length,r=this.getSubgraphAdjacencyMatrix(e),n=Array(t);for(var a=0;a<t;a++)n[a]=Array(t),n[a].fill(1/0);for(a=0;a<t;a++)for(var i=0;i<t;i++)1===r[a][i]&&(n[a][i]=1);for(var o=0;o<t;o++)for(a=0;a<t;a++)for(i=0;i<t;i++)n[a][i]>n[a][o]+n[o][i]&&(n[a][i]=n[a][o]+n[o][i]);return n}getAdjacencyList(){let e=this.vertices.length,t=Array(e);for(var r=0;r<e;r++){t[r]=[];for(var n=0;n<e;n++)r!==n&&this.hasEdge(this.vertices[r].id,this.vertices[n].id)&&t[r].push(n)}return t}getSubgraphAdjacencyList(e){let t=e.length,r=Array(t);for(var n=0;n<t;n++){r[n]=Array();for(var a=0;a<t;a++)n!==a&&this.hasEdge(e[n],e[a])&&r[n].push(a)}return r}getBridges(){let e=this.vertices.length,t=new Array(e),r=new Array(e),n=new Array(e),a=new Array(e),i=this.getAdjacencyList(),o=Array();t.fill(!1),a.fill(null),this._time=0;for(var s=0;s<e;s++)t[s]||this._bridgeDfs(s,t,r,n,a,i,o);return o}traverseBF(e,t){let r=this.vertices.length,n=new Array(r);n.fill(!1);for(var a=[e];a.length>0;){let e=a.shift(),r=this.vertices[e];t(r);for(var i=0;i<r.neighbours.length;i++){let e=r.neighbours[i];n[e]||(n[e]=!0,a.push(e))}}}getTreeDepth(e,t){if(null===e||null===t)return 0;let r=this.vertices[e].getSpanningTreeNeighbours(t),n=0;for(var a=0;a<r.length;a++){let t=r[a],i=this.getTreeDepth(t,e);i>n&&(n=i)}return n+1}traverseTree(e,t,r,n=999999,a=!1,i=1,o=null){if(null===o&&(o=new Uint8Array(this.vertices.length)),i>n+1||1===o[e])return;o[e]=1;let s=this.vertices[e],l=s.getNeighbours(t);(!a||i>1)&&r(s);for(var c=0;c<l.length;c++)this.traverseTree(l[c],e,r,n,a,i+1,o)}kkLayout(e,t,r,n,a,i=.1,o=.1,s=2e3,l=50,c=1e9){let d=a;for(var u=e.length;u--;){var p=this.vertices[e[u]].neighbours.length}let _=this.getSubgraphDistanceMatrix(e),m=e.length,g=Pr.polyCircumradius(500,m),h=Pr.centralAngle(m),f=0,E=new Float32Array(m),b=new Float32Array(m),S=Array(m);for(u=m;u--;){let r=this.vertices[e[u]];r.positioned?(E[u]=r.position.x,b[u]=r.position.y):(E[u]=t.x+Math.cos(f)*g,b[u]=t.y+Math.sin(f)*g),S[u]=r.positioned,f+=h}let v=Array(m);for(u=m;u--;){v[u]=new Array(m);for(p=m;p--;)v[u][p]=a*_[u][p]}let T=Array(m);for(u=m;u--;){T[u]=Array(m);for(p=m;p--;)T[u][p]=d*Math.pow(_[u][p],-2)}let y,C,N,R,A,O,I,x=Array(m),w=new Float32Array(m),D=new Float32Array(m);for(u=m;u--;)x[u]=Array(m);for(u=m;u--;){y=E[u],C=b[u],N=0,R=0;let e=m;for(;e--;)u!==e&&(A=E[e],O=b[e],I=1/Math.sqrt((y-A)*(y-A)+(C-O)*(C-O)),x[u][e]=[T[u][e]*(y-A-v[u][e]*(y-A)*I),T[u][e]*(C-O-v[u][e]*(C-O)*I)],x[e][u]=x[u][e],N+=x[u][e][0],R+=x[u][e][1]);w[u]=N,D[u]=R}let M=function(e){return[w[e]*w[e]+D[e]*D[e],w[e],D[e]]},k=function(){let e=0,t=0,r=0,n=0;for(u=m;u--;){let[a,i,o]=M(u);a>e&&!1===S[u]&&(e=a,t=u,r=i,n=o)}return[t,e,r,n]},L=function(e,t,r){let n=0,a=0,i=0,o=E[e],s=b[e],l=v[e],c=T[e];for(u=m;u--;){if(u===e)continue;let t=E[u],r=b[u],d=l[u],p=c[u],_=(o-t)*(o-t),m=1/Math.pow(_+(s-r)*(s-r),1.5);n+=p*(1-d*(s-r)*(s-r)*m),a+=p*(1-d*_*m),i+=p*(d*(o-t)*(s-r)*m)}0===n&&(n=.1),0===a&&(a=.1),0===i&&(i=.1);let d=t/n+r/i;d/=i/n-a/i;let p=-(i*d+t)/n;E[e]+=p,b[e]+=d;let _,g,h,f,S,y=x[e];for(t=0,r=0,o=E[e],s=b[e],u=m;u--;)e!==u&&(_=E[u],g=b[u],h=y[u][0],f=y[u][1],S=1/Math.sqrt((o-_)*(o-_)+(s-g)*(s-g)),p=c[u]*(o-_-l[u]*(o-_)*S),d=c[u]*(s-g-l[u]*(s-g)*S),y[u]=[p,d],t+=p,r+=d,w[u]+=p-h,D[u]+=d-f);w[e]=t,D[e]=r},P=0,F=0,B=0,U=0,G=0,z=0;for(;c>i&&s>G;)for(G++,[P,c,F,B]=k(),U=c,z=0;U>o&&l>z;)z++,L(P,F,B),[U,F,B]=M(P);for(u=m;u--;){let t=e[u],r=this.vertices[t];r.position.x=E[u],r.position.y=b[u],r.positioned=!0,r.forcePositioned=!0}}_bridgeDfs(e,t,r,n,a,i,o){t[e]=!0,r[e]=n[e]=++this._time;for(var s=0;s<i[e].length;s++){let l=i[e][s];t[l]?l!==a[e]&&(n[e]=Math.min(n[e],r[l])):(a[l]=e,this._bridgeDfs(l,t,r,n,a,i,o),n[e]=Math.min(n[e],n[l]),n[l]>r[e]&&o.push([e,l]))}}static getConnectedComponents(t){let r=t.length,n=new Array(r),a=new Array;n.fill(!1);for(var i=0;i<r;i++)if(!n[i]){let r=Array();n[i]=!0,r.push(i),e._ccGetDfs(i,n,t,r),r.length>1&&a.push(r)}return a}static getConnectedComponentCount(t){let r=t.length,n=new Array(r),a=0;n.fill(!1);for(var i=0;i<r;i++)n[i]||(n[i]=!0,a++,e._ccCountDfs(i,n,t));return a}static _ccCountDfs(t,r,n){for(var a=0;a<n[t].length;a++){n[t][a]&&!r[a]&&t!==a&&(r[a]=!0,e._ccCountDfs(a,r,n))}}static _ccGetDfs(t,r,n,a){for(var i=0;i<n[t].length;i++){n[t][i]&&!r[i]&&t!==i&&(r[i]=!0,a.push(i),e._ccGetDfs(i,r,n,a))}}};const zr=Gr;var Yr=class e{static getRings(t,r=!1){let n=t.getComponentsAdjacencyMatrix();if(0===n.length)return null;let a=zr.getConnectedComponents(n),i=Array();for(var o=0;o<a.length;o++){let n=a[o],c=t.getSubgraphAdjacencyMatrix([...n]),d=new Uint16Array(c.length),u=new Uint16Array(c.length);for(var s=0;s<c.length;s++){u[s]=0,d[s]=0;for(var l=0;l<c[s].length;l++)d[s]+=c[s][l]}let p=0;for(s=0;s<c.length;s++)for(l=s+1;l<c.length;l++)p+=c[s][l];let _=p-c.length+1,m=!0;for(s=0;s<d.length;s++)3!==d[s]&&(m=!1);if(m&&(_=2+p-c.length),1===_){i.push([...n]);continue}r&&(_=999);let{d:g,pe:h,pe_prime:f}=e.getPathIncludedDistanceMatrices(c),E=e.getRingCandidates(g,h,f),b=e.getSSSR(E,g,c,h,f,d,u,_);for(s=0;s<b.length;s++){let e=Array(b[s].size),t=0;for(let r of b[s])e[t++]=n[r];i.push(e)}}return i}static matrixToString(e){let t="";for(var r=0;r<e.length;r++){for(var n=0;n<e[r].length;n++)t+=e[r][n]+" ";t+="\n"}return t}static getPathIncludedDistanceMatrices(e){let t=e.length,r=Array(t),n=Array(t),a=Array(t);for(var i=0,o=0,s=0,l=t;l--;){r[l]=Array(t),n[l]=Array(t),a[l]=Array(t);for(var c=t;c--;)r[l][c]=l===c||1===e[l][c]?e[l][c]:Number.POSITIVE_INFINITY,1===r[l][c]?n[l][c]=[[[l,c]]]:n[l][c]=Array(),a[l][c]=Array()}for(var d=t;d--;)for(l=t;l--;)for(c=t;c--;){const e=r[l][c],t=r[l][d]+r[d][c];if(e>t){if(e===t+1)for(a[l][c]=[n[l][c].length],i=n[l][c].length;i--;)for(a[l][c][i]=[n[l][c][i].length],o=n[l][c][i].length;o--;)for(a[l][c][i][o]=[n[l][c][i][o].length],s=n[l][c][i][o].length;s--;)a[l][c][i][o][s]=[n[l][c][i][o][0],n[l][c][i][o][1]];else a[l][c]=Array();for(r[l][c]=t,n[l][c]=[[]],i=n[l][d][0].length;i--;)n[l][c][0].push(n[l][d][0][i]);for(i=n[d][c][0].length;i--;)n[l][c][0].push(n[d][c][0][i])}else if(e===t){if(n[l][d].length&&n[d][c].length)if(n[l][c].length){let e=Array();for(i=n[l][d][0].length;i--;)e.push(n[l][d][0][i]);for(i=n[d][c][0].length;i--;)e.push(n[d][c][0][i]);n[l][c].push(e)}else{let e=Array();for(i=n[l][d][0].length;i--;)e.push(n[l][d][0][i]);for(i=n[d][c][0].length;i--;)e.push(n[d][c][0][i]);n[l][c][0]=e}}else if(e===t-1){if(a[l][c].length){let e=Array();for(i=n[l][d][0].length;i--;)e.push(n[l][d][0][i]);for(i=n[d][c][0].length;i--;)e.push(n[d][c][0][i]);a[l][c].push(e)}else{let e=Array();for(i=n[l][d][0].length;i--;)e.push(n[l][d][0][i]);for(i=n[d][c][0].length;i--;)e.push(n[d][c][0][i]);a[l][c][0]=e}}}return{d:r,pe:n,pe_prime:a}}static getRingCandidates(e,t,r){let n=e.length,a=Array(),i=0;for(let o=0;o<n;o++)for(let s=0;s<n;s++)0===e[o][s]||1===t[o][s].length&&0===r[o][s]||(i=0!==r[o][s].length?2*(e[o][s]+.5):2*e[o][s],i!==1/0&&a.push([i,t[o][s],r[o][s]]));return a.sort(function(e,t){return e[0]-t[0]}),a}static getSSSR(t,r,n,a,i,o,s,l){let c=Array(),d=Array();for(let r=0;r<t.length;r++)if(t[r][0]%2!=0)for(let a=0;a<t[r][2].length;a++){let i=t[r][1][0].concat(t[r][2][a]);for(var u=0;u<i.length;u++)i[u][0].constructor===Array&&(i[u]=i[u][0]);let p=e.bondsToAtoms(i);if(e.getBondCount(p,n)!==p.size||e.pathSetsContain(c,p,i,d,o,s)||(c.push(p),d=d.concat(i)),c.length>l)return c}else for(let a=0;a<t[r][1].length-1;a++){let i=t[r][1][a].concat(t[r][1][a+1]);for(u=0;u<i.length;u++)i[u][0].constructor===Array&&(i[u]=i[u][0]);let p=e.bondsToAtoms(i);if(e.getBondCount(p,n)!==p.size||e.pathSetsContain(c,p,i,d,o,s)||(c.push(p),d=d.concat(i)),c.length>l)return c}return c}static getEdgeCount(e){let t=0,r=e.length;for(var n=r-1;n--;)for(var a=r;a--;)1===e[n][a]&&t++;return t}static getEdgeList(e){let t=e.length,r=Array();for(var n=t-1;n--;)for(var a=t;a--;)1===e[n][a]&&r.push([n,a]);return r}static bondsToAtoms(e){let t=new Set;for(var r=e.length;r--;)t.add(e[r][0]),t.add(e[r][1]);return t}static getBondCount(e,t){let r=0;for(let n of e)for(let a of e)n!==a&&(r+=t[n][a]);return r/2}static pathSetsContain(t,r,n,a,i,o){for(var s=t.length;s--;){if(e.isSupersetOf(r,t[s]))return!0;if(t[s].size===r.size&&e.areSetsEqual(t[s],r))return!0}let l=0,c=!1;for(s=n.length;s--;)for(var d=a.length;d--;)(n[s][0]===a[d][0]&&n[s][1]===a[d][1]||n[s][1]===a[d][0]&&n[s][0]===a[d][1])&&l++,l===n.length&&(c=!0);let u=!1;if(c)for(let e of r)if(o[e]<i[e]){u=!0;break}if(c&&!u)return!0;for(let e of r)o[e]++;return!1}static areSetsEqual(e,t){if(e.size!==t.size)return!1;for(let r of e)if(!t.has(r))return!1;return!0}static isSupersetOf(e,t){for(var r of t)if(!e.has(r))return!1;return!0}};var qr=class{constructor(e,t){this.colors=e,this.theme=this.colors[t]}getColor(e){return e&&(e=e.toUpperCase())in this.theme?this.theme[e]:this.theme.C}setTheme(e){this.colors.hasOwnProperty(e)&&(this.theme=this.colors[e])}};var Hr=class{static extend(){let e=this,t={},r=!1,n=0,a=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(r=arguments[0],n++);let i=function(n){for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(r&&"[object Object]"===Object.prototype.toString.call(n[a])?t[a]=e.extend(!0,t[a],n[a]):t[a]=n[a])};for(;n<a;n++){i(arguments[n])}return t}};const Vr=mr,$r=_r,Wr=yr,jr=Ir;Cr();const Qr=xr,Kr=Ar(),Xr=Rr(),Zr=Nr(),Jr=Lr,en=Gr,tn=Yr,rn=qr,nn=Hr;var an=class{constructor(e){this.graph=null,this.doubleBondConfigCount=0,this.doubleBondConfig=null,this.ringIdCounter=0,this.ringConnectionIdCounter=0,this.canvasWrapper=null,this.totalOverlapScore=0,this.defaultOptions={width:500,height:500,scale:0,bondThickness:1,bondLength:30,shortBondLength:.8,bondSpacing:.17*30,atomVisualization:"default",isomeric:!0,debug:!1,terminalCarbons:!1,explicitHydrogens:!0,overlapSensitivity:.42,overlapResolutionIterations:1,compactDrawing:!0,fontFamily:"Arial, Helvetica, sans-serif",fontSizeLarge:11,fontSizeSmall:3,padding:10,experimentalSSSR:!1,kkThreshold:.1,kkInnerThreshold:.1,kkMaxIteration:2e4,kkMaxInnerIteration:50,kkMaxEnergy:1e9,weights:{colormap:null,additionalPadding:20,sigma:10,interval:0,opacity:1},themes:{dark:{C:"#fff",O:"#e74c3c",N:"#3498db",F:"#27ae60",CL:"#16a085",BR:"#d35400",I:"#8e44ad",P:"#d35400",S:"#f1c40f",B:"#e67e22",SI:"#e67e22",H:"#aaa",BACKGROUND:"#141414"},light:{C:"#222",O:"#e74c3c",N:"#3498db",F:"#27ae60",CL:"#16a085",BR:"#d35400",I:"#8e44ad",P:"#d35400",S:"#f1c40f",B:"#e67e22",SI:"#e67e22",H:"#666",BACKGROUND:"#fff"},oldschool:{C:"#000",O:"#000",N:"#000",F:"#000",CL:"#000",BR:"#000",I:"#000",P:"#000",S:"#000",B:"#000",SI:"#000",H:"#000",BACKGROUND:"#fff"},solarized:{C:"#586e75",O:"#dc322f",N:"#268bd2",F:"#859900",CL:"#16a085",BR:"#cb4b16",I:"#6c71c4",P:"#d33682",S:"#b58900",B:"#2aa198",SI:"#2aa198",H:"#657b83",BACKGROUND:"#fff"},"solarized-dark":{C:"#93a1a1",O:"#dc322f",N:"#268bd2",F:"#859900",CL:"#16a085",BR:"#cb4b16",I:"#6c71c4",P:"#d33682",S:"#b58900",B:"#2aa198",SI:"#2aa198",H:"#839496",BACKGROUND:"#fff"},matrix:{C:"#678c61",O:"#2fc079",N:"#4f7e7e",F:"#90d762",CL:"#82d967",BR:"#23755a",I:"#409931",P:"#c1ff8a",S:"#faff00",B:"#50b45a",SI:"#409931",H:"#426644",BACKGROUND:"#fff"},github:{C:"#24292f",O:"#cf222e",N:"#0969da",F:"#2da44e",CL:"#6fdd8b",BR:"#bc4c00",I:"#8250df",P:"#bf3989",S:"#d4a72c",B:"#fb8f44",SI:"#bc4c00",H:"#57606a",BACKGROUND:"#fff"},carbon:{C:"#161616",O:"#da1e28",N:"#0f62fe",F:"#198038",CL:"#007d79",BR:"#fa4d56",I:"#8a3ffc",P:"#ff832b",S:"#f1c21b",B:"#8a3800",SI:"#e67e22",H:"#525252",BACKGROUND:"#fff"},cyberpunk:{C:"#ea00d9",O:"#ff3131",N:"#0abdc6",F:"#00ff9f",CL:"#00fe00",BR:"#fe9f20",I:"#ff00ff",P:"#fe7f00",S:"#fcee0c",B:"#ff00ff",SI:"#ffffff",H:"#913cb1",BACKGROUND:"#fff"},gruvbox:{C:"#665c54",O:"#cc241d",N:"#458588",F:"#98971a",CL:"#79740e",BR:"#d65d0e",I:"#b16286",P:"#af3a03",S:"#d79921",B:"#689d6a",SI:"#427b58",H:"#7c6f64",BACKGROUND:"#fbf1c7"},"gruvbox-dark":{C:"#ebdbb2",O:"#cc241d",N:"#458588",F:"#98971a",CL:"#b8bb26",BR:"#d65d0e",I:"#b16286",P:"#fe8019",S:"#d79921",B:"#8ec07c",SI:"#83a598",H:"#bdae93",BACKGROUND:"#282828"},custom:{C:"#222",O:"#e74c3c",N:"#3498db",F:"#27ae60",CL:"#16a085",BR:"#d35400",I:"#8e44ad",P:"#d35400",S:"#f1c40f",B:"#e67e22",SI:"#e67e22",H:"#666",BACKGROUND:"#fff"}}},this.opts=nn.extend(!0,this.defaultOptions,e),this.opts.halfBondSpacing=this.opts.bondSpacing/2,this.opts.bondLengthSq=this.opts.bondLength*this.opts.bondLength,this.opts.halfFontSizeLarge=this.opts.fontSizeLarge/2,this.opts.quarterFontSizeLarge=this.opts.fontSizeLarge/4,this.opts.fifthFontSizeSmall=this.opts.fontSizeSmall/5,this.theme=this.opts.themes.dark}draw(e,t,r="light",n=!1){this.initDraw(e,r,n),this.infoOnly||(this.themeManager=new rn(this.opts.themes,r),this.canvasWrapper=new Jr(t,this.themeManager,this.opts)),n||(this.processGraph(),this.canvasWrapper.scale(this.graph.vertices),this.drawEdges(this.opts.debug),this.drawVertices(this.opts.debug),this.canvasWrapper.reset(),this.opts.debug&&(console.log(this.graph),console.log(this.rings),console.log(this.ringConnections)))}edgeRingCount(e){let t=this.graph.edges[e],r=this.graph.vertices[t.sourceId],n=this.graph.vertices[t.targetId];return Math.min(r.value.rings.length,n.value.rings.length)}getBridgedRings(){let e=Array();for(var t=0;t<this.rings.length;t++)this.rings[t].isBridged&&e.push(this.rings[t]);return e}getFusedRings(){let e=Array();for(var t=0;t<this.rings.length;t++)this.rings[t].isFused&&e.push(this.rings[t]);return e}getSpiros(){let e=Array();for(var t=0;t<this.rings.length;t++)this.rings[t].isSpiro&&e.push(this.rings[t]);return e}printRingInfo(){let e="";for(var t=0;t<this.rings.length;t++){const r=this.rings[t];e+=r.id+";",e+=r.members.length+";",e+=r.neighbours.length+";",e+=r.isSpiro?"true;":"false;",e+=r.isFused?"true;":"false;",e+=r.isBridged?"true;":"false;",e+=r.rings.length+";",e+="\n"}return e}rotateDrawing(){let e=0,t=0,r=0;for(var n=0;n<this.graph.vertices.length;n++){let i=this.graph.vertices[n];if(i.value.isDrawn)for(var a=n+1;a<this.graph.vertices.length;a++){let o=this.graph.vertices[a];if(!o.value.isDrawn)continue;let s=i.position.distanceSq(o.position);s>r&&(r=s,e=n,t=a)}}let i=-Wr.subtract(this.graph.vertices[e].position,this.graph.vertices[t].position).angle();if(!isNaN(i)){let e=i%.523599;e<.2617995?i-=e:i+=.523599-e;for(n=0;n<this.graph.vertices.length;n++)n!==t&&this.graph.vertices[n].position.rotateAround(i,this.graph.vertices[t].position);for(n=0;n<this.rings.length;n++)this.rings[n].center.rotateAround(i,this.graph.vertices[t].position)}}getTotalOverlapScore(){return this.totalOverlapScore}getRingCount(){return this.rings.length}hasBridgedRing(){return this.bridgedRing}getHeavyAtomCount(){let e=0;for(var t=0;t<this.graph.vertices.length;t++)"H"!==this.graph.vertices[t].value.element&&e++;return e}getMolecularFormula(e=null){let t="",r=new Map,n=null===e?this.graph:new en(e,this.opts.isomeric);for(var a=0;a<n.vertices.length;a++){let e=n.vertices[a].value;if(r.has(e.element)?r.set(e.element,r.get(e.element)+1):r.set(e.element,1),e.bracket&&!e.bracket.chirality&&(r.has("H")?r.set("H",r.get("H")+e.bracket.hcount):r.set("H",e.bracket.hcount)),!e.bracket){let t=Kr.maxBonds[e.element]-e.bondCount;e.isPartOfAromaticRing&&t--,r.has("H")?r.set("H",r.get("H")+t):r.set("H",t)}}if(r.has("C")){let e=r.get("C");t+="C"+(e>1?e:""),r.delete("C")}if(r.has("H")){let e=r.get("H");t+="H"+(e>1?e:""),r.delete("H")}return Object.keys(Kr.atomicNumbers).sort().map(e=>{if(r.has(e)){let n=r.get(e);t+=e+(n>1?n:"")}}),t}getRingbondType(e,t){if(e.value.getRingbondCount()<1||t.value.getRingbondCount()<1)return null;for(var r=0;r<e.value.ringbonds.length;r++)for(var n=0;n<t.value.ringbonds.length;n++)if(e.value.ringbonds[r].id===t.value.ringbonds[n].id)return"-"===e.value.ringbonds[r].bondType?t.value.ringbonds[n].bond:e.value.ringbonds[r].bond;return null}initDraw(e,t,r,n){this.data=e,this.infoOnly=r,this.ringIdCounter=0,this.ringConnectionIdCounter=0,this.graph=new en(e,this.opts.isomeric),this.rings=Array(),this.ringConnections=Array(),this.originalRings=Array(),this.originalRingConnections=Array(),this.bridgedRing=!1,this.doubleBondConfigCount=null,this.doubleBondConfig=null,this.highlight_atoms=n,this.initRings(),this.initHydrogens()}processGraph(){this.position(),this.restoreRingInformation(),this.resolvePrimaryOverlaps();let e=this.getOverlapScore();this.totalOverlapScore=this.getOverlapScore().total;for(var t=0;t<this.opts.overlapResolutionIterations;t++)for(var r=0;r<this.graph.edges.length;r++){let t=this.graph.edges[r];if(this.isEdgeRotatable(t)){let r=this.graph.getTreeDepth(t.sourceId,t.targetId),n=this.graph.getTreeDepth(t.targetId,t.sourceId),a=t.targetId,i=t.sourceId;if(r>n&&(a=t.sourceId,i=t.targetId),this.getSubtreeOverlapScore(i,a,e.vertexScores).value>this.opts.overlapSensitivity){let t=this.graph.vertices[a],r=this.graph.vertices[i],n=r.getNeighbours(a);if(1===n.length){let e=this.graph.vertices[n[0]],a=e.position.getRotateAwayFromAngle(t.position,r.position,Vr.toRad(120));this.rotateSubtree(e.id,r.id,a,r.position);let i=this.getOverlapScore().total;i>this.totalOverlapScore?this.rotateSubtree(e.id,r.id,-a,r.position):this.totalOverlapScore=i}else if(2===n.length){if(0!==r.value.rings.length&&0!==t.value.rings.length)continue;let e=this.graph.vertices[n[0]],a=this.graph.vertices[n[1]];if(1===e.value.rings.length&&1===a.value.rings.length){if(e.value.rings[0]!==a.value.rings[0])continue}else{if(0!==e.value.rings.length||0!==a.value.rings.length)continue;{let n=e.position.getRotateAwayFromAngle(t.position,r.position,Vr.toRad(120)),i=a.position.getRotateAwayFromAngle(t.position,r.position,Vr.toRad(120));this.rotateSubtree(e.id,r.id,n,r.position),this.rotateSubtree(a.id,r.id,i,r.position);let o=this.getOverlapScore().total;o>this.totalOverlapScore?(this.rotateSubtree(e.id,r.id,-n,r.position),this.rotateSubtree(a.id,r.id,-i,r.position)):this.totalOverlapScore=o}}}e=this.getOverlapScore()}}}this.resolveSecondaryOverlaps(e.scores),this.opts.isomeric&&this.annotateStereochemistry(),this.opts.compactDrawing&&"default"===this.opts.atomVisualization&&this.initPseudoElements(),this.rotateDrawing()}initRings(){let e=new Map;for(var t=this.graph.vertices.length-1;t>=0;t--){let n=this.graph.vertices[t];if(0!==n.value.ringbonds.length)for(var r=0;r<n.value.ringbonds.length;r++){let t=n.value.ringbonds[r].id,a=n.value.ringbonds[r].bond;if(e.has(t)){let i=n.id,o=e.get(t)[0],s=e.get(t)[1],l=new Qr(i,o,1);l.setBondType(s||a||"-");let c=this.graph.addEdge(l),d=this.graph.vertices[o];n.addRingbondChild(o,r),n.value.addNeighbouringElement(d.value.element),d.addRingbondChild(i,r),d.value.addNeighbouringElement(n.value.element),n.edges.push(c),d.edges.push(c),e.delete(t)}else e.set(t,[n.id,a])}}let n=tn.getRings(this.graph,this.opts.experimentalSSSR);if(null!==n){for(t=0;t<n.length;t++){let e=[...n[t]],a=this.addRing(new Xr(e));for(r=0;r<e.length;r++)this.graph.vertices[e[r]].value.rings.push(a)}for(t=0;t<this.rings.length-1;t++)for(r=t+1;r<this.rings.length;r++){let e=this.rings[t],n=this.rings[r],a=new Zr(e,n);a.vertices.size>0&&this.addRingConnection(a)}for(t=0;t<this.rings.length;t++){let e=this.rings[t];e.neighbours=Zr.getNeighbours(this.ringConnections,e.id)}for(t=0;t<this.rings.length;t++){let e=this.rings[t];this.graph.vertices[e.members[0]].value.addAnchoredRing(e.id)}for(this.backupRingInformation();this.rings.length>0;){let e=-1;for(t=0;t<this.rings.length;t++){let r=this.rings[t];this.isPartOfBridgedRing(r.id)&&!r.isBridged&&(e=r.id)}if(-1===e)break;let r=this.getRing(e),n=this.getBridgedRingRings(r.id);this.bridgedRing=!0,this.createBridgedRing(n,r.members[0]);for(t=0;t<n.length;t++)this.removeRing(n[t])}}}initHydrogens(){if(!this.opts.explicitHydrogens)for(var e=0;e<this.graph.vertices.length;e++){let t=this.graph.vertices[e];if("H"!==t.value.element)continue;let r=this.graph.vertices[t.neighbours[0]];r.value.hasHydrogen=!0,(!r.value.isStereoCenter||r.value.rings.length<2&&!r.value.bridgedRing||r.value.bridgedRing&&r.value.originalRings.length<2)&&(t.value.isDrawn=!1)}}getBridgedRingRings(e){let t=Array(),r=this,n=function(e){let a=r.getRing(e);t.push(e);for(var i=0;i<a.neighbours.length;i++){let o=a.neighbours[i];-1===t.indexOf(o)&&o!==e&&Zr.isBridge(r.ringConnections,r.graph.vertices,e,o)&&n(o)}};return n(e),$r.unique(t)}isPartOfBridgedRing(e){for(var t=0;t<this.ringConnections.length;t++)if(this.ringConnections[t].containsRing(e)&&this.ringConnections[t].isBridge(this.graph.vertices))return!0;return!1}createBridgedRing(e,t){let r=new Set,n=new Set,a=new Set;for(var i=0;i<e.length;i++){let t=this.getRing(e[i]);t.isPartOfBridged=!0;for(var o=0;o<t.members.length;o++)n.add(t.members[o]);for(o=0;o<t.neighbours.length;o++){let r=t.neighbours[o];-1===e.indexOf(r)&&a.add(t.neighbours[o])}}let s=new Set;for(let t of n){let n=this.graph.vertices[t],a=$r.intersection(e,n.value.rings);1===n.value.rings.length||1===a.length?r.add(n.id):s.add(n.id)}Array();let l=Array();for(let e of s){let t=this.graph.vertices[e],n=!1;for(let e=0;e<t.edges.length;e++)1===this.edgeRingCount(t.edges[e])&&(n=!0);n?(t.value.isBridgeNode=!0,r.add(t.id)):(t.value.isBridge=!0,r.add(t.id))}let c=new Xr([...r]);this.addRing(c),c.isBridged=!0,c.neighbours=[...a];for(i=0;i<e.length;i++)c.rings.push(this.getRing(e[i]).clone());for(i=0;i<c.members.length;i++)this.graph.vertices[c.members[i]].value.bridgedRing=c.id;for(i=0;i<l.length;i++){this.graph.vertices[l[i]].value.rings=Array()}for(let t of r){let r=this.graph.vertices[t];r.value.rings=$r.removeAll(r.value.rings,e),r.value.rings.push(c.id)}for(i=0;i<e.length;i++)for(o=i+1;o<e.length;o++)this.removeRingConnectionsBetween(e[i],e[o]);for(let t of a){let r=this.getRingConnections(t,e);for(o=0;o<r.length;o++)this.getRingConnection(r[o]).updateOther(c.id,t);this.getRing(t).neighbours.push(c.id)}return c}areVerticesInSameRing(e,t){for(var r=0;r<e.value.rings.length;r++)for(var n=0;n<t.value.rings.length;n++)if(e.value.rings[r]===t.value.rings[n])return!0;return!1}getCommonRings(e,t){let r=Array();for(var n=0;n<e.value.rings.length;n++)for(var a=0;a<t.value.rings.length;a++)e.value.rings[n]==t.value.rings[a]&&r.push(e.value.rings[n]);return r}getLargestOrAromaticCommonRing(e,t){let r=this.getCommonRings(e,t),n=0,a=null;for(var i=0;i<r.length;i++){let e=this.getRing(r[i]),t=e.getSize();if(e.isBenzeneLike(this.graph.vertices))return e;t>n&&(n=t,a=e)}return a}getVerticesAt(e,t,r){let n=Array();for(var a=0;a<this.graph.vertices.length;a++){let i=this.graph.vertices[a];i.id!==r&&i.positioned&&(e.distanceSq(i.position)<=t*t&&n.push(i.id))}return n}getClosestVertex(e){let t=99999,r=null;for(var n=0;n<this.graph.vertices.length;n++){let a=this.graph.vertices[n];if(a.id===e.id)continue;let i=e.position.distanceSq(a.position);i<t&&(t=i,r=a)}return r}addRing(e){return e.id=this.ringIdCounter++,this.rings.push(e),e.id}removeRing(e){this.rings=this.rings.filter(function(t){return t.id!==e}),this.ringConnections=this.ringConnections.filter(function(t){return t.firstRingId!==e&&t.secondRingId!==e});for(var t=0;t<this.rings.length;t++){let r=this.rings[t];r.neighbours=r.neighbours.filter(function(t){return t!==e})}}getRing(e){for(var t=0;t<this.rings.length;t++)if(this.rings[t].id==e)return this.rings[t]}addRingConnection(e){return e.id=this.ringConnectionIdCounter++,this.ringConnections.push(e),e.id}removeRingConnection(e){this.ringConnections=this.ringConnections.filter(function(t){return t.id!==e})}removeRingConnectionsBetween(e,t){let r=Array();for(var n=0;n<this.ringConnections.length;n++){let a=this.ringConnections[n];(a.firstRingId===e&&a.secondRingId===t||a.firstRingId===t&&a.secondRingId===e)&&r.push(a.id)}for(n=0;n<r.length;n++)this.removeRingConnection(r[n])}getRingConnection(e){for(var t=0;t<this.ringConnections.length;t++)if(this.ringConnections[t].id==e)return this.ringConnections[t]}getRingConnections(e,t){let r=Array();for(var n=0;n<this.ringConnections.length;n++){let i=this.ringConnections[n];for(var a=0;a<t.length;a++){let n=t[a];(i.firstRingId===e&&i.secondRingId===n||i.firstRingId===n&&i.secondRingId===e)&&r.push(i.id)}}return r}getOverlapScore(){let e=0,t=new Float32Array(this.graph.vertices.length);for(var r=0;r<this.graph.vertices.length;r++)t[r]=0;for(r=0;r<this.graph.vertices.length;r++)for(var n=this.graph.vertices.length;--n>r;){let a=this.graph.vertices[r],i=this.graph.vertices[n];if(!a.value.isDrawn||!i.value.isDrawn)continue;let o=Wr.subtract(a.position,i.position).lengthSq();if(o<this.opts.bondLengthSq){let a=(this.opts.bondLength-Math.sqrt(o))/this.opts.bondLength;e+=a,t[r]+=a,t[n]+=a}}let a=Array();for(r=0;r<this.graph.vertices.length;r++)a.push({id:r,score:t[r]});return a.sort(function(e,t){return t.score-e.score}),{total:e,scores:a,vertexScores:t}}chooseSide(e,t,r){let n=e.getNeighbours(t.id),a=t.getNeighbours(e.id),i=n.length,o=a.length,s=$r.merge(n,a),l=[0,0];for(var c=0;c<s.length;c++){this.graph.vertices[s[c]].position.sameSideAs(e.position,t.position,r[0])?l[0]++:l[1]++}let d=[0,0];for(c=0;c<this.graph.vertices.length;c++){this.graph.vertices[c].position.sameSideAs(e.position,t.position,r[0])?d[0]++:d[1]++}return{totalSideCount:d,totalPosition:d[0]>d[1]?0:1,sideCount:l,position:l[0]>l[1]?0:1,anCount:i,bnCount:o}}setRingCenter(e){let t=e.getSize(),r=new Wr(0,0);for(var n=0;n<t;n++)r.add(this.graph.vertices[e.members[n]].position);e.center=r.divide(t)}getSubringCenter(e,t){let r=t.value.originalRings,n=e.center,a=Number.MAX_VALUE;for(var i=0;i<r.length;i++)for(var o=0;o<e.rings.length;o++)r[i]===e.rings[o].id&&e.rings[o].getSize()<a&&(n=e.rings[o].center,a=e.rings[o].getSize());return n}drawEdges(e){let t=this,r=Array(this.graph.edges.length);if(r.fill(!1),this.graph.traverseBF(0,function(n){let a=t.graph.getEdges(n.id);for(var i=0;i<a.length;i++){let n=a[i];r[n]||(r[n]=!0,t.drawEdge(n,e))}}),!this.bridgedRing)for(var n=0;n<this.rings.length;n++){let e=this.rings[n];this.isRingAromatic(e)&&this.canvasWrapper.drawAromaticityRing(e)}}drawEdge(e,t){let r=this,n=this.graph.edges[e],a=this.graph.vertices[n.sourceId],i=this.graph.vertices[n.targetId],o=a.value.element,s=i.value.element;if(!(a.value.isDrawn&&i.value.isDrawn||"default"!==this.opts.atomVisualization))return;let l=a.position,c=i.position,d=this.getEdgeNormals(n),u=$r.clone(d);if(u[0].multiplyScalar(10).add(l),u[1].multiplyScalar(10).add(l),"="===n.bondType||"="===this.getRingbondType(a,i)||n.isPartOfAromaticRing&&this.bridgedRing){let e=this.areVerticesInSameRing(a,i),t=this.chooseSide(a,i,u);if(e){let e=this.getLargestOrAromaticCommonRing(a,i).center;d[0].multiplyScalar(r.opts.bondSpacing),d[1].multiplyScalar(r.opts.bondSpacing);let t=null;t=e.sameSideAs(a.position,i.position,Wr.add(l,d[0]))?new jr(Wr.add(l,d[0]),Wr.add(c,d[0]),o,s):new jr(Wr.add(l,d[1]),Wr.add(c,d[1]),o,s),t.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),n.isPartOfAromaticRing?this.canvasWrapper.drawLine(t,!0):this.canvasWrapper.drawLine(t),this.canvasWrapper.drawLine(new jr(l,c,o,s))}else if(n.center||a.isTerminal()&&i.isTerminal()){d[0].multiplyScalar(r.opts.halfBondSpacing),d[1].multiplyScalar(r.opts.halfBondSpacing);let e=new jr(Wr.add(l,d[0]),Wr.add(c,d[0]),o,s),t=new jr(Wr.add(l,d[1]),Wr.add(c,d[1]),o,s);this.canvasWrapper.drawLine(e),this.canvasWrapper.drawLine(t)}else if(0==t.anCount&&t.bnCount>1||0==t.bnCount&&t.anCount>1){d[0].multiplyScalar(r.opts.halfBondSpacing),d[1].multiplyScalar(r.opts.halfBondSpacing);let e=new jr(Wr.add(l,d[0]),Wr.add(c,d[0]),o,s),t=new jr(Wr.add(l,d[1]),Wr.add(c,d[1]),o,s);this.canvasWrapper.drawLine(e),this.canvasWrapper.drawLine(t)}else if(t.sideCount[0]>t.sideCount[1]){d[0].multiplyScalar(r.opts.bondSpacing),d[1].multiplyScalar(r.opts.bondSpacing);let e=new jr(Wr.add(l,d[0]),Wr.add(c,d[0]),o,s);e.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),this.canvasWrapper.drawLine(e),this.canvasWrapper.drawLine(new jr(l,c,o,s))}else if(t.sideCount[0]<t.sideCount[1]){d[0].multiplyScalar(r.opts.bondSpacing),d[1].multiplyScalar(r.opts.bondSpacing);let e=new jr(Wr.add(l,d[1]),Wr.add(c,d[1]),o,s);e.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),this.canvasWrapper.drawLine(e),this.canvasWrapper.drawLine(new jr(l,c,o,s))}else if(t.totalSideCount[0]>t.totalSideCount[1]){d[0].multiplyScalar(r.opts.bondSpacing),d[1].multiplyScalar(r.opts.bondSpacing);let e=new jr(Wr.add(l,d[0]),Wr.add(c,d[0]),o,s);e.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),this.canvasWrapper.drawLine(e),this.canvasWrapper.drawLine(new jr(l,c,o,s))}else if(t.totalSideCount[0]<=t.totalSideCount[1]){d[0].multiplyScalar(r.opts.bondSpacing),d[1].multiplyScalar(r.opts.bondSpacing);let e=new jr(Wr.add(l,d[1]),Wr.add(c,d[1]),o,s);e.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),this.canvasWrapper.drawLine(e),this.canvasWrapper.drawLine(new jr(l,c,o,s))}}else if("#"===n.bondType){d[0].multiplyScalar(r.opts.bondSpacing/1.5),d[1].multiplyScalar(r.opts.bondSpacing/1.5);let e=new jr(Wr.add(l,d[0]),Wr.add(c,d[0]),o,s),t=new jr(Wr.add(l,d[1]),Wr.add(c,d[1]),o,s);this.canvasWrapper.drawLine(e),this.canvasWrapper.drawLine(t),this.canvasWrapper.drawLine(new jr(l,c,o,s))}else if("."===n.bondType);else{let e=a.value.isStereoCenter,t=i.value.isStereoCenter;"up"===n.wedge?this.canvasWrapper.drawWedge(new jr(l,c,o,s,e,t)):"down"===n.wedge?this.canvasWrapper.drawDashedWedge(new jr(l,c,o,s,e,t)):this.canvasWrapper.drawLine(new jr(l,c,o,s,e,t))}if(t){let t=Wr.midpoint(l,c);this.canvasWrapper.drawDebugText(t.x,t.y,"e: "+e)}}drawVertices(e){var t=this.graph.vertices.length;for(t=0;t<this.graph.vertices.length;t++){let r=this.graph.vertices[t],n=r.value,a=0,i=0,o=r.value.bondCount,s=n.element,l=Kr.maxBonds[s]-o,c=r.getTextDirection(this.graph.vertices),d=!(!this.opts.terminalCarbons&&"C"===s&&!n.hasAttachedPseudoElements)&&r.isTerminal(),u="C"===n.element;if("N"===n.element&&n.isPartOfAromaticRing&&(l=0),n.bracket&&(l=n.bracket.hcount,a=n.bracket.charge,i=n.bracket.isotope),"allballs"===this.opts.atomVisualization)this.canvasWrapper.drawBall(r.position.x,r.position.y,s);else if(n.isDrawn&&(!u||n.drawExplicit||d||n.hasAttachedPseudoElements)||1===this.graph.vertices.length)"default"===this.opts.atomVisualization?this.canvasWrapper.drawText(r.position.x,r.position.y,s,l,c,d,a,i,this.graph.vertices.length,n.getAttachedPseudoElements()):"balls"===this.opts.atomVisualization&&this.canvasWrapper.drawBall(r.position.x,r.position.y,s);else if(2===r.getNeighbourCount()&&1==r.forcePositioned){let e=this.graph.vertices[r.neighbours[0]].position,t=this.graph.vertices[r.neighbours[1]].position,n=Wr.threePointangle(r.position,e,t);Math.abs(Math.PI-n)<.1&&this.canvasWrapper.drawPoint(r.position.x,r.position.y,s)}if(e){let e="v: "+r.id+" "+$r.print(n.ringbonds);this.canvasWrapper.drawDebugText(r.position.x,r.position.y,e)}}if(this.opts.debug)for(t=0;t<this.rings.length;t++){let e=this.rings[t].center;this.canvasWrapper.drawDebugPoint(e.x,e.y,"r: "+this.rings[t].id)}}position(){let e=null;for(var t=0;t<this.graph.vertices.length;t++)if(null!==this.graph.vertices[t].value.bridgedRing){e=this.graph.vertices[t];break}for(t=0;t<this.rings.length;t++)this.rings[t].isBridged&&(e=this.graph.vertices[this.rings[t].members[0]]);this.rings.length>0&&null===e&&(e=this.graph.vertices[this.rings[0].members[0]]),null===e&&(e=this.graph.vertices[0]),this.createNextBond(e,null,0)}backupRingInformation(){this.originalRings=Array(),this.originalRingConnections=Array();for(var e=0;e<this.rings.length;e++)this.originalRings.push(this.rings[e]);for(e=0;e<this.ringConnections.length;e++)this.originalRingConnections.push(this.ringConnections[e]);for(e=0;e<this.graph.vertices.length;e++)this.graph.vertices[e].value.backupRings()}restoreRingInformation(){let e=this.getBridgedRings();this.rings=Array(),this.ringConnections=Array();for(var t=0;t<e.length;t++){let n=e[t];for(var r=0;r<n.rings.length;r++){let e=n.rings[r];this.originalRings[e.id].center=e.center}}for(t=0;t<this.originalRings.length;t++)this.rings.push(this.originalRings[t]);for(t=0;t<this.originalRingConnections.length;t++)this.ringConnections.push(this.originalRingConnections[t]);for(t=0;t<this.graph.vertices.length;t++)this.graph.vertices[t].value.restoreRings()}createRing(e,t=null,r=null,n=null){if(e.positioned)return;t=t||new Wr(0,0);let a=e.getOrderedNeighbours(this.ringConnections),i=r?Wr.subtract(r.position,t).angle():0,o=Vr.polyCircumradius(this.opts.bondLength,e.getSize()),s=Vr.centralAngle(e.getSize());e.centralAngle=s;let l=i,c=this,d=r?r.id:null;if(-1===e.members.indexOf(d)&&(r&&(r.positioned=!1),d=e.members[0]),e.isBridged){this.graph.kkLayout(e.members.slice(),t,r.id,e,this.opts.bondLength,this.opts.kkThreshold,this.opts.kkInnerThreshold,this.opts.kkMaxIteration,this.opts.kkMaxInnerIteration,this.opts.kkMaxEnergy),e.positioned=!0,this.setRingCenter(e),t=e.center;for(var u=0;u<e.rings.length;u++)this.setRingCenter(e.rings[u])}else e.eachMember(this.graph.vertices,function(r){let n=c.graph.vertices[r];n.positioned||n.setPosition(t.x+Math.cos(l)*o,t.y+Math.sin(l)*o),l+=s,(!e.isBridged||e.rings.length<3)&&(n.angle=l,n.positioned=!0)},d,n?n.id:null);e.positioned=!0,e.center=t;for(u=0;u<a.length;u++){let r=this.getRing(a[u].neighbour);if(r.positioned)continue;let n=Zr.getVertices(this.ringConnections,e.id,r.id);if(2===n.length){e.isFused=!0,r.isFused=!0;let a=this.graph.vertices[n[0]],i=this.graph.vertices[n[1]],o=Wr.midpoint(a.position,i.position),s=Wr.normals(a.position,i.position);s[0].normalize(),s[1].normalize();let l=Vr.polyCircumradius(this.opts.bondLength,r.getSize()),c=Vr.apothem(l,r.getSize());s[0].multiplyScalar(c).add(o),s[1].multiplyScalar(c).add(o);let d=s[0];Wr.subtract(t,s[1]).lengthSq()>Wr.subtract(t,s[0]).lengthSq()&&(d=s[1]);let u=Wr.subtract(a.position,d),p=Wr.subtract(i.position,d);-1===u.clockwise(p)?r.positioned||this.createRing(r,d,a,i):r.positioned||this.createRing(r,d,i,a)}else if(1===n.length){e.isSpiro=!0,r.isSpiro=!0;let a=this.graph.vertices[n[0]],i=Wr.subtract(t,a.position);i.invert(),i.normalize();let o=Vr.polyCircumradius(this.opts.bondLength,r.getSize());i.multiplyScalar(o),i.add(a.position),r.positioned||this.createRing(r,i,a)}}for(u=0;u<e.members.length;u++){let t=this.graph.vertices[e.members[u]],r=t.neighbours;for(var p=0;p<r.length;p++){let e=this.graph.vertices[r[p]];e.positioned||(e.value.isConnectedToRing=!0,this.createNextBond(e,t,0))}}}rotateSubtree(e,t,r,n){let a=this;this.graph.traverseTree(e,t,function(e){e.position.rotateAround(r,n);for(var t=0;t<e.value.anchoredRings.length;t++){let i=a.rings[e.value.anchoredRings[t]];i&&i.center.rotateAround(r,n)}})}getSubtreeOverlapScore(e,t,r){let n=this,a=0,i=new Wr(0,0),o=0;return this.graph.traverseTree(e,t,function(e){if(!e.value.isDrawn)return;let t=r[e.id];t>n.opts.overlapSensitivity&&(a+=t,o++);let s=n.graph.vertices[e.id].position.clone();s.multiplyScalar(t),i.add(s)}),i.divide(a),{value:a/o,center:i}}getCurrentCenterOfMass(){let e=new Wr(0,0),t=0;for(var r=0;r<this.graph.vertices.length;r++){let n=this.graph.vertices[r];n.positioned&&(e.add(n.position),t++)}return e.divide(t)}getCurrentCenterOfMassInNeigbourhood(e,t=2*this.opts.bondLength){let r=new Wr(0,0),n=0,a=t*t;for(var i=0;i<this.graph.vertices.length;i++){let t=this.graph.vertices[i];t.positioned&&e.distanceSq(t.position)<a&&(r.add(t.position),n++)}return r.divide(n)}resolvePrimaryOverlaps(){let e=Array(),t=Array(this.graph.vertices.length);for(var r=0;r<this.rings.length;r++){let i=this.rings[r];for(var n=0;n<i.members.length;n++){let r=this.graph.vertices[i.members[n]];if(t[r.id])continue;t[r.id]=!0;let o=this.getNonRingNeighbours(r.id);if(o.length>1){let t=Array();for(var a=0;a<r.value.rings.length;a++)t.push(r.value.rings[a]);e.push({common:r,rings:t,vertices:o})}else if(1===o.length&&2===r.value.rings.length){let t=Array();for(a=0;a<r.value.rings.length;a++)t.push(r.value.rings[a]);e.push({common:r,rings:t,vertices:o})}}}for(r=0;r<e.length;r++){let t=e[r];if(2===t.vertices.length){let e=t.vertices[0],r=t.vertices[1];if(!e.value.isDrawn||!r.value.isDrawn)continue;let n=(2*Math.PI-this.getRing(t.rings[0]).getAngle())/6;this.rotateSubtree(e.id,t.common.id,n,t.common.position),this.rotateSubtree(r.id,t.common.id,-n,t.common.position);let a=this.getOverlapScore(),i=this.getSubtreeOverlapScore(e.id,t.common.id,a.vertexScores),o=this.getSubtreeOverlapScore(r.id,t.common.id,a.vertexScores),s=i.value+o.value;this.rotateSubtree(e.id,t.common.id,-2*n,t.common.position),this.rotateSubtree(r.id,t.common.id,2*n,t.common.position),a=this.getOverlapScore(),i=this.getSubtreeOverlapScore(e.id,t.common.id,a.vertexScores),o=this.getSubtreeOverlapScore(r.id,t.common.id,a.vertexScores),i.value+o.value>s&&(this.rotateSubtree(e.id,t.common.id,2*n,t.common.position),this.rotateSubtree(r.id,t.common.id,-2*n,t.common.position))}else 1===t.vertices.length&&t.rings.length}}resolveSecondaryOverlaps(e){for(var t=0;t<e.length;t++)if(e[t].score>this.opts.overlapSensitivity){let r=this.graph.vertices[e[t].id];if(r.isTerminal()){let e=this.getClosestVertex(r);if(e){let t=null;t=e.isTerminal()?0===e.id?this.graph.vertices[1].position:e.previousPosition:0===e.id?this.graph.vertices[1].position:e.position;let n=0===r.id?this.graph.vertices[1].position:r.previousPosition;r.position.rotateAwayFrom(t,n,Vr.toRad(20))}}}}getLastVertexWithAngle(e){let t=0,r=null;for(;!t&&e;)r=this.graph.vertices[e],t=r.angle,e=r.parentVertexId;return r}createNextBond(e,t=null,r=0,n=!1,a=!1){if(e.positioned&&!a)return;let i=!1;if(t){let r=this.graph.getEdge(e.id,t.id);"/"!==r.bondType&&"\\"!==r.bondType||++this.doubleBondConfigCount%2!=1||null===this.doubleBondConfig&&(this.doubleBondConfig=r.bondType,i=!0,null===t.parentVertexId&&e.value.branchBond&&("/"===this.doubleBondConfig?this.doubleBondConfig="\\":"\\"===this.doubleBondConfig&&(this.doubleBondConfig="/")))}if(!a)if(t)if(t.value.rings.length>0){let r=t.neighbours,n=null,a=new Wr(0,0);if(null===t.value.bridgedRing&&t.value.rings.length>1)for(var o=0;o<r.length;o++){let e=this.graph.vertices[r[o]];if($r.containsAll(e.value.rings,t.value.rings)){n=e;break}}if(null===n){for(o=0;o<r.length;o++){let e=this.graph.vertices[r[o]];e.positioned&&this.areVerticesInSameRing(e,t)&&a.add(Wr.subtract(e.position,t.position))}a.invert().normalize().multiplyScalar(this.opts.bondLength).add(t.position)}else a=n.position.clone().rotateAround(Math.PI,t.position);e.previousPosition=t.position,e.setPositionFromVector(a),e.positioned=!0}else{let n=new Wr(this.opts.bondLength,0);n.rotate(r),n.add(t.position),e.setPositionFromVector(n),e.previousPosition=t.position,e.positioned=!0}else{let t=new Wr(this.opts.bondLength,0);t.rotate(Vr.toRad(-60)),e.previousPosition=t,e.setPosition(this.opts.bondLength,0),e.angle=Vr.toRad(-60),null===e.value.bridgedRing&&(e.positioned=!0)}if(null!==e.value.bridgedRing){let t=this.getRing(e.value.bridgedRing);if(!t.positioned){let r=Wr.subtract(e.previousPosition,e.position);r.invert(),r.normalize();let n=Vr.polyCircumradius(this.opts.bondLength,t.members.length);r.multiplyScalar(n),r.add(e.position),this.createRing(t,r,e)}}else if(e.value.rings.length>0){let t=this.getRing(e.value.rings[0]);if(!t.positioned){let r=Wr.subtract(e.previousPosition,e.position);r.invert(),r.normalize();let n=Vr.polyCircumradius(this.opts.bondLength,t.getSize());r.multiplyScalar(n),r.add(e.position),this.createRing(t,r,e)}}else{e.value.isStereoCenter;let r=e.getNeighbours(),a=Array();for(o=0;o<r.length;o++)this.graph.vertices[r[o]].value.isDrawn&&a.push(r[o]);t&&(a=$r.remove(a,t.id));let s=e.getAngle();if(1===a.length){let r=this.graph.vertices[a[0]];if("#"===e.value.bondType||t&&"#"===t.value.bondType||"="===e.value.bondType&&t&&0===t.value.rings.length&&"="===t.value.bondType&&"-"!==e.value.branchBond){if(e.value.drawExplicit=!1,t){this.graph.getEdge(e.id,t.id).center=!0}this.graph.getEdge(e.id,r.id).center=!0,("#"===e.value.bondType||t&&"#"===t.value.bondType)&&(r.angle=0),r.drawExplicit=!0,this.createNextBond(r,e,s+r.angle)}else if(t&&t.value.rings.length>0){let t=Vr.toRad(60),n=-t,a=new Wr(this.opts.bondLength,0),i=new Wr(this.opts.bondLength,0);a.rotate(t).add(e.position),i.rotate(n).add(e.position);let o=this.getCurrentCenterOfMass(),l=a.distanceSq(o),c=i.distanceSq(o);r.angle=l<c?n:t,this.createNextBond(r,e,s+r.angle)}else{let a=e.angle;if(t&&t.neighbours.length>3)a=a>0?Math.min(1.0472,a):a<0?Math.max(-1.0472,a):1.0472;else if(!a){a=this.getLastVertexWithAngle(e.id).angle,a||(a=1.0472)}if(t&&!i){let t=this.graph.getEdge(e.id,r.id).bondType;"/"===t?("/"===this.doubleBondConfig||"\\"===this.doubleBondConfig&&(a=-a),this.doubleBondConfig=null):"\\"===t&&("/"===this.doubleBondConfig?a=-a:this.doubleBondConfig,this.doubleBondConfig=null)}r.angle=n?a:-a,this.createNextBond(r,e,s+r.angle)}}else if(2===a.length){let r=e.angle;r||(r=1.0472);let n=this.graph.getTreeDepth(a[0],e.id),i=this.graph.getTreeDepth(a[1],e.id),o=this.graph.vertices[a[0]],l=this.graph.vertices[a[1]];o.value.subtreeDepth=n,l.value.subtreeDepth=i;let c=this.graph.getTreeDepth(t?t.id:null,e.id);t&&(t.value.subtreeDepth=c);let d=0,u=1;"C"===l.value.element&&"C"!==o.value.element&&i>1&&n<5?(d=1,u=0):"C"!==l.value.element&&"C"===o.value.element&&n>1&&i<5?(d=0,u=1):i>n&&(d=1,u=0);let p=this.graph.vertices[a[d]],_=this.graph.vertices[a[u]];this.graph.getEdge(e.id,p.id),this.graph.getEdge(e.id,_.id);let m=!1;c<n&&c<i&&(m=!0),_.angle=r,p.angle=-r,"\\"===this.doubleBondConfig?"\\"===_.value.branchBond&&(_.angle=-r,p.angle=r):"/"===this.doubleBondConfig&&"/"===_.value.branchBond&&(_.angle=-r,p.angle=r),this.createNextBond(_,e,s+_.angle,m),this.createNextBond(p,e,s+p.angle,m)}else if(3===a.length){let r=this.graph.getTreeDepth(a[0],e.id),n=this.graph.getTreeDepth(a[1],e.id),i=this.graph.getTreeDepth(a[2],e.id),o=this.graph.vertices[a[0]],l=this.graph.vertices[a[1]],c=this.graph.vertices[a[2]];o.value.subtreeDepth=r,l.value.subtreeDepth=n,c.value.subtreeDepth=i,n>r&&n>i?(o=this.graph.vertices[a[1]],l=this.graph.vertices[a[0]],c=this.graph.vertices[a[2]]):i>r&&i>n&&(o=this.graph.vertices[a[2]],l=this.graph.vertices[a[0]],c=this.graph.vertices[a[1]]),t&&t.value.rings.length<1&&o.value.rings.length<1&&l.value.rings.length<1&&c.value.rings.length<1&&1===this.graph.getTreeDepth(l.id,e.id)&&1===this.graph.getTreeDepth(c.id,e.id)&&this.graph.getTreeDepth(o.id,e.id)>1?(o.angle=-e.angle,e.angle>=0?(l.angle=Vr.toRad(30),c.angle=Vr.toRad(90)):(l.angle=-Vr.toRad(30),c.angle=-Vr.toRad(90)),this.createNextBond(o,e,s+o.angle),this.createNextBond(l,e,s+l.angle),this.createNextBond(c,e,s+c.angle)):(o.angle=0,l.angle=Vr.toRad(90),c.angle=-Vr.toRad(90),this.createNextBond(o,e,s+o.angle),this.createNextBond(l,e,s+l.angle),this.createNextBond(c,e,s+c.angle))}else if(4===a.length){let t=this.graph.getTreeDepth(a[0],e.id),r=this.graph.getTreeDepth(a[1],e.id),n=this.graph.getTreeDepth(a[2],e.id),i=this.graph.getTreeDepth(a[3],e.id),o=this.graph.vertices[a[0]],l=this.graph.vertices[a[1]],c=this.graph.vertices[a[2]],d=this.graph.vertices[a[3]];o.value.subtreeDepth=t,l.value.subtreeDepth=r,c.value.subtreeDepth=n,d.value.subtreeDepth=i,r>t&&r>n&&r>i?(o=this.graph.vertices[a[1]],l=this.graph.vertices[a[0]],c=this.graph.vertices[a[2]],d=this.graph.vertices[a[3]]):n>t&&n>r&&n>i?(o=this.graph.vertices[a[2]],l=this.graph.vertices[a[0]],c=this.graph.vertices[a[1]],d=this.graph.vertices[a[3]]):i>t&&i>r&&i>n&&(o=this.graph.vertices[a[3]],l=this.graph.vertices[a[0]],c=this.graph.vertices[a[1]],d=this.graph.vertices[a[2]]),o.angle=-Vr.toRad(36),l.angle=Vr.toRad(36),c.angle=-Vr.toRad(108),d.angle=Vr.toRad(108),this.createNextBond(o,e,s+o.angle),this.createNextBond(l,e,s+l.angle),this.createNextBond(c,e,s+c.angle),this.createNextBond(d,e,s+d.angle)}}}getCommonRingbondNeighbour(e){let t=e.neighbours;for(var r=0;r<t.length;r++){let n=this.graph.vertices[t[r]];if($r.containsAll(n.value.rings,e.value.rings))return n}return null}isPointInRing(e){for(var t=0;t<this.rings.length;t++){let r=this.rings[t];if(!r.positioned)continue;let n=Vr.polyCircumradius(this.opts.bondLength,r.getSize()),a=n*n;if(e.distanceSq(r.center)<a)return!0}return!1}isEdgeInRing(e){let t=this.graph.vertices[e.sourceId],r=this.graph.vertices[e.targetId];return this.areVerticesInSameRing(t,r)}isEdgeRotatable(e){let t=this.graph.vertices[e.sourceId],r=this.graph.vertices[e.targetId];return"-"===e.bondType&&(!t.isTerminal()&&!r.isTerminal()&&!(t.value.rings.length>0&&r.value.rings.length>0&&this.areVerticesInSameRing(t,r)))}isRingAromatic(e){for(var t=0;t<e.members.length;t++){if(!this.graph.vertices[e.members[t]].value.isPartOfAromaticRing)return!1}return!0}getEdgeNormals(e){let t=this.graph.vertices[e.sourceId].position,r=this.graph.vertices[e.targetId].position;return Wr.units(t,r)}getNonRingNeighbours(e){let t=Array(),r=this.graph.vertices[e],n=r.neighbours;for(var a=0;a<n.length;a++){let e=this.graph.vertices[n[a]];0===$r.intersection(r.value.rings,e.value.rings).length&&0==e.value.isBridge&&t.push(e)}return t}annotateStereochemistry(){for(var e=0;e<this.graph.vertices.length;e++){let a=this.graph.vertices[e];if(!a.value.isStereoCenter)continue;let i=a.getNeighbours(),o=i.length,s=Array(o);for(var t=0;t<o;t++){let e=new Uint8Array(this.graph.vertices.length),n=Array(Array());e[a.id]=1,this.visitStereochemistry(i[t],a.id,e,n,10,0);for(var r=0;r<n.length;r++)n[r].sort(function(e,t){return t-e});s[t]=[t,n]}let l=0,c=0;for(t=0;t<s.length;t++){s[t][1].length>l&&(l=s[t][1].length);for(r=0;r<s[t][1].length;r++)s[t][1][r].length>c&&(c=s[t][1][r].length)}for(t=0;t<s.length;t++){let e=l-s[t][1].length;for(r=0;r<e;r++)s[t][1].push([]);s[t][1].push([i[t]]);for(r=0;r<s[t][1].length;r++){let e=c-s[t][1][r].length;for(var n=0;n<e;n++)s[t][1][r].push(0)}}s.sort(function(e,t){for(var r=0;r<e[1].length;r++)for(var n=0;n<e[1][r].length;n++){if(e[1][r][n]>t[1][r][n])return-1;if(e[1][r][n]<t[1][r][n])return 1}return 0});let d=new Uint8Array(o);for(t=0;t<o;t++)d[t]=s[t][0],a.value.priority=t;let u=this.graph.vertices[i[d[0]]].position,p=this.graph.vertices[i[d[1]]].position,_=this.graph.vertices[i[d[2]]].position,m=u.relativeClockwise(p,a.position);u.relativeClockwise(_,a.position);let g=-1===m,h="@"===a.value.bracket.chirality?-1:1,f=Vr.parityOfPermutation(d)*h===1?"R":"S",E="down",b="up";(g&&"R"!==f||!g&&"S"!==f)&&(a.value.hydrogenDirection="up",E="up",b="down"),a.value.hasHydrogen&&(this.graph.getEdge(a.id,i[d[d.length-1]]).wedge=E);let S=new Array(i.length-1),v=a.value.rings.length>1&&a.value.hasHydrogen,T=a.value.hasHydrogen?1:0;for(t=0;t<d.length-T;t++){S[t]=new Uint32Array(2);let e=this.graph.vertices[i[d[t]]];S[t][0]+=e.value.isStereoCenter?0:1e5,S[t][0]+=this.areVerticesInSameRing(e,a)?0:1e4,S[t][0]+=e.value.isHeteroAtom()?1e3:0,S[t][0]-=0===e.value.subtreeDepth?1e3:0,S[t][0]+=1e3-e.value.subtreeDepth,S[t][1]=i[d[t]]}if(S.sort(function(e,t){return e[0]>t[0]?-1:e[0]<t[0]?1:0}),!v){let e=S[0][1];if(a.value.hasHydrogen)this.graph.getEdge(a.id,e).wedge=b;else{let r=b;for(t=d.length-1;t>=0&&(r=r===E?b:E,i[d[t]]!==e);t--);this.graph.getEdge(a.id,e).wedge=r}}a.value.chirality=f}}visitStereochemistry(e,t,r,n,a,i,o=0){r[e]=1;let s=this.graph.vertices[e],l=s.value.getAtomicNumber();n.length<=i&&n.push(Array());for(var c=0;c<this.graph.getEdge(e,t).weight;c++)n[i].push(1e3*o+l);let d=this.graph.vertices[e].neighbours;for(c=0;c<d.length;c++)1!==r[d[c]]&&i<a-1&&this.visitStereochemistry(d[c],e,r.slice(),n,a,i+1,l);if(i<a-1){let t=0;for(c=0;c<d.length;c++)t+=this.graph.getEdge(e,d[c]).weight;for(c=0;c<s.value.getMaxBonds()-t;c++)n.length<=i+1&&n.push(Array()),n[i+1].push(1e3*l+1)}}initPseudoElements(){for(var e=0;e<this.graph.vertices.length;e++){const r=this.graph.vertices[e],n=r.neighbours;let a=Array(n.length);for(var t=0;t<n.length;t++)a[t]=this.graph.vertices[n[t]];if(r.getNeighbourCount()<3||r.value.rings.length>0)continue;if("P"===r.value.element)continue;if("C"===r.value.element&&3===a.length&&"N"===a[0].value.element&&"N"===a[1].value.element&&"N"===a[2].value.element)continue;let i=0,o=0;for(t=0;t<a.length;t++){let e=a[t],r=e.value.element,n=e.getNeighbourCount();"C"!==r&&"H"!==r&&1===n&&i++,n>1&&o++}if(o>1||i<2)continue;let s=null;for(t=0;t<a.length;t++){let e=a[t];e.getNeighbourCount()>1&&(s=e)}for(t=0;t<a.length;t++){let e=a[t];if(e.getNeighbourCount()>1)continue;e.value.isDrawn=!1;let n=Kr.maxBonds[e.value.element]-e.value.bondCount,i="";e.value.bracket&&(n=e.value.bracket.hcount,i=e.value.bracket.charge||0),r.value.attachPseudoElement(e.value.element,s?s.value.element:null,n,i)}}for(e=0;e<this.graph.vertices.length;e++){const r=this.graph.vertices[e],n=r.value,a=n.element;if("C"===a||"H"===a||!n.isDrawn)continue;const i=r.neighbours;let o=Array(i.length);for(t=0;t<i.length;t++)o[t]=this.graph.vertices[i[t]];for(t=0;t<o.length;t++){let e=o[t].value;if(!e.hasAttachedPseudoElements||2!==e.getAttachedPseudoElementsCount())continue;const n=e.getAttachedPseudoElements();n.hasOwnProperty("0O")&&n.hasOwnProperty("3C")&&(e.isDrawn=!1,r.value.attachPseudoElement("Ac","",0))}}}};const{getChargeText:on}=wr,sn=Ir,ln=yr,cn=mr;var dn=class e{constructor(e,t,r,n=!0){if(this.svg="string"==typeof t||t instanceof String?document.getElementById(t):t,this.container=null,this.opts=r,this.uid=function(e){for(var t="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=0;n<e;n++)t+=r.charAt(Math.floor(62*Math.random()));return t}(5),this.gradientId=0,this.backgroundItems=[],this.paths=[],this.vertices=[],this.gradients=[],this.highlights=[],this.drawingWidth=0,this.drawingHeight=0,this.halfBondThickness=this.opts.bondThickness/2,this.themeManager=e,this.maskElements=[],this.maxX=-Number.MAX_VALUE,this.maxY=-Number.MAX_VALUE,this.minX=Number.MAX_VALUE,this.minY=Number.MAX_VALUE,n)for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild);this.style=document.createElementNS("http://www.w3.org/2000/svg","style"),this.style.appendChild(document.createTextNode(`\n .element {\n font: ${this.opts.fontSizeLarge}pt ${this.opts.fontFamily};\n }\n .sub {\n font: ${this.opts.fontSizeSmall}pt ${this.opts.fontFamily};\n }\n `)),this.svg?this.svg.appendChild(this.style):(this.container=document.createElementNS("http://www.w3.org/2000/svg","g"),container.appendChild(this.style))}constructSvg(){let e=document.createElementNS("http://www.w3.org/2000/svg","defs"),t=document.createElementNS("http://www.w3.org/2000/svg","mask"),r=document.createElementNS("http://www.w3.org/2000/svg","g"),n=document.createElementNS("http://www.w3.org/2000/svg","g"),a=document.createElementNS("http://www.w3.org/2000/svg","g"),i=document.createElementNS("http://www.w3.org/2000/svg","g"),o=this.paths,s=document.createElementNS("http://www.w3.org/2000/svg","rect");s.setAttributeNS(null,"x",this.minX),s.setAttributeNS(null,"y",this.minY),s.setAttributeNS(null,"width",this.maxX-this.minX),s.setAttributeNS(null,"height",this.maxY-this.minY),s.setAttributeNS(null,"fill","white"),t.appendChild(s),t.setAttributeNS(null,"id",this.uid+"-text-mask");for(let e of o)a.appendChild(e);for(let e of this.backgroundItems)r.appendChild(e);for(let e of this.highlights)n.appendChild(e);for(let e of this.vertices)i.appendChild(e);for(let e of this.maskElements)t.appendChild(e);for(let t of this.gradients)e.appendChild(t);if(a.setAttributeNS(null,"mask","url(#"+this.uid+"-text-mask)"),this.updateViewbox(this.opts.scale),r.setAttributeNS(null,"style",`transform: translateX(${this.minX}px) translateY(${this.minY}px)`),!this.svg)return this.container.appendChild(e),this.container.appendChild(t),this.container.appendChild(r),this.container.appendChild(a),this.container.appendChild(i),this.container;this.svg.appendChild(e),this.svg.appendChild(t),this.svg.appendChild(r),this.svg.appendChild(n),this.svg.appendChild(a),this.svg.appendChild(i)}addLayer(e){this.backgroundItems.push(e.firstChild)}createGradient(e){let t=document.createElementNS("http://www.w3.org/2000/svg","linearGradient"),r=this.uid+"-line-"+this.gradientId++,n=e.getLeftVector(),a=e.getRightVector(),i=n.x,o=n.y,s=a.x,l=a.y;t.setAttributeNS(null,"id",r),t.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),t.setAttributeNS(null,"x1",i),t.setAttributeNS(null,"y1",o),t.setAttributeNS(null,"x2",s),t.setAttributeNS(null,"y2",l);let c=document.createElementNS("http://www.w3.org/2000/svg","stop");c.setAttributeNS(null,"stop-color",this.themeManager.getColor(e.getLeftElement())||this.themeManager.getColor("C")),c.setAttributeNS(null,"offset","20%");let d=document.createElementNS("http://www.w3.org/2000/svg","stop");return d.setAttributeNS(null,"stop-color",this.themeManager.getColor(e.getRightElement()||this.themeManager.getColor("C"))),d.setAttributeNS(null,"offset","100%"),t.appendChild(c),t.appendChild(d),this.gradients.push(t),r}createSubSuperScripts(e,t){let r=document.createElementNS("http://www.w3.org/2000/svg","tspan");return r.setAttributeNS(null,"baseline-shift",t),r.appendChild(document.createTextNode(e)),r.setAttributeNS(null,"class","sub"),r}static createUnicodeCharge(t){return 1===t?"⁺":-1===t?"⁻":t>1?e.createUnicodeSuperscript(t)+"⁺":t<-1?e.createUnicodeSuperscript(t)+"⁻":""}determineDimensions(e){for(var t=0;t<e.length;t++){if(!e[t].value.isDrawn)continue;let r=e[t].position;this.maxX<r.x&&(this.maxX=r.x),this.maxY<r.y&&(this.maxY=r.y),this.minX>r.x&&(this.minX=r.x),this.minY>r.y&&(this.minY=r.y)}let r=this.opts.padding;this.maxX+=r,this.maxY+=r,this.minX-=r,this.minY-=r,this.drawingWidth=this.maxX-this.minX,this.drawingHeight=this.maxY-this.minY}updateViewbox(e){let t=this.minX,r=this.minY,n=this.maxX-this.minX,a=this.maxY-this.minY;if(e<=0)if(n>a){let e=n-a;a=n,r-=e/2}else{let e=a-n;n=a,t-=e/2}else this.svg&&(this.svg.style.width=e*n+"px",this.svg.style.height=e*a+"px");this.svg.setAttributeNS(null,"viewBox",`${t} ${r} ${n} ${a}`)}drawBall(e,t,r){let n=this.opts.bondLength/4.5;e-n<this.minX&&(this.minX=e-n),e+n>this.maxX&&(this.maxX=e+n),t-n<this.minY&&(this.minY=t-n),t+n>this.maxY&&(this.maxY=t+n);let a=document.createElementNS("http://www.w3.org/2000/svg","circle");a.setAttributeNS(null,"cx",e),a.setAttributeNS(null,"cy",t),a.setAttributeNS(null,"r",n),a.setAttributeNS(null,"fill",this.themeManager.getColor(r)),this.vertices.push(a)}drawWedge(e){let t=e.getLeftVector().clone(),r=e.getRightVector().clone(),n=ln.normals(t,r);n[0].normalize(),n[1].normalize();let a=t,i=r;e.getRightChiral()&&(a=r,i=t);let o=ln.add(a,ln.multiplyScalar(n[0],this.halfBondThickness)),s=ln.add(i,ln.multiplyScalar(n[0],3+this.opts.fontSizeLarge/4)),l=ln.add(i,ln.multiplyScalar(n[1],3+this.opts.fontSizeLarge/4)),c=ln.add(a,ln.multiplyScalar(n[1],this.halfBondThickness)),d=document.createElementNS("http://www.w3.org/2000/svg","polygon"),u=this.createGradient(e,t.x,t.y,r.x,r.y);d.setAttributeNS(null,"points",`${o.x},${o.y} ${s.x},${s.y} ${l.x},${l.y} ${c.x},${c.y}`),d.setAttributeNS(null,"fill",`url('#${u}')`),this.paths.push(d)}drawAtomHighlight(e,t,r="#03fc9d"){let n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttributeNS(null,"cx",e),n.setAttributeNS(null,"cy",t),n.setAttributeNS(null,"r",this.opts.bondLength/3),n.setAttributeNS(null,"fill",r),this.highlights.push(n)}drawDashedWedge(e){if(isNaN(e.from.x)||isNaN(e.from.y)||isNaN(e.to.x)||isNaN(e.to.y))return;let t,r,n=e.getLeftVector().clone(),a=e.getRightVector().clone(),i=ln.normals(n,a);i[0].normalize(),i[1].normalize(),e.getRightChiral()?(t=a,r=n):(t=n,r=a);let o=ln.subtract(r,t).normalize(),s=e.getLength(),l=1.25/(s/(this.opts.bondLength/10)),c=this.createGradient(e);for(let e=0;e<1;e+=l){let r=ln.multiplyScalar(o,e*s),n=ln.add(t,r),a=this.opts.fontSizeLarge/2*e,l=ln.multiplyScalar(i[0],a);n.subtract(l);let d=n.clone();d.add(ln.multiplyScalar(l,2)),this.drawLine(new sn(n,d),null,c)}}drawDebugPoint(e,t,r="",n="#f00"){let a=document.createElementNS("http://www.w3.org/2000/svg","circle");a.setAttributeNS(null,"cx",e),a.setAttributeNS(null,"cy",t),a.setAttributeNS(null,"r","2"),a.setAttributeNS(null,"fill","#f00"),this.vertices.push(a),this.drawDebugText(e,t,r)}drawDebugText(e,t,r){let n=document.createElementNS("http://www.w3.org/2000/svg","text");n.setAttributeNS(null,"x",e),n.setAttributeNS(null,"y",t),n.setAttributeNS(null,"class","debug"),n.setAttributeNS(null,"fill","#ff0000"),n.setAttributeNS(null,"style","\n font: 5px Droid Sans, sans-serif;\n "),n.appendChild(document.createTextNode(r)),this.vertices.push(n)}drawRing(e,t,r){let n=document.createElementNS("http://www.w3.org/2000/svg","circle"),a=cn.apothemFromSideLength(this.opts.bondLength,r);n.setAttributeNS(null,"cx",e),n.setAttributeNS(null,"cy",t),n.setAttributeNS(null,"r",a-this.opts.bondSpacing),n.setAttributeNS(null,"stroke",this.themeManager.getColor("C")),n.setAttributeNS(null,"stroke-width",this.opts.bondThickness),n.setAttributeNS(null,"fill","none"),this.paths.push(n)}drawLine(e,t=!1,r=null,n="round"){this.opts;let a=[["stroke-width",this.opts.bondThickness],["stroke-linecap",n],["stroke-dasharray",t?"5, 5":"none"]],i=e.getLeftVector(),o=e.getRightVector(),s=i.x,l=i.y,c=o.x,d=o.y,u=a.map(e=>e.join(":")).join(";"),p=document.createElementNS("http://www.w3.org/2000/svg","line");p.setAttributeNS(null,"x1",s),p.setAttributeNS(null,"y1",l),p.setAttributeNS(null,"x2",c),p.setAttributeNS(null,"y2",d),p.setAttributeNS(null,"style",u),this.paths.push(p),null==r&&(r=this.createGradient(e,s,l,c,d)),p.setAttributeNS(null,"stroke",`url('#${r}')`)}drawPoint(e,t,r){let n=.75;e-n<this.minX&&(this.minX=e-n),e+n>this.maxX&&(this.maxX=e+n),t-n<this.minY&&(this.minY=t-n),t+n>this.maxY&&(this.maxY=t+n);let a=document.createElementNS("http://www.w3.org/2000/svg","circle");a.setAttributeNS(null,"cx",e),a.setAttributeNS(null,"cy",t),a.setAttributeNS(null,"r","1.5"),a.setAttributeNS(null,"fill","black"),this.maskElements.push(a);let i=document.createElementNS("http://www.w3.org/2000/svg","circle");i.setAttributeNS(null,"cx",e),i.setAttributeNS(null,"cy",t),i.setAttributeNS(null,"r",n),i.setAttributeNS(null,"fill",this.themeManager.getColor(r)),this.vertices.push(i)}drawText(t,r,n,a,i,o,s,l,c,d={}){let u=[],p=n;0!==s&&null!==s&&(p+=e.createUnicodeCharge(s)),0!==l&&null!==l&&(p=e.createUnicodeSuperscript(l)+p),u.push([p,n]),1===a?u.push(["H","H"]):a>1&&u.push(["H"+e.createUnicodeSubscript(a),"H"]),1===s&&"N"===n&&d.hasOwnProperty("0O")&&d.hasOwnProperty("0O-1")&&(d={"0O":{element:"O",count:2,hydrogenCount:0,previousElement:"C",charge:""}},s=0);for(let t in d){if(!d.hasOwnProperty(t))continue;let r=d[t],n=r.element;r.count>1&&(n+=e.createUnicodeSubscript(r.count)),""!==r.charge&&(n+=e.createUnicodeCharge(s)),u.push([n,r.element]),1===r.hydrogenCount?u.push(["H","H"]):r.hydrogenCount>1&&u.push(["H"+e.createUnicodeSubscript(r.hydrogenCount),"H"])}this.write(u,i,t,r,1===c)}write(t,r,n,a,i){let o=e.measureText(t[0][1],this.opts.fontSizeLarge,this.opts.fontFamily);"left"===r&&t[0][0]!==t[0][1]&&(o.width*=2),i?(n+o.width*t.length>this.maxX&&(this.maxX=n+o.width*t.length),n-o.width/2<this.minX&&(this.minX=n-o.width/2),a-o.height<this.minY&&(this.minY=a-o.height),a+o.height>this.maxY&&(this.maxY=a+o.height)):("right"!==r?(n+o.width*t.length>this.maxX&&(this.maxX=n+o.width*t.length),n-o.width*t.length<this.minX&&(this.minX=n-o.width*t.length)):"left"!==r&&(n+o.width*t.length>this.maxX&&(this.maxX=n+o.width*t.length),n-o.width/2<this.minX&&(this.minX=n-o.width/2)),a-o.height<this.minY&&(this.minY=a-o.height),a+o.height>this.maxY&&(this.maxY=a+o.height),"down"===r&&a+.8*o.height*t.length>this.maxY&&(this.maxY=a+.8*o.height*t.length),"up"===r&&a-.8*o.height*t.length<this.minY&&(this.minY=a-.8*o.height*t.length));let s=n,l=a,c=document.createElementNS("http://www.w3.org/2000/svg","text");c.setAttributeNS(null,"class","element");let d=document.createElementNS("http://www.w3.org/2000/svg","g");c.setAttributeNS(null,"fill","#ffffff"),"left"===r&&(t=t.reverse()),"right"!==r&&"down"!==r&&"up"!==r||(n-=o.width/2),"left"===r&&(n+=o.width/2),t.forEach((e,t)=>{const n=e[0],a=e[1];let i=document.createElementNS("http://www.w3.org/2000/svg","tspan");i.setAttributeNS(null,"fill",this.themeManager.getColor(a)),i.textContent=n,"up"!==r&&"down"!==r||(i.setAttributeNS(null,"x","0px"),"up"===r?i.setAttributeNS(null,"y",`-${.9*t}em`):i.setAttributeNS(null,"y",.9*t+"em")),c.appendChild(i)}),c.setAttributeNS(null,"data-direction",r),"left"===r||"right"===r?(c.setAttributeNS(null,"dominant-baseline","alphabetic"),c.setAttributeNS(null,"y","0.36em")):c.setAttributeNS(null,"dominant-baseline","central"),"left"===r&&c.setAttributeNS(null,"text-anchor","end"),d.appendChild(c),d.setAttributeNS(null,"style",`transform: translateX(${n}px) translateY(${a}px)`);let u=.75*this.opts.fontSizeLarge;t[0][1].length>1&&(u=1.1*this.opts.fontSizeLarge);let p=document.createElementNS("http://www.w3.org/2000/svg","circle");p.setAttributeNS(null,"cx",s),p.setAttributeNS(null,"cy",l),p.setAttributeNS(null,"r",u),p.setAttributeNS(null,"fill","black"),this.maskElements.push(p),this.vertices.push(d)}toCanvas(e,t,r){("string"==typeof e||e instanceof String)&&(e=document.getElementById(e));let n=new Image;n.onload=function(){e.width=t,e.height=r,e.getContext("2d").drawImage(n,0,0,t,r)},n.src="data:image/svg+xml;charset-utf-8,"+encodeURIComponent(this.svg.outerHTML)}static createUnicodeSubscript(e){let t="";return e.toString().split("").forEach(e=>{t+=["₀","₁","₂","₃","₄","₅","₆","₇","₈","₉"][parseInt(e)]}),t}static createUnicodeSuperscript(e){let t="";return e.toString().split("").forEach(e=>{parseInt(e)&&(t+=["⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹"][parseInt(e)])}),t}static replaceNumbersWithSubscript(e){let t={0:"₀",1:"₁",2:"₂",3:"₃",4:"₄",5:"₅",6:"₆",7:"₇",8:"₈",9:"₉"};for(const[r,n]of Object.entries(t))e=e.replaceAll(r,n);return e}static measureText(e,t,r,n=.9){const a=document.createElement("canvas").getContext("2d");a.font=`${t}pt ${r}`;let i=a.measureText(e),o=Math.abs(i.actualBoundingBoxLeft)+Math.abs(i.actualBoundingBoxRight);return{width:i.width>o?i.width:o,height:(Math.abs(i.actualBoundingBoxAscent)+Math.abs(i.actualBoundingBoxAscent))*n}}static svgToCanvas(e,t,r,n,a=null){e.setAttributeNS(null,"width",r),e.setAttributeNS(null,"height",n);let i=new Image;return i.onload=function(){t.width=r,t.height=n;let e=t.getContext("2d");e.imageSmoothingEnabled=!1,e.drawImage(i,0,0,r,n),a&&a(t)},i.onerror=function(e){console.log(e)},i.src="data:image/svg+xml;charset-utf-8,"+encodeURIComponent(e.outerHTML),t}static svgToImg(e,t,r,n){let a=document.createElement("canvas");this.svgToCanvas(e,a,r,n,e=>{t.src=a.toDataURL("image/png")})}static writeText(t,r,n,a,i=Number.MAX_SAFE_INTEGER){let o=document.createElementNS("http://www.w3.org/2000/svg","svg"),s=document.createElementNS("http://www.w3.org/2000/svg","style");s.appendChild(document.createTextNode(`\n .text {\n font: ${n}pt ${a};\n dominant-baseline: ideographic;\n }\n `)),o.appendChild(s);let l=document.createElementNS("http://www.w3.org/2000/svg","text");l.setAttributeNS(null,"class","text");let c=0,d=0,u=[];return t.split("\n").forEach(t=>{let r=e.measureText(t,n,a,1);if(r.width>=i){let r=0,o=0,s=t.split(" "),l=0;for(let t=0;t<s.length;t++){let c=e.measureText(s[t],n,a,1);r+c.width>i&&(u.push({text:s.slice(l,t).join(" "),width:r,height:o}),r=0,o=0,l=t),c.height>o&&(o=c.height),r+=c.width}l<s.length&&u.push({text:s.slice(l,s.length).join(" "),width:r,height:o})}else u.push({text:t,width:r.width,height:r.height})}),u.forEach((e,t)=>{d+=e.height;let n=document.createElementNS("http://www.w3.org/2000/svg","tspan");n.setAttributeNS(null,"fill",r.getColor("C")),n.textContent=e.text,n.setAttributeNS(null,"x","0px"),n.setAttributeNS(null,"y",`${d}px`),l.appendChild(n),e.width>c&&(c=e.width)}),o.appendChild(l),{svg:o,width:c,height:d}}};var un=function(e){function t(e,t){var r=e.length,n=0;if(0===r||r>0&&r-1 in e)for(;n<r&&!1!==t.call(e[n],n,e[n]);n++);else for(n in e)if(!1===t.call(e[n],n,e[n]))break}function r(e){var t=parseInt(e).toString(16);return 1==t.length?"0"+t:t}function n(e,t,n,a){return void 0===(a=parseInt(a))||255===a?"#"+r(e)+r(t)+r(n):0!==a&&"rgba("+e+","+t+","+n+","+a/255+")"}function a(e,t,r){return"M"+e+" "+t+"h"+r}let i=function(e){var t={},r=e.data,n=r.length,a=e.width;e.height;for(var i,o=0,s=0,l=0;l<n;l+=4)r[l+3]>0&&(t[i=r[l]+","+r[l+1]+","+r[l+2]+","+r[l+3]]=t[i]||[],o=l/4%a,s=Math.floor(l/4/a),t[i].push([o,s]));return t}(e),o=function(e){var r="";return t(e,function(e,i){if(!1!==(e=n.apply(null,e.split(",")))){var o,s=[],l=1;t(i,function(){o&&this[1]===o[1]&&this[0]===o[0]+l?l++:(o&&(s.push(a(o[0],o[1],l)),l=1),o=this)}),s.push(a(o[0],o[1],l)),r+=function(e,t){return'<path stroke="'+e+'" d="'+t+'" />\n'}(e,s.join(""))}}),r}(i),s='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -0.5 '+e.width+" "+e.height+'" shape-rendering="crispEdges"><g shape-rendering="crispEdges">'+o+"</g></svg>";var l=document.createElement("div");return l.innerHTML=s,l.firstChild},pn={exports:{}};
+/**
+ * chroma.js - JavaScript library for color conversions
+ *
+ * Copyright (c) 2011-2024, Gregor Aisch
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * 3. The name Gregor Aisch may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * -------------------------------------------------------
+ *
+ * chroma.js includes colors from colorbrewer2.org, which are released under
+ * the following license:
+ *
+ * Copyright (c) 2002 Cynthia Brewer, Mark Harrower,
+ * and The Pennsylvania State University.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific
+ * language governing permissions and limitations under the License.
+ *
+ * ------------------------------------------------------
+ *
+ * Named colors are taken from X11 Color Names.
+ * http://www.w3.org/TR/css3-color/#svg-color
+ *
+ * @preserve
+ */
+!function(e){e.exports=function(){function e(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=1),d(u(t,e),r)}function t(t){t._clipped=!1,t._unclipped=t.slice(0);for(var r=0;r<=3;r++)r<3?((t[r]<0||t[r]>255)&&(t._clipped=!0),t[r]=e(t[r],0,255)):3===r&&(t[r]=e(t[r],0,1));return t}for(var r={},n=0,a=["Boolean","Number","String","Function","Array","Date","RegExp","Undefined","Null"];n<a.length;n+=1){var i=a[n];r["[object "+i+"]"]=i.toLowerCase()}function o(e){return r[Object.prototype.toString.call(e)]||"object"}function s(e,t){return void 0===t&&(t=null),e.length>=3?Array.prototype.slice.call(e):"object"==o(e[0])&&t?t.split("").filter(function(t){return void 0!==e[0][t]}).map(function(t){return e[0][t]}):e[0]}function l(e){if(e.length<2)return null;var t=e.length-1;return"string"==o(e[t])?e[t].toLowerCase():null}var c=Math.PI,d=Math.min,u=Math.max,p=2*c,_=c/3,m=c/180,g=180/c,h={format:{},autodetect:[]},f=function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];var n=this;if("object"===o(e[0])&&e[0].constructor&&e[0].constructor===this.constructor)return e[0];var a=l(e),i=!1;if(!a){i=!0,h.sorted||(h.autodetect=h.autodetect.sort(function(e,t){return t.p-e.p}),h.sorted=!0);for(var s=0,c=h.autodetect;s<c.length;s+=1){var d=c[s];if(a=d.test.apply(d,e))break}}if(!h.format[a])throw new Error("unknown format: "+e);var u=h.format[a].apply(null,i?e:e.slice(0,-1));n._rgb=t(u),3===n._rgb.length&&n._rgb.push(1)};f.prototype.toString=function(){return"function"==o(this.hex)?this.hex():"["+this._rgb.join(",")+"]"};var E="2.6.0",b=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(b.Color,[null].concat(e)))};b.Color=f,b.version=E;var S=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=(e=s(e,"cmyk"))[0],n=e[1],a=e[2],i=e[3],o=e.length>4?e[4]:1;return 1===i?[0,0,0,o]:[r>=1?0:255*(1-r)*(1-i),n>=1?0:255*(1-n)*(1-i),a>=1?0:255*(1-a)*(1-i),o]},v=Math.max,T=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgb"),n=r[0],a=r[1],i=r[2],o=1-v(n/=255,v(a/=255,i/=255)),l=o<1?1/(1-o):0;return[(1-n-o)*l,(1-a-o)*l,(1-i-o)*l,o]};f.prototype.cmyk=function(){return T(this._rgb)},b.cmyk=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["cmyk"])))},h.format.cmyk=S,h.autodetect.push({p:2,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if("array"===o(e=s(e,"cmyk"))&&4===e.length)return"cmyk"}});var y=function(e){return Math.round(100*e)/100},C=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"hsla"),n=l(e)||"lsa";return r[0]=y(r[0]||0),r[1]=y(100*r[1])+"%",r[2]=y(100*r[2])+"%","hsla"===n||r.length>3&&r[3]<1?(r[3]=r.length>3?r[3]:1,n="hsla"):r.length=3,n+"("+r.join(",")+")"},N=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r,n,a=(e=s(e,"rgba"))[0],i=e[1],o=e[2],l=d(a/=255,i/=255,o/=255),c=u(a,i,o),p=(c+l)/2;return c===l?(r=0,n=Number.NaN):r=p<.5?(c-l)/(c+l):(c-l)/(2-c-l),a==c?n=(i-o)/(c-l):i==c?n=2+(o-a)/(c-l):o==c&&(n=4+(a-i)/(c-l)),(n*=60)<0&&(n+=360),e.length>3&&void 0!==e[3]?[n,r,p,e[3]]:[n,r,p]},R=Math.round,A=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgba"),n=l(e)||"rgb";return"hsl"==n.substr(0,3)?C(N(r),n):(r[0]=R(r[0]),r[1]=R(r[1]),r[2]=R(r[2]),("rgba"===n||r.length>3&&r[3]<1)&&(r[3]=r.length>3?r[3]:1,n="rgba"),n+"("+r.slice(0,"rgb"===n?3:4).join(",")+")")},O=Math.round,I=function(){for(var e,t=[],r=arguments.length;r--;)t[r]=arguments[r];var n,a,i,o=(t=s(t,"hsl"))[0],l=t[1],c=t[2];if(0===l)n=a=i=255*c;else{var d=[0,0,0],u=[0,0,0],p=c<.5?c*(1+l):c+l-c*l,_=2*c-p,m=o/360;d[0]=m+1/3,d[1]=m,d[2]=m-1/3;for(var g=0;g<3;g++)d[g]<0&&(d[g]+=1),d[g]>1&&(d[g]-=1),6*d[g]<1?u[g]=_+6*(p-_)*d[g]:2*d[g]<1?u[g]=p:3*d[g]<2?u[g]=_+(p-_)*(2/3-d[g])*6:u[g]=_;n=(e=[O(255*u[0]),O(255*u[1]),O(255*u[2])])[0],a=e[1],i=e[2]}return t.length>3?[n,a,i,t[3]]:[n,a,i,1]},x=/^rgb\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*\)$/,w=/^rgba\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*([01]|[01]?\.\d+)\)$/,D=/^rgb\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,M=/^rgba\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,k=/^hsl\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,L=/^hsla\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,P=Math.round,F=function(e){var t;if(e=e.toLowerCase().trim(),h.format.named)try{return h.format.named(e)}catch(e){}if(t=e.match(x)){for(var r=t.slice(1,4),n=0;n<3;n++)r[n]=+r[n];return r[3]=1,r}if(t=e.match(w)){for(var a=t.slice(1,5),i=0;i<4;i++)a[i]=+a[i];return a}if(t=e.match(D)){for(var o=t.slice(1,4),s=0;s<3;s++)o[s]=P(2.55*o[s]);return o[3]=1,o}if(t=e.match(M)){for(var l=t.slice(1,5),c=0;c<3;c++)l[c]=P(2.55*l[c]);return l[3]=+l[3],l}if(t=e.match(k)){var d=t.slice(1,4);d[1]*=.01,d[2]*=.01;var u=I(d);return u[3]=1,u}if(t=e.match(L)){var p=t.slice(1,4);p[1]*=.01,p[2]*=.01;var _=I(p);return _[3]=+t[4],_}};F.test=function(e){return x.test(e)||w.test(e)||D.test(e)||M.test(e)||k.test(e)||L.test(e)},f.prototype.css=function(e){return A(this._rgb,e)},b.css=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["css"])))},h.format.css=F,h.autodetect.push({p:5,test:function(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];if(!t.length&&"string"===o(e)&&F.test(e))return"css"}}),h.format.gl=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgba");return r[0]*=255,r[1]*=255,r[2]*=255,r},b.gl=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["gl"])))},f.prototype.gl=function(){var e=this._rgb;return[e[0]/255,e[1]/255,e[2]/255,e[3]]};var B=Math.floor,U=function(){for(var e,t,r,n,a,i,o=[],l=arguments.length;l--;)o[l]=arguments[l];var c,d,u,p=(o=s(o,"hcg"))[0],_=o[1],m=o[2];m*=255;var g=255*_;if(0===_)c=d=u=m;else{360===p&&(p=0),p>360&&(p-=360),p<0&&(p+=360);var h=B(p/=60),f=p-h,E=m*(1-_),b=E+g*(1-f),S=E+g*f,v=E+g;switch(h){case 0:c=(e=[v,S,E])[0],d=e[1],u=e[2];break;case 1:c=(t=[b,v,E])[0],d=t[1],u=t[2];break;case 2:c=(r=[E,v,S])[0],d=r[1],u=r[2];break;case 3:c=(n=[E,b,v])[0],d=n[1],u=n[2];break;case 4:c=(a=[S,E,v])[0],d=a[1],u=a[2];break;case 5:c=(i=[v,E,b])[0],d=i[1],u=i[2]}}return[c,d,u,o.length>3?o[3]:1]},G=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r,n=s(e,"rgb"),a=n[0],i=n[1],o=n[2],l=d(a,i,o),c=u(a,i,o),p=c-l,_=100*p/255,m=l/(255-p)*100;return 0===p?r=Number.NaN:(a===c&&(r=(i-o)/p),i===c&&(r=2+(o-a)/p),o===c&&(r=4+(a-i)/p),(r*=60)<0&&(r+=360)),[r,_,m]};f.prototype.hcg=function(){return G(this._rgb)},b.hcg=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["hcg"])))},h.format.hcg=U,h.autodetect.push({p:1,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if("array"===o(e=s(e,"hcg"))&&3===e.length)return"hcg"}});var z=/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,Y=/^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$/,q=function(e){if(e.match(z)){4!==e.length&&7!==e.length||(e=e.substr(1)),3===e.length&&(e=(e=e.split(""))[0]+e[0]+e[1]+e[1]+e[2]+e[2]);var t=parseInt(e,16);return[t>>16,t>>8&255,255&t,1]}if(e.match(Y)){5!==e.length&&9!==e.length||(e=e.substr(1)),4===e.length&&(e=(e=e.split(""))[0]+e[0]+e[1]+e[1]+e[2]+e[2]+e[3]+e[3]);var r=parseInt(e,16);return[r>>24&255,r>>16&255,r>>8&255,Math.round((255&r)/255*100)/100]}throw new Error("unknown hex color: "+e)},H=Math.round,V=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgba"),n=r[0],a=r[1],i=r[2],o=r[3],c=l(e)||"auto";void 0===o&&(o=1),"auto"===c&&(c=o<1?"rgba":"rgb");var d="000000"+((n=H(n))<<16|(a=H(a))<<8|(i=H(i))).toString(16);d=d.substr(d.length-6);var u="0"+H(255*o).toString(16);switch(u=u.substr(u.length-2),c.toLowerCase()){case"rgba":return"#"+d+u;case"argb":return"#"+u+d;default:return"#"+d}};f.prototype.hex=function(e){return V(this._rgb,e)},b.hex=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["hex"])))},h.format.hex=q,h.autodetect.push({p:4,test:function(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];if(!t.length&&"string"===o(e)&&[3,4,5,6,7,8,9].indexOf(e.length)>=0)return"hex"}});var $=Math.cos,W=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];var n,a,i,o=(t=s(t,"hsi"))[0],l=t[1],c=t[2];return isNaN(o)&&(o=0),isNaN(l)&&(l=0),o>360&&(o-=360),o<0&&(o+=360),(o/=360)<1/3?a=1-((i=(1-l)/3)+(n=(1+l*$(p*o)/$(_-p*o))/3)):o<2/3?i=1-((n=(1-l)/3)+(a=(1+l*$(p*(o-=1/3))/$(_-p*o))/3)):n=1-((a=(1-l)/3)+(i=(1+l*$(p*(o-=2/3))/$(_-p*o))/3)),[255*(n=e(c*n*3)),255*(a=e(c*a*3)),255*(i=e(c*i*3)),t.length>3?t[3]:1]},j=Math.min,Q=Math.sqrt,K=Math.acos,X=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r,n=s(e,"rgb"),a=n[0],i=n[1],o=n[2],l=j(a/=255,i/=255,o/=255),c=(a+i+o)/3,d=c>0?1-l/c:0;return 0===d?r=NaN:(r=(a-i+(a-o))/2,r/=Q((a-i)*(a-i)+(a-o)*(i-o)),r=K(r),o>i&&(r=p-r),r/=p),[360*r,d,c]};f.prototype.hsi=function(){return X(this._rgb)},b.hsi=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["hsi"])))},h.format.hsi=W,h.autodetect.push({p:2,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if("array"===o(e=s(e,"hsi"))&&3===e.length)return"hsi"}}),f.prototype.hsl=function(){return N(this._rgb)},b.hsl=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["hsl"])))},h.format.hsl=I,h.autodetect.push({p:2,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if("array"===o(e=s(e,"hsl"))&&3===e.length)return"hsl"}});var Z=Math.floor,J=function(){for(var e,t,r,n,a,i,o=[],l=arguments.length;l--;)o[l]=arguments[l];var c,d,u,p=(o=s(o,"hsv"))[0],_=o[1],m=o[2];if(m*=255,0===_)c=d=u=m;else{360===p&&(p=0),p>360&&(p-=360),p<0&&(p+=360);var g=Z(p/=60),h=p-g,f=m*(1-_),E=m*(1-_*h),b=m*(1-_*(1-h));switch(g){case 0:c=(e=[m,b,f])[0],d=e[1],u=e[2];break;case 1:c=(t=[E,m,f])[0],d=t[1],u=t[2];break;case 2:c=(r=[f,m,b])[0],d=r[1],u=r[2];break;case 3:c=(n=[f,E,m])[0],d=n[1],u=n[2];break;case 4:c=(a=[b,f,m])[0],d=a[1],u=a[2];break;case 5:c=(i=[m,f,E])[0],d=i[1],u=i[2]}}return[c,d,u,o.length>3?o[3]:1]},ee=Math.min,te=Math.max,re=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r,n,a,i=(e=s(e,"rgb"))[0],o=e[1],l=e[2],c=ee(i,o,l),d=te(i,o,l),u=d-c;return a=d/255,0===d?(r=Number.NaN,n=0):(n=u/d,i===d&&(r=(o-l)/u),o===d&&(r=2+(l-i)/u),l===d&&(r=4+(i-o)/u),(r*=60)<0&&(r+=360)),[r,n,a]};f.prototype.hsv=function(){return re(this._rgb)},b.hsv=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["hsv"])))},h.format.hsv=J,h.autodetect.push({p:2,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if("array"===o(e=s(e,"hsv"))&&3===e.length)return"hsv"}});var ne={Kn:18,Xn:.95047,Yn:1,Zn:1.08883,t0:.137931034,t1:.206896552,t2:.12841855,t3:.008856452},ae=Math.pow,ie=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r,n,a,i=(e=s(e,"lab"))[0],o=e[1],l=e[2];return n=(i+16)/116,r=isNaN(o)?n:n+o/500,a=isNaN(l)?n:n-l/200,n=ne.Yn*se(n),r=ne.Xn*se(r),a=ne.Zn*se(a),[oe(3.2404542*r-1.5371385*n-.4985314*a),oe(-.969266*r+1.8760108*n+.041556*a),oe(.0556434*r-.2040259*n+1.0572252*a),e.length>3?e[3]:1]},oe=function(e){return 255*(e<=.00304?12.92*e:1.055*ae(e,1/2.4)-.055)},se=function(e){return e>ne.t1?e*e*e:ne.t2*(e-ne.t0)},le=Math.pow,ce=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgb"),n=r[0],a=r[1],i=r[2],o=pe(n,a,i),l=o[0],c=o[1],d=116*c-16;return[d<0?0:d,500*(l-c),200*(c-o[2])]},de=function(e){return(e/=255)<=.04045?e/12.92:le((e+.055)/1.055,2.4)},ue=function(e){return e>ne.t3?le(e,1/3):e/ne.t2+ne.t0},pe=function(e,t,r){return e=de(e),t=de(t),r=de(r),[ue((.4124564*e+.3575761*t+.1804375*r)/ne.Xn),ue((.2126729*e+.7151522*t+.072175*r)/ne.Yn),ue((.0193339*e+.119192*t+.9503041*r)/ne.Zn)]};f.prototype.lab=function(){return ce(this._rgb)},b.lab=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["lab"])))},h.format.lab=ie,h.autodetect.push({p:2,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if("array"===o(e=s(e,"lab"))&&3===e.length)return"lab"}});var _e=Math.sin,me=Math.cos,ge=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"lch"),n=r[0],a=r[1],i=r[2];return isNaN(i)&&(i=0),[n,me(i*=m)*a,_e(i)*a]},he=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=(e=s(e,"lch"))[0],n=e[1],a=e[2],i=ge(r,n,a),o=i[0],l=i[1],c=i[2],d=ie(o,l,c);return[d[0],d[1],d[2],e.length>3?e[3]:1]},fe=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"hcl").reverse();return he.apply(void 0,r)},Ee=Math.sqrt,be=Math.atan2,Se=Math.round,ve=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"lab"),n=r[0],a=r[1],i=r[2],o=Ee(a*a+i*i),l=(be(i,a)*g+360)%360;return 0===Se(1e4*o)&&(l=Number.NaN),[n,o,l]},Te=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgb"),n=r[0],a=r[1],i=r[2],o=ce(n,a,i),l=o[0],c=o[1],d=o[2];return ve(l,c,d)};f.prototype.lch=function(){return Te(this._rgb)},f.prototype.hcl=function(){return Te(this._rgb).reverse()},b.lch=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["lch"])))},b.hcl=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["hcl"])))},h.format.lch=he,h.format.hcl=fe,["lch","hcl"].forEach(function(e){return h.autodetect.push({p:2,test:function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];if("array"===o(t=s(t,e))&&3===t.length)return e}})});var ye={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",laserlemon:"#ffff54",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrod:"#fafad2",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",maroon2:"#7f0000",maroon3:"#b03060",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",purple2:"#7f007f",purple3:"#a020f0",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};f.prototype.name=function(){for(var e=V(this._rgb,"rgb"),t=0,r=Object.keys(ye);t<r.length;t+=1){var n=r[t];if(ye[n]===e)return n.toLowerCase()}return e},h.format.named=function(e){if(e=e.toLowerCase(),ye[e])return q(ye[e]);throw new Error("unknown color name: "+e)},h.autodetect.push({p:5,test:function(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];if(!t.length&&"string"===o(e)&&ye[e.toLowerCase()])return"named"}});var Ce=function(e){if("number"==o(e)&&e>=0&&e<=16777215)return[e>>16,e>>8&255,255&e,1];throw new Error("unknown num color: "+e)},Ne=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgb");return(r[0]<<16)+(r[1]<<8)+r[2]};f.prototype.num=function(){return Ne(this._rgb)},b.num=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["num"])))},h.format.num=Ce,h.autodetect.push({p:5,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if(1===e.length&&"number"===o(e[0])&&e[0]>=0&&e[0]<=16777215)return"num"}});var Re=Math.round;f.prototype.rgb=function(e){return void 0===e&&(e=!0),!1===e?this._rgb.slice(0,3):this._rgb.slice(0,3).map(Re)},f.prototype.rgba=function(e){return void 0===e&&(e=!0),this._rgb.slice(0,4).map(function(t,r){return r<3?!1===e?t:Re(t):t})},b.rgb=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["rgb"])))},h.format.rgb=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgba");return void 0===r[3]&&(r[3]=1),r},h.autodetect.push({p:3,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if("array"===o(e=s(e,"rgba"))&&(3===e.length||4===e.length&&"number"==o(e[3])&&e[3]>=0&&e[3]<=1))return"rgb"}});var Ae=Math.log,Oe=function(e){var t,r,n,a=e/100;return a<66?(t=255,r=a<6?0:-155.25485562709179-.44596950469579133*(r=a-2)+104.49216199393888*Ae(r),n=a<20?0:.8274096064007395*(n=a-10)-254.76935184120902+115.67994401066147*Ae(n)):(t=351.97690566805693+.114206453784165*(t=a-55)-40.25366309332127*Ae(t),r=325.4494125711974+.07943456536662342*(r=a-50)-28.0852963507957*Ae(r),n=255),[t,r,n,1]},Ie=Math.round,xe=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var r,n=s(e,"rgb"),a=n[0],i=n[2],o=1e3,l=4e4,c=.4;l-o>c;){var d=Oe(r=.5*(l+o));d[2]/d[0]>=i/a?l=r:o=r}return Ie(r)};f.prototype.temp=f.prototype.kelvin=f.prototype.temperature=function(){return xe(this._rgb)},b.temp=b.kelvin=b.temperature=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["temp"])))},h.format.temp=h.format.kelvin=h.format.temperature=Oe;var we=Math.pow,De=Math.sign,Me=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=(e=s(e,"lab"))[0],n=e[1],a=e[2],i=we(r+.3963377774*n+.2158037573*a,3),o=we(r-.1055613458*n-.0638541728*a,3),l=we(r-.0894841775*n-1.291485548*a,3);return[255*ke(4.0767416621*i-3.3077115913*o+.2309699292*l),255*ke(-1.2684380046*i+2.6097574011*o-.3413193965*l),255*ke(-.0041960863*i-.7034186147*o+1.707614701*l),e.length>3?e[3]:1]};function ke(e){var t=Math.abs(e);return t>.0031308?(De(e)||1)*(1.055*we(t,1/2.4)-.055):12.92*e}var Le=Math.cbrt,Pe=Math.pow,Fe=Math.sign,Be=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgb"),n=r[0],a=r[1],i=r[2],o=[Ue(n/255),Ue(a/255),Ue(i/255)],l=o[0],c=o[1],d=o[2],u=Le(.4122214708*l+.5363325363*c+.0514459929*d),p=Le(.2119034982*l+.6806995451*c+.1073969566*d),_=Le(.0883024619*l+.2817188376*c+.6299787005*d);return[.2104542553*u+.793617785*p-.0040720468*_,1.9779984951*u-2.428592205*p+.4505937099*_,.0259040371*u+.7827717662*p-.808675766*_]};function Ue(e){var t=Math.abs(e);return t<.04045?e/12.92:(Fe(e)||1)*Pe((t+.055)/1.055,2.4)}f.prototype.oklab=function(){return Be(this._rgb)},b.oklab=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["oklab"])))},h.format.oklab=Me,h.autodetect.push({p:3,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if("array"===o(e=s(e,"oklab"))&&3===e.length)return"oklab"}});var Ge=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=(e=s(e,"lch"))[0],n=e[1],a=e[2],i=ge(r,n,a),o=i[0],l=i[1],c=i[2],d=Me(o,l,c);return[d[0],d[1],d[2],e.length>3?e[3]:1]},ze=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var r=s(e,"rgb"),n=r[0],a=r[1],i=r[2],o=Be(n,a,i),l=o[0],c=o[1],d=o[2];return ve(l,c,d)};f.prototype.oklch=function(){return ze(this._rgb)},b.oklch=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return new(Function.prototype.bind.apply(f,[null].concat(e,["oklch"])))},h.format.oklch=Ge,h.autodetect.push({p:3,test:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];if("array"===o(e=s(e,"oklch"))&&3===e.length)return"oklch"}}),f.prototype.alpha=function(e,t){return void 0===t&&(t=!1),void 0!==e&&"number"===o(e)?t?(this._rgb[3]=e,this):new f([this._rgb[0],this._rgb[1],this._rgb[2],e],"rgb"):this._rgb[3]},f.prototype.clipped=function(){return this._rgb._clipped||!1},f.prototype.darken=function(e){void 0===e&&(e=1);var t=this,r=t.lab();return r[0]-=ne.Kn*e,new f(r,"lab").alpha(t.alpha(),!0)},f.prototype.brighten=function(e){return void 0===e&&(e=1),this.darken(-e)},f.prototype.darker=f.prototype.darken,f.prototype.brighter=f.prototype.brighten,f.prototype.get=function(e){var t=e.split("."),r=t[0],n=t[1],a=this[r]();if(n){var i=r.indexOf(n)-("ok"===r.substr(0,2)?2:0);if(i>-1)return a[i];throw new Error("unknown channel "+n+" in mode "+r)}return a};var Ye=Math.pow,qe=1e-7,He=20;f.prototype.luminance=function(e,t){if(void 0===t&&(t="rgb"),void 0!==e&&"number"===o(e)){if(0===e)return new f([0,0,0,this._rgb[3]],"rgb");if(1===e)return new f([255,255,255,this._rgb[3]],"rgb");var r=this.luminance(),n=He,a=function(r,i){var o=r.interpolate(i,.5,t),s=o.luminance();return Math.abs(e-s)<qe||!n--?o:s>e?a(r,o):a(o,i)},i=(r>e?a(new f([0,0,0]),this):a(this,new f([255,255,255]))).rgb();return new f(i.concat([this._rgb[3]]))}return Ve.apply(void 0,this._rgb.slice(0,3))};var Ve=function(e,t,r){return.2126*(e=$e(e))+.7152*(t=$e(t))+.0722*(r=$e(r))},$e=function(e){return(e/=255)<=.03928?e/12.92:Ye((e+.055)/1.055,2.4)},We={};function je(e,t,r){void 0===r&&(r=.5);for(var n=[],a=arguments.length-3;a-- >0;)n[a]=arguments[a+3];var i=n[0]||"lrgb";if(We[i]||n.length||(i=Object.keys(We)[0]),!We[i])throw new Error("interpolation mode "+i+" is not defined");return"object"!==o(e)&&(e=new f(e)),"object"!==o(t)&&(t=new f(t)),We[i](e,t,r).alpha(e.alpha()+r*(t.alpha()-e.alpha()))}f.prototype.mix=f.prototype.interpolate=function(e,t){void 0===t&&(t=.5);for(var r=[],n=arguments.length-2;n-- >0;)r[n]=arguments[n+2];return je.apply(void 0,[this,e,t].concat(r))},f.prototype.premultiply=function(e){void 0===e&&(e=!1);var t=this._rgb,r=t[3];return e?(this._rgb=[t[0]*r,t[1]*r,t[2]*r,r],this):new f([t[0]*r,t[1]*r,t[2]*r,r],"rgb")},f.prototype.saturate=function(e){void 0===e&&(e=1);var t=this,r=t.lch();return r[1]+=ne.Kn*e,r[1]<0&&(r[1]=0),new f(r,"lch").alpha(t.alpha(),!0)},f.prototype.desaturate=function(e){return void 0===e&&(e=1),this.saturate(-e)},f.prototype.set=function(e,t,r){void 0===r&&(r=!1);var n=e.split("."),a=n[0],i=n[1],s=this[a]();if(i){var l=a.indexOf(i)-("ok"===a.substr(0,2)?2:0);if(l>-1){if("string"==o(t))switch(t.charAt(0)){case"+":case"-":s[l]+=+t;break;case"*":s[l]*=+t.substr(1);break;case"/":s[l]/=+t.substr(1);break;default:s[l]=+t}else{if("number"!==o(t))throw new Error("unsupported value for Color.set");s[l]=t}var c=new f(s,a);return r?(this._rgb=c._rgb,this):c}throw new Error("unknown channel "+i+" in mode "+a)}return s},f.prototype.tint=function(e){void 0===e&&(e=.5);for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return je.apply(void 0,[this,"white",e].concat(t))},f.prototype.shade=function(e){void 0===e&&(e=.5);for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return je.apply(void 0,[this,"black",e].concat(t))};var Qe=function(e,t,r){var n=e._rgb,a=t._rgb;return new f(n[0]+r*(a[0]-n[0]),n[1]+r*(a[1]-n[1]),n[2]+r*(a[2]-n[2]),"rgb")};We.rgb=Qe;var Ke=Math.sqrt,Xe=Math.pow,Ze=function(e,t,r){var n=e._rgb,a=n[0],i=n[1],o=n[2],s=t._rgb,l=s[0],c=s[1],d=s[2];return new f(Ke(Xe(a,2)*(1-r)+Xe(l,2)*r),Ke(Xe(i,2)*(1-r)+Xe(c,2)*r),Ke(Xe(o,2)*(1-r)+Xe(d,2)*r),"rgb")};We.lrgb=Ze;var Je=function(e,t,r){var n=e.lab(),a=t.lab();return new f(n[0]+r*(a[0]-n[0]),n[1]+r*(a[1]-n[1]),n[2]+r*(a[2]-n[2]),"lab")};function et(e,t,r,n){var a,i,o,s,l,c,d,u,p,_,m,g,h;return"hsl"===n?(o=e.hsl(),s=t.hsl()):"hsv"===n?(o=e.hsv(),s=t.hsv()):"hcg"===n?(o=e.hcg(),s=t.hcg()):"hsi"===n?(o=e.hsi(),s=t.hsi()):"lch"===n||"hcl"===n?(n="hcl",o=e.hcl(),s=t.hcl()):"oklch"===n&&(o=e.oklch().reverse(),s=t.oklch().reverse()),"h"!==n.substr(0,1)&&"oklch"!==n||(l=(a=o)[0],d=a[1],p=a[2],c=(i=s)[0],u=i[1],_=i[2]),isNaN(l)||isNaN(c)?isNaN(l)?isNaN(c)?g=Number.NaN:(g=c,1!=p&&0!=p||"hsv"==n||(m=u)):(g=l,1!=_&&0!=_||"hsv"==n||(m=d)):g=l+r*(c>l&&c-l>180?c-(l+360):c<l&&l-c>180?c+360-l:c-l),void 0===m&&(m=d+r*(u-d)),h=p+r*(_-p),new f("oklch"===n?[h,m,g]:[g,m,h],n)}We.lab=Je;var tt=function(e,t,r){return et(e,t,r,"lch")};We.lch=tt,We.hcl=tt;var rt=function(e,t,r){var n=e.num(),a=t.num();return new f(n+r*(a-n),"num")};We.num=rt;var nt=function(e,t,r){return et(e,t,r,"hcg")};We.hcg=nt;var at=function(e,t,r){return et(e,t,r,"hsi")};We.hsi=at;var it=function(e,t,r){return et(e,t,r,"hsl")};We.hsl=it;var ot=function(e,t,r){return et(e,t,r,"hsv")};We.hsv=ot;var st=function(e,t,r){var n=e.oklab(),a=t.oklab();return new f(n[0]+r*(a[0]-n[0]),n[1]+r*(a[1]-n[1]),n[2]+r*(a[2]-n[2]),"oklab")};We.oklab=st;var lt=function(e,t,r){return et(e,t,r,"oklch")};We.oklch=lt;var ct=Math.pow,dt=Math.sqrt,ut=Math.PI,pt=Math.cos,_t=Math.sin,mt=Math.atan2;function gt(e,t,r){void 0===t&&(t="lrgb"),void 0===r&&(r=null);var n=e.length;r||(r=Array.from(new Array(n)).map(function(){return 1}));var a=n/r.reduce(function(e,t){return e+t});if(r.forEach(function(e,t){r[t]*=a}),e=e.map(function(e){return new f(e)}),"lrgb"===t)return ht(e,r);for(var i=e.shift(),o=i.get(t),s=[],l=0,c=0,d=0;d<o.length;d++)if(o[d]=(o[d]||0)*r[0],s.push(isNaN(o[d])?0:r[0]),"h"===t.charAt(d)&&!isNaN(o[d])){var u=o[d]/180*ut;l+=pt(u)*r[0],c+=_t(u)*r[0]}var p=i.alpha()*r[0];e.forEach(function(e,n){var a=e.get(t);p+=e.alpha()*r[n+1];for(var i=0;i<o.length;i++)if(!isNaN(a[i]))if(s[i]+=r[n+1],"h"===t.charAt(i)){var d=a[i]/180*ut;l+=pt(d)*r[n+1],c+=_t(d)*r[n+1]}else o[i]+=a[i]*r[n+1]});for(var _=0;_<o.length;_++)if("h"===t.charAt(_)){for(var m=mt(c/s[_],l/s[_])/ut*180;m<0;)m+=360;for(;m>=360;)m-=360;o[_]=m}else o[_]=o[_]/s[_];return p/=n,new f(o,t).alpha(p>.99999?1:p,!0)}var ht=function(e,r){for(var n=e.length,a=[0,0,0,0],i=0;i<e.length;i++){var o=e[i],s=r[i]/n,l=o._rgb;a[0]+=ct(l[0],2)*s,a[1]+=ct(l[1],2)*s,a[2]+=ct(l[2],2)*s,a[3]+=l[3]*s}return a[0]=dt(a[0]),a[1]=dt(a[1]),a[2]=dt(a[2]),a[3]>.9999999&&(a[3]=1),new f(t(a))},ft=Math.pow;function Et(t){var r="rgb",n=b("#ccc"),a=0,i=[0,1],s=[],l=[0,0],c=!1,d=[],u=!1,p=0,_=1,m=!1,g={},h=!0,f=1,E=function(e){if((e=e||["#fff","#000"])&&"string"===o(e)&&b.brewer&&b.brewer[e.toLowerCase()]&&(e=b.brewer[e.toLowerCase()]),"array"===o(e)){1===e.length&&(e=[e[0],e[0]]),e=e.slice(0);for(var t=0;t<e.length;t++)e[t]=b(e[t]);s.length=0;for(var r=0;r<e.length;r++)s.push(r/(e.length-1))}return C(),d=e},S=function(e){if(null!=c){for(var t=c.length-1,r=0;r<t&&e>=c[r];)r++;return r-1}return 0},v=function(e){return e},T=function(e){return e},y=function(t,a){var i,u;if(null==a&&(a=!1),isNaN(t)||null===t)return n;u=a?t:c&&c.length>2?S(t)/(c.length-2):_!==p?(t-p)/(_-p):1,u=T(u),a||(u=v(u)),1!==f&&(u=ft(u,f)),u=e(u=l[0]+u*(1-l[0]-l[1]),0,1);var m=Math.floor(1e4*u);if(h&&g[m])i=g[m];else{if("array"===o(d))for(var E=0;E<s.length;E++){var y=s[E];if(u<=y){i=d[E];break}if(u>=y&&E===s.length-1){i=d[E];break}if(u>y&&u<s[E+1]){u=(u-y)/(s[E+1]-y),i=b.interpolate(d[E],d[E+1],u,r);break}}else"function"===o(d)&&(i=d(u));h&&(g[m]=i)}return i},C=function(){return g={}};E(t);var N=function(e){var t=b(y(e));return u&&t[u]?t[u]():t};return N.classes=function(e){if(null!=e){if("array"===o(e))c=e,i=[e[0],e[e.length-1]];else{var t=b.analyze(i);c=0===e?[t.min,t.max]:b.limits(t,"e",e)}return N}return c},N.domain=function(e){if(!arguments.length)return i;p=e[0],_=e[e.length-1],s=[];var t=d.length;if(e.length===t&&p!==_)for(var r=0,n=Array.from(e);r<n.length;r+=1){var a=n[r];s.push((a-p)/(_-p))}else{for(var o=0;o<t;o++)s.push(o/(t-1));if(e.length>2){var l=e.map(function(t,r){return r/(e.length-1)}),c=e.map(function(e){return(e-p)/(_-p)});c.every(function(e,t){return l[t]===e})||(T=function(e){if(e<=0||e>=1)return e;for(var t=0;e>=c[t+1];)t++;var r=(e-c[t])/(c[t+1]-c[t]);return l[t]+r*(l[t+1]-l[t])})}}return i=[p,_],N},N.mode=function(e){return arguments.length?(r=e,C(),N):r},N.range=function(e,t){return E(e),N},N.out=function(e){return u=e,N},N.spread=function(e){return arguments.length?(a=e,N):a},N.correctLightness=function(e){return null==e&&(e=!0),m=e,C(),v=m?function(e){for(var t=y(0,!0).lab()[0],r=y(1,!0).lab()[0],n=t>r,a=y(e,!0).lab()[0],i=t+(r-t)*e,o=a-i,s=0,l=1,c=20;Math.abs(o)>.01&&c-- >0;)(function(){n&&(o*=-1),o<0?(s=e,e+=.5*(l-e)):(l=e,e+=.5*(s-e)),a=y(e,!0).lab()[0],o=a-i})();return e}:function(e){return e},N},N.padding=function(e){return null!=e?("number"===o(e)&&(e=[e,e]),l=e,N):l},N.colors=function(e,r){arguments.length<2&&(r="hex");var n=[];if(0===arguments.length)n=d.slice(0);else if(1===e)n=[N(.5)];else if(e>1){var a=i[0],o=i[1]-a;n=bt(0,e).map(function(t){return N(a+t/(e-1)*o)})}else{t=[];var s=[];if(c&&c.length>2)for(var l=1,u=c.length,p=1<=u;p?l<u:l>u;p?l++:l--)s.push(.5*(c[l-1]+c[l]));else s=i;n=s.map(function(e){return N(e)})}return b[r]&&(n=n.map(function(e){return e[r]()})),n},N.cache=function(e){return null!=e?(h=e,N):h},N.gamma=function(e){return null!=e?(f=e,N):f},N.nodata=function(e){return null!=e?(n=b(e),N):n},N}function bt(e,t,r){for(var n=[],a=e<t,i=t,o=e;a?o<i:o>i;a?o++:o--)n.push(o);return n}var St=function(e){for(var t=[1,1],r=1;r<e;r++){for(var n=[1],a=1;a<=t.length;a++)n[a]=(t[a]||0)+t[a-1];t=n}return t},vt=function(e){var t,r,n,a,i,o,s;if(2===(e=e.map(function(e){return new f(e)})).length)t=e.map(function(e){return e.lab()}),i=t[0],o=t[1],a=function(e){var t=[0,1,2].map(function(t){return i[t]+e*(o[t]-i[t])});return new f(t,"lab")};else if(3===e.length)r=e.map(function(e){return e.lab()}),i=r[0],o=r[1],s=r[2],a=function(e){var t=[0,1,2].map(function(t){return(1-e)*(1-e)*i[t]+2*(1-e)*e*o[t]+e*e*s[t]});return new f(t,"lab")};else if(4===e.length){var l;n=e.map(function(e){return e.lab()}),i=n[0],o=n[1],s=n[2],l=n[3],a=function(e){var t=[0,1,2].map(function(t){return(1-e)*(1-e)*(1-e)*i[t]+3*(1-e)*(1-e)*e*o[t]+3*(1-e)*e*e*s[t]+e*e*e*l[t]});return new f(t,"lab")}}else{if(!(e.length>=5))throw new RangeError("No point in running bezier with only one color.");var c,d,u;c=e.map(function(e){return e.lab()}),u=e.length-1,d=St(u),a=function(e){var t=1-e,r=[0,1,2].map(function(r){return c.reduce(function(n,a,i){return n+d[i]*Math.pow(t,u-i)*Math.pow(e,i)*a[r]},0)});return new f(r,"lab")}}return a};function Tt(e){var t=vt(e);return t.scale=function(){return Et(t)},t}var yt=function(e,t,r){if(!yt[r])throw new Error("unknown blend mode "+r);return yt[r](e,t)},Ct=function(e){return function(t,r){var n=b(r).rgb(),a=b(t).rgb();return b.rgb(e(n,a))}},Nt=function(e){return function(t,r){var n=[];return n[0]=e(t[0],r[0]),n[1]=e(t[1],r[1]),n[2]=e(t[2],r[2]),n}},Rt=function(e){return e},At=function(e,t){return e*t/255},Ot=function(e,t){return e>t?t:e},It=function(e,t){return e>t?e:t},xt=function(e,t){return 255*(1-(1-e/255)*(1-t/255))},wt=function(e,t){return t<128?2*e*t/255:255*(1-2*(1-e/255)*(1-t/255))},Dt=function(e,t){return 255*(1-(1-t/255)/(e/255))},Mt=function(e,t){return 255===e||(e=t/255*255/(1-e/255))>255?255:e};yt.normal=Ct(Nt(Rt)),yt.multiply=Ct(Nt(At)),yt.screen=Ct(Nt(xt)),yt.overlay=Ct(Nt(wt)),yt.darken=Ct(Nt(Ot)),yt.lighten=Ct(Nt(It)),yt.dodge=Ct(Nt(Mt)),yt.burn=Ct(Nt(Dt));var kt=Math.pow,Lt=Math.sin,Pt=Math.cos;function Ft(e,r,n,a,i){void 0===e&&(e=300),void 0===r&&(r=-1.5),void 0===n&&(n=1),void 0===a&&(a=1),void 0===i&&(i=[0,1]);var s,l=0;"array"===o(i)?s=i[1]-i[0]:(s=0,i=[i,i]);var c=function(o){var c=p*((e+120)/360+r*o),d=kt(i[0]+s*o,a),u=(0!==l?n[0]+o*l:n)*d*(1-d)/2,_=Pt(c),m=Lt(c);return b(t([255*(d+u*(-.14861*_+1.78277*m)),255*(d+u*(-.29227*_-.90649*m)),255*(d+u*(1.97294*_)),1]))};return c.start=function(t){return null==t?e:(e=t,c)},c.rotations=function(e){return null==e?r:(r=e,c)},c.gamma=function(e){return null==e?a:(a=e,c)},c.hue=function(e){return null==e?n:("array"===o(n=e)?0===(l=n[1]-n[0])&&(n=n[1]):l=0,c)},c.lightness=function(e){return null==e?i:("array"===o(e)?(i=e,s=e[1]-e[0]):(i=[e,e],s=0),c)},c.scale=function(){return b.scale(c)},c.hue(n),c}var Bt="0123456789abcdef",Ut=Math.floor,Gt=Math.random;function zt(){for(var e="#",t=0;t<6;t++)e+=Bt.charAt(Ut(16*Gt()));return new f(e,"hex")}var Yt=Math.log,qt=Math.pow,Ht=Math.floor,Vt=Math.abs;function $t(e,t){void 0===t&&(t=null);var r={min:Number.MAX_VALUE,max:-1*Number.MAX_VALUE,sum:0,values:[],count:0};return"object"===o(e)&&(e=Object.values(e)),e.forEach(function(e){t&&"object"===o(e)&&(e=e[t]),null==e||isNaN(e)||(r.values.push(e),r.sum+=e,e<r.min&&(r.min=e),e>r.max&&(r.max=e),r.count+=1)}),r.domain=[r.min,r.max],r.limits=function(e,t){return Wt(r,e,t)},r}function Wt(e,t,r){void 0===t&&(t="equal"),void 0===r&&(r=7),"array"==o(e)&&(e=$t(e));var n=e.min,a=e.max,i=e.values.sort(function(e,t){return e-t});if(1===r)return[n,a];var s=[];if("c"===t.substr(0,1)&&(s.push(n),s.push(a)),"e"===t.substr(0,1)){s.push(n);for(var l=1;l<r;l++)s.push(n+l/r*(a-n));s.push(a)}else if("l"===t.substr(0,1)){if(n<=0)throw new Error("Logarithmic scales are only possible for values > 0");var c=Math.LOG10E*Yt(n),d=Math.LOG10E*Yt(a);s.push(n);for(var u=1;u<r;u++)s.push(qt(10,c+u/r*(d-c)));s.push(a)}else if("q"===t.substr(0,1)){s.push(n);for(var p=1;p<r;p++){var _=(i.length-1)*p/r,m=Ht(_);if(m===_)s.push(i[m]);else{var g=_-m;s.push(i[m]*(1-g)+i[m+1]*g)}}s.push(a)}else if("k"===t.substr(0,1)){var h,f=i.length,E=new Array(f),b=new Array(r),S=!0,v=0,T=null;(T=[]).push(n);for(var y=1;y<r;y++)T.push(n+y/r*(a-n));for(T.push(a);S;){for(var C=0;C<r;C++)b[C]=0;for(var N=0;N<f;N++)for(var R=i[N],A=Number.MAX_VALUE,O=void 0,I=0;I<r;I++){var x=Vt(T[I]-R);x<A&&(A=x,O=I),b[O]++,E[N]=O}for(var w=new Array(r),D=0;D<r;D++)w[D]=null;for(var M=0;M<f;M++)null===w[h=E[M]]?w[h]=i[M]:w[h]+=i[M];for(var k=0;k<r;k++)w[k]*=1/b[k];S=!1;for(var L=0;L<r;L++)if(w[L]!==T[L]){S=!0;break}T=w,++v>200&&(S=!1)}for(var P={},F=0;F<r;F++)P[F]=[];for(var B=0;B<f;B++)P[h=E[B]].push(i[B]);for(var U=[],G=0;G<r;G++)U.push(P[G][0]),U.push(P[G][P[G].length-1]);U=U.sort(function(e,t){return e-t}),s.push(U[0]);for(var z=1;z<U.length;z+=2){var Y=U[z];isNaN(Y)||-1!==s.indexOf(Y)||s.push(Y)}}return s}function jt(e,t){e=new f(e),t=new f(t);var r=e.luminance(),n=t.luminance();return r>n?(r+.05)/(n+.05):(n+.05)/(r+.05)}var Qt=Math.sqrt,Kt=Math.pow,Xt=Math.min,Zt=Math.max,Jt=Math.atan2,er=Math.abs,tr=Math.cos,rr=Math.sin,nr=Math.exp,ar=Math.PI;function ir(e,t,r,n,a){void 0===r&&(r=1),void 0===n&&(n=1),void 0===a&&(a=1);var i=function(e){return 360*e/(2*ar)},o=function(e){return 2*ar*e/360};e=new f(e),t=new f(t);var s=Array.from(e.lab()),l=s[0],c=s[1],d=s[2],u=Array.from(t.lab()),p=u[0],_=u[1],m=u[2],g=(l+p)/2,h=(Qt(Kt(c,2)+Kt(d,2))+Qt(Kt(_,2)+Kt(m,2)))/2,E=.5*(1-Qt(Kt(h,7)/(Kt(h,7)+Kt(25,7)))),b=c*(1+E),S=_*(1+E),v=Qt(Kt(b,2)+Kt(d,2)),T=Qt(Kt(S,2)+Kt(m,2)),y=(v+T)/2,C=i(Jt(d,b)),N=i(Jt(m,S)),R=C>=0?C:C+360,A=N>=0?N:N+360,O=er(R-A)>180?(R+A+360)/2:(R+A)/2,I=1-.17*tr(o(O-30))+.24*tr(o(2*O))+.32*tr(o(3*O+6))-.2*tr(o(4*O-63)),x=A-R;x=er(x)<=180?x:A<=R?x+360:x-360,x=2*Qt(v*T)*rr(o(x)/2);var w=p-l,D=T-v,M=1+.015*Kt(g-50,2)/Qt(20+Kt(g-50,2)),k=1+.045*y,L=1+.015*y*I,P=30*nr(-Kt((O-275)/25,2)),F=-2*Qt(Kt(y,7)/(Kt(y,7)+Kt(25,7)))*rr(2*o(P)),B=Qt(Kt(w/(r*M),2)+Kt(D/(n*k),2)+Kt(x/(a*L),2)+F*(D/(n*k))*(x/(a*L)));return Zt(0,Xt(100,B))}function or(e,t,r){void 0===r&&(r="lab"),e=new f(e),t=new f(t);var n=e.get(r),a=t.get(r),i=0;for(var o in n){var s=(n[o]||0)-(a[o]||0);i+=s*s}return Math.sqrt(i)}function sr(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];try{return new(Function.prototype.bind.apply(f,[null].concat(e))),!0}catch(e){return!1}}for(var lr={cool:function(){return Et([b.hsl(180,1,.9),b.hsl(250,.7,.4)])},hot:function(){return Et(["#000","#f00","#ff0","#fff"]).mode("rgb")}},cr={OrRd:["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"],PuBu:["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"],BuPu:["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"],Oranges:["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"],BuGn:["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"],YlOrBr:["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"],YlGn:["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"],Reds:["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"],RdPu:["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"],Greens:["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"],YlGnBu:["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"],Purples:["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"],GnBu:["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"],Greys:["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"],YlOrRd:["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"],PuRd:["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"],Blues:["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"],PuBuGn:["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"],Viridis:["#440154","#482777","#3f4a8a","#31678e","#26838f","#1f9d8a","#6cce5a","#b6de2b","#fee825"],Spectral:["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"],RdYlGn:["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"],RdBu:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"],PiYG:["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"],PRGn:["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"],RdYlBu:["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"],BrBG:["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"],RdGy:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"],PuOr:["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"],Set2:["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"],Accent:["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"],Set1:["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"],Set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],Dark2:["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"],Paired:["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"],Pastel2:["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"],Pastel1:["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"]},dr=0,ur=Object.keys(cr);dr<ur.length;dr+=1){var pr=ur[dr];cr[pr.toLowerCase()]=cr[pr]}return Object.assign(b,{average:gt,bezier:Tt,blend:yt,cubehelix:Ft,mix:je,interpolate:je,random:zt,scale:Et,analyze:$t,contrast:jt,deltaE:ir,distance:or,limits:Wt,valid:sr,scales:lr,input:h,colors:ye,brewer:cr}),b}()}(pn);const _n=yr,mn=un,gn=pn.exports;var hn=class{constructor(e,t,r,n,a=.3,i=0,o=null,s=1,l=!1){if(this.points=e,this.weights=t,this.width=r,this.height=n,this.sigma=a,this.interval=i,this.opacity=s,this.normalized=l,null===o){o=["#c51b7d","#de77ae","#f1b6da","#fde0ef","#ffffff","#e6f5d0","#b8e186","#7fbc41","#4d9221"]}this.colormap=o,this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.canvas.width=this.width,this.canvas.height=this.height}setFromArray(e,t){this.points=[],e.forEach(e=>{this.points.push(new _n(e[0],e[1]))}),this.weights=[],t.forEach(e=>{this.weights.push(e)})}draw(){let e=[];for(let t=0;t<this.width;t++){let t=[];for(let e=0;e<this.height;e++)t.push(0);e.push(t)}let t=1/(2*this.sigma**2);for(let r=0;r<this.points.length;r++){let n=this.points[r],a=this.weights[r];for(let r=0;r<this.width;r++)for(let i=0;i<this.height;i++){let o=((r-n.x)**2+(i-n.y)**2)*t,s=a*Math.exp(-o);e[r][i]+=s}}let r=1;if(!this.normalized){let t=-Number.MAX_SAFE_INTEGER,n=Number.MAX_SAFE_INTEGER;for(let r=0;r<this.width;r++)for(let a=0;a<this.height;a++)e[r][a]<n&&(n=e[r][a]),e[r][a]>t&&(t=e[r][a]);r=Math.max(Math.abs(n),Math.abs(t))}const n=gn.scale(this.colormap).domain([-1,1]);for(let t=0;t<this.width;t++)for(let a=0;a<this.height;a++){this.normalized||(e[t][a]=e[t][a]/r),0!==this.interval&&(e[t][a]=Math.round(e[t][a]/this.interval)*this.interval);let[i,o,s]=n(e[t][a]).rgb();this.setPixel(new _n(t,a),i,o,s)}}getImage(e){let t=new Image;t.onload=()=>{this.context.imageSmoothingEnabled=!1,this.context.drawImage(t,0,0,this.width,this.height),e&&e(t)},t.onerror=function(e){console.log(e)},t.src=this.canvas.toDataURL()}getSVG(){return mn(this.context.getImageData(0,0,this.width,this.height))}setPixel(e,t,r,n){this.context.fillStyle="rgba("+t+","+r+","+n+","+this.opacity+")",this.context.fillRect(e.x,e.y,1,1)}};const fn=_r,En=Ar(),bn=an,Sn=Ir,vn=dn,Tn=qr,yn=yr,Cn=hn;var Nn=class{constructor(e,t=!0){this.preprocessor=new bn(e),this.opts=this.preprocessor.opts,this.clear=t,this.svgWrapper=null}draw(e,t,r="light",n=null,a=!1,i=[],o=!1){null===t||"svg"===t?((t=document.createElementNS("http://www.w3.org/2000/svg","svg")).setAttribute("xmlns","http://www.w3.org/2000/svg"),t.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),t.setAttributeNS(null,"width",this.opts.width),t.setAttributeNS(null,"height",this.opts.height)):t instanceof String&&(t=document.getElementById(t));let s={padding:this.opts.padding,compactDrawing:this.opts.compactDrawing};null!==n&&(this.opts.padding+=this.opts.weights.additionalPadding,this.opts.compactDrawing=!1);let l=this.preprocessor;return l.initDraw(e,r,a,i),a||(this.themeManager=new Tn(this.opts.themes,r),(null===this.svgWrapper||this.clear)&&(this.svgWrapper=new vn(this.themeManager,t,this.opts,this.clear))),l.processGraph(),this.svgWrapper.determineDimensions(l.graph.vertices),this.drawAtomHighlights(l.opts.debug),this.drawEdges(l.opts.debug),this.drawVertices(l.opts.debug),null!==n&&this.drawWeights(n,o),l.opts.debug&&(console.log(l.graph),console.log(l.rings),console.log(l.ringConnections)),this.svgWrapper.constructSvg(),null!==n&&(this.opts.padding=s.padding,this.opts.compactDrawing=s.padding),t}drawCanvas(e,t,r="light",n=!1){let a=null;a="string"==typeof t||t instanceof String?document.getElementById(t):t;let i=document.createElementNS("http://www.w3.org/2000/svg","svg");return i.setAttribute("xmlns","http://www.w3.org/2000/svg"),i.setAttributeNS(null,"viewBox","0 0 500 500"),i.setAttributeNS(null,"width","500"),i.setAttributeNS(null,"height","500"),i.setAttributeNS(null,"style","visibility: hidden: position: absolute; left: -1000px"),document.body.appendChild(i),this.svgDrawer.draw(e,i,r,n),this.svgDrawer.svgWrapper.toCanvas(a,this.svgDrawer.opts.width,this.svgDrawer.opts.height),document.body.removeChild(i),t}drawAromaticityRing(e){this.svgWrapper.drawRing(e.center.x,e.center.y,e.getSize())}drawEdges(e){let t=this.preprocessor,r=t.graph,n=t.rings,a=Array(this.preprocessor.graph.edges.length);if(a.fill(!1),r.traverseBF(0,t=>{let n=r.getEdges(t.id);for(var i=0;i<n.length;i++){let t=n[i];a[t]||(a[t]=!0,this.drawEdge(t,e))}}),!this.bridgedRing)for(var i=0;i<n.length;i++){let e=n[i];t.isRingAromatic(e)&&this.drawAromaticityRing(e)}}drawEdge(e,t){let r=this.preprocessor,n=r.opts,a=this.svgWrapper,i=r.graph.edges[e],o=r.graph.vertices[i.sourceId],s=r.graph.vertices[i.targetId],l=o.value.element,c=s.value.element;if(!(o.value.isDrawn&&s.value.isDrawn||"default"!==r.opts.atomVisualization))return;let d=o.position,u=s.position,p=r.getEdgeNormals(i),_=fn.clone(p);if(_[0].multiplyScalar(10).add(d),_[1].multiplyScalar(10).add(d),"="===i.bondType||"="===r.getRingbondType(o,s)||i.isPartOfAromaticRing&&r.bridgedRing){let e=r.areVerticesInSameRing(o,s),t=r.chooseSide(o,s,_);if(e){let e=r.getLargestOrAromaticCommonRing(o,s).center;p[0].multiplyScalar(n.bondSpacing),p[1].multiplyScalar(n.bondSpacing);let t=null;t=e.sameSideAs(o.position,s.position,yn.add(d,p[0]))?new Sn(yn.add(d,p[0]),yn.add(u,p[0]),l,c):new Sn(yn.add(d,p[1]),yn.add(u,p[1]),l,c),t.shorten(n.bondLength-n.shortBondLength*n.bondLength),i.isPartOfAromaticRing?a.drawLine(t,!0):a.drawLine(t),a.drawLine(new Sn(d,u,l,c))}else if(i.center||o.isTerminal()&&s.isTerminal()||0==t.anCount&&t.bnCount>1||0==t.bnCount&&t.anCount>1){this.multiplyNormals(p,n.halfBondSpacing);let e=new Sn(yn.add(d,p[0]),yn.add(u,p[0]),l,c),t=new Sn(yn.add(d,p[1]),yn.add(u,p[1]),l,c);a.drawLine(e),a.drawLine(t)}else if(t.sideCount[0]>t.sideCount[1]||t.totalSideCount[0]>t.totalSideCount[1]){this.multiplyNormals(p,n.bondSpacing);let e=new Sn(yn.add(d,p[0]),yn.add(u,p[0]),l,c);e.shorten(n.bondLength-n.shortBondLength*n.bondLength),a.drawLine(e),a.drawLine(new Sn(d,u,l,c))}else if(t.sideCount[0]<t.sideCount[1]||t.totalSideCount[0]<=t.totalSideCount[1]){this.multiplyNormals(p,n.bondSpacing);let e=new Sn(yn.add(d,p[1]),yn.add(u,p[1]),l,c);e.shorten(n.bondLength-n.shortBondLength*n.bondLength),a.drawLine(e),a.drawLine(new Sn(d,u,l,c))}}else if("#"===i.bondType){p[0].multiplyScalar(n.bondSpacing/1.5),p[1].multiplyScalar(n.bondSpacing/1.5);let e=new Sn(yn.add(d,p[0]),yn.add(u,p[0]),l,c),t=new Sn(yn.add(d,p[1]),yn.add(u,p[1]),l,c);a.drawLine(e),a.drawLine(t),a.drawLine(new Sn(d,u,l,c))}else if("."===i.bondType);else{let e=o.value.isStereoCenter,t=s.value.isStereoCenter;"up"===i.wedge?a.drawWedge(new Sn(d,u,l,c,e,t)):"down"===i.wedge?a.drawDashedWedge(new Sn(d,u,l,c,e,t)):a.drawLine(new Sn(d,u,l,c,e,t))}if(t){let t=yn.midpoint(d,u);a.drawDebugText(t.x,t.y,"e: "+e)}}drawAtomHighlights(e){let t=this.preprocessor;t.opts;let r=t.graph;t.rings;let n=this.svgWrapper;for(var a=0;a<r.vertices.length;a++){let e=r.vertices[a],o=e.value;for(var i=0;i<t.highlight_atoms.length;i++){let r=t.highlight_atoms[i];o.class===r[0]&&n.drawAtomHighlight(e.position.x,e.position.y,r[1])}}}drawVertices(e){let t=this.preprocessor,r=t.opts,n=t.graph,a=t.rings,i=this.svgWrapper;var o=n.vertices.length;for(o=0;o<n.vertices.length;o++){let t=n.vertices[o],a=t.value,s=0,l=0,c=t.value.bondCount,d=a.element,u=En.maxBonds[d]-c,p=t.getTextDirection(n.vertices,a.hasAttachedPseudoElements),_=!(!r.terminalCarbons&&"C"===d&&!a.hasAttachedPseudoElements)&&t.isTerminal(),m="C"===a.element;if(n.vertices.length<3&&(m=!1),"N"===a.element&&a.isPartOfAromaticRing&&(u=0),a.bracket&&(u=a.bracket.hcount,s=a.bracket.charge,l=a.bracket.isotope),"allballs"===r.atomVisualization)i.drawBall(t.position.x,t.position.y,d);else if(a.isDrawn&&(!m||a.drawExplicit||_||a.hasAttachedPseudoElements)||1===n.vertices.length)if("default"===r.atomVisualization){let e=a.getAttachedPseudoElements();a.hasAttachedPseudoElements&&n.vertices.length===Object.keys(e).length+1&&(p="right"),i.drawText(t.position.x,t.position.y,d,u,p,_,s,l,n.vertices.length,e)}else"balls"===r.atomVisualization&&i.drawBall(t.position.x,t.position.y,d);else if(2===t.getNeighbourCount()&&1==t.forcePositioned){let e=n.vertices[t.neighbours[0]].position,r=n.vertices[t.neighbours[1]].position,a=yn.threePointangle(t.position,e,r);Math.abs(Math.PI-a)<.1&&i.drawPoint(t.position.x,t.position.y,d)}if(e){let e="v: "+t.id+" "+fn.print(a.ringbonds);i.drawDebugText(t.position.x,t.position.y,e)}}if(r.debug)for(o=0;o<a.length;o++){let e=a[o].center;i.drawDebugPoint(e.x,e.y,"r: "+a[o].id)}}drawWeights(e,t){if(e.every(e=>0===e))return;if(e.length!==this.preprocessor.graph.atomIdxToVertexId.length)throw new Error("The number of weights supplied must be equal to the number of (heavy) atoms in the molecule.");let r=[];for(const e of this.preprocessor.graph.atomIdxToVertexId){let t=this.preprocessor.graph.vertices[e];r.push(new yn(t.position.x-this.svgWrapper.minX,t.position.y-this.svgWrapper.minY))}let n=new Cn(r,e,this.svgWrapper.drawingWidth,this.svgWrapper.drawingHeight,this.opts.weights.sigma,this.opts.weights.interval,this.opts.weights.colormap,this.opts.weights.opacity,t);n.draw(),this.svgWrapper.addLayer(n.getSVG())}getTotalOverlapScore(){return this.preprocessor.getTotalOverlapScore()}getMolecularFormula(e=null){return this.preprocessor.getMolecularFormula(e)}multiplyNormals(e,t){e[0].multiplyScalar(t),e[1].multiplyScalar(t)}};const Rn=Nn;var An=class{constructor(e){this.svgDrawer=new Rn(e)}draw(e,t,r="light",n=!1,a=[]){let i=null;i="string"==typeof t||t instanceof String?document.getElementById(t):t;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.setAttribute("xmlns","http://www.w3.org/2000/svg"),o.setAttributeNS(null,"viewBox","0 0 "+this.svgDrawer.opts.width+" "+this.svgDrawer.opts.height),o.setAttributeNS(null,"width",this.svgDrawer.opts.width+""),o.setAttributeNS(null,"height",this.svgDrawer.opts.height+""),this.svgDrawer.draw(e,o,r,n,a),this.svgDrawer.svgWrapper.toCanvas(i,this.svgDrawer.opts.width,this.svgDrawer.opts.height)}getTotalOverlapScore(){return this.svgDrawer.getTotalOverlapScore()}getMolecularFormula(){this.svgDrawer.getMolecularFormula()}},On=function(){function e(t,r,n,a){this.message=t,this.expected=r,this.found=n,this.location=a,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}return function(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}(e,Error),e.buildMessage=function(e,t){var r={literal:function(e){return'"'+a(e.text)+'"'},class:function(e){var t,r="";for(t=0;t<e.parts.length;t++)r+=e.parts[t]instanceof Array?i(e.parts[t][0])+"-"+i(e.parts[t][1]):i(e.parts[t]);return"["+(e.inverted?"^":"")+r+"]"},any:function(e){return"any character"},end:function(e){return"end of input"},other:function(e){return e.description}};function n(e){return e.charCodeAt(0).toString(16).toUpperCase()}function a(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function o(e){return r[e.type](e)}return"Expected "+function(e){var t,r,n=new Array(e.length);for(t=0;t<e.length;t++)n[t]=o(e[t]);if(n.sort(),n.length>0){for(t=1,r=1;t<n.length;t++)n[t-1]!==n[t]&&(n[r]=n[t],r++);n.length=r}switch(n.length){case 1:return n[0];case 2:return n[0]+" or "+n[1];default:return n.slice(0,-1).join(", ")+", or "+n[n.length-1]}}(e)+" but "+function(e){return e?'"'+a(e)+'"':"end of input"}(t)+" found."},{SyntaxError:e,parse:function(t,r){if(r=void 0!==r?r:{},t.split("(").length-1!==t.split(")").length-1)throw Ve("The number of opening parentheses does not match the number of closing parentheses.",0);var n,a,i,o,s={},l={chain:$e},c=$e,d=function(e){for(var t=[],r=[],n=0;n<e[1].length;n++)t.push(e[1][n]);for(n=0;n<e[2].length;n++){var a=e[2][n][0]?e[2][n][0]:"-";r.push({bond:a,id:e[2][n][1]})}for(n=0;n<e[3].length;n++)t.push(e[3][n]);for(n=0;n<e[6].length;n++)t.push(e[6][n]);return{atom:e[0],isBracket:!!e[0].element,branches:t,branchCount:t.length,ringbonds:r,ringbondCount:r.length,bond:e[4]?e[4]:"-",next:e[5],hasNext:!!e[5]}},u="(",p=Ge("(",!1),_=")",m=Ge(")",!1),g=function(e){var t=e[1]?e[1]:"-";return e[2].branchBond=t,e[2]},h=function(e){return e},f=/^[\-=#$:\/\\.]/,E=ze(["-","=","#","$",":","/","\\","."],!1,!1),b=function(e){return e},S="[",v=Ge("[",!1),T="se",y=Ge("se",!1),C="as",N=Ge("as",!1),R="]",A=Ge("]",!1),O=function(e){return{isotope:e[1],element:e[2],chirality:e[3],hcount:e[4],charge:e[5],class:e[6]}},I="B",x=Ge("B",!1),w="r",D=Ge("r",!1),M="C",k=Ge("C",!1),L="l",P=Ge("l",!1),F=/^[NOPSFI]/,B=ze(["N","O","P","S","F","I"],!1,!1),U=function(e){return e.length>1?e.join(""):e},G=/^[bcnops]/,z=ze(["b","c","n","o","p","s"],!1,!1),Y="*",q=Ge("*",!1),H=function(e){return e},V=/^[A-Z]/,$=ze([["A","Z"]],!1,!1),W=/^[a-z]/,j=ze([["a","z"]],!1,!1),Q=function(e){return e.join("")},K="%",X=Ge("%",!1),Z=/^[1-9]/,J=ze([["1","9"]],!1,!1),ee=/^[0-9]/,te=ze([["0","9"]],!1,!1),re=function(e){return 1==e.length?Number(e):Number(e.join("").replace("%",""))},ne="@",ae=Ge("@",!1),ie="TH",oe=Ge("TH",!1),se=/^[12]/,le=ze(["1","2"],!1,!1),ce="AL",de=Ge("AL",!1),ue="SP",pe=Ge("SP",!1),_e=/^[1-3]/,me=ze([["1","3"]],!1,!1),ge="TB",he=Ge("TB",!1),fe="OH",Ee=Ge("OH",!1),be=function(e){return e[1]?"@"==e[1]?"@@":e[1].join("").replace(",",""):"@"},Se=function(e){return e},ve="+",Te=Ge("+",!1),ye=function(e){return e[1]?"+"!=e[1]?Number(e[1].join("")):2:1},Ce="-",Ne=Ge("-",!1),Re=function(e){return e[1]?"-"!=e[1]?-Number(e[1].join("")):-2:-1},Ae="H",Oe=Ge("H",!1),Ie=function(e){return e[1]?Number(e[1]):1},xe=":",we=Ge(":",!1),De=/^[0]/,Me=ze(["0"],!1,!1),ke=function(e){return Number(e[1][0]+e[1][1].join(""))},Le=function(e){return Number(e.join(""))},Pe=0,Fe=[{line:1,column:1}],Be=0,Ue=[];if("startRule"in r){if(!(r.startRule in l))throw new Error("Can't start parsing from rule \""+r.startRule+'".');c=l[r.startRule]}function Ge(e,t){return{type:"literal",text:e,ignoreCase:t}}function ze(e,t,r){return{type:"class",parts:e,inverted:t,ignoreCase:r}}function Ye(e){var r,n=Fe[e];if(n)return n;for(r=e-1;!Fe[r];)r--;for(n={line:(n=Fe[r]).line,column:n.column};r<e;)10===t.charCodeAt(r)?(n.line++,n.column=1):n.column++,r++;return Fe[e]=n,n}function qe(e,t){var r=Ye(e),n=Ye(t);return{start:{offset:e,line:r.line,column:r.column},end:{offset:t,line:n.line,column:n.column}}}function He(e){Pe<Be||(Pe>Be&&(Be=Pe,Ue=[]),Ue.push(e))}function Ve(t,r){return new e(t,null,null,r)}function $e(){var e,r,n,a,i,o,l,c,u;if(e=Pe,r=function(){var e,r;e=Pe,r=function(){var e,r,n,a;e=Pe,r=Pe,66===t.charCodeAt(Pe)?(n=I,Pe++):(n=s,He(x));n!==s?(114===t.charCodeAt(Pe)?(a=w,Pe++):(a=s,He(D)),a===s&&(a=null),a!==s?r=n=[n,a]:(Pe=r,r=s)):(Pe=r,r=s);r===s&&(r=Pe,67===t.charCodeAt(Pe)?(n=M,Pe++):(n=s,He(k)),n!==s?(108===t.charCodeAt(Pe)?(a=L,Pe++):(a=s,He(P)),a===s&&(a=null),a!==s?r=n=[n,a]:(Pe=r,r=s)):(Pe=r,r=s),r===s&&(F.test(t.charAt(Pe))?(r=t.charAt(Pe),Pe++):(r=s,He(B))));r!==s&&(r=U(r));return e=r,e}(),r===s&&(r=Qe())===s&&(r=function(){var e,r,n,a,i,o,l,c,d,u;e=Pe,r=Pe,91===t.charCodeAt(Pe)?(n=S,Pe++):(n=s,He(v));n!==s?(a=function(){var e,r,n,a,i;e=Pe,r=Pe,Z.test(t.charAt(Pe))?(n=t.charAt(Pe),Pe++):(n=s,He(J));n!==s?(ee.test(t.charAt(Pe))?(a=t.charAt(Pe),Pe++):(a=s,He(te)),a===s&&(a=null),a!==s?(ee.test(t.charAt(Pe))?(i=t.charAt(Pe),Pe++):(i=s,He(te)),i===s&&(i=null),i!==s?r=n=[n,a,i]:(Pe=r,r=s)):(Pe=r,r=s)):(Pe=r,r=s);r!==s&&(r=Le(r));return e=r,e}(),a===s&&(a=null),a!==s?(t.substr(Pe,2)===T?(i=T,Pe+=2):(i=s,He(y)),i===s&&(t.substr(Pe,2)===C?(i=C,Pe+=2):(i=s,He(N)),i===s&&(i=Qe())===s&&(i=function(){var e,r,n,a;e=Pe,r=Pe,V.test(t.charAt(Pe))?(n=t.charAt(Pe),Pe++):(n=s,He($));n!==s?(W.test(t.charAt(Pe))?(a=t.charAt(Pe),Pe++):(a=s,He(j)),a===s&&(a=null),a!==s?r=n=[n,a]:(Pe=r,r=s)):(Pe=r,r=s);r!==s&&(r=Q(r));return e=r,e}(),i===s&&(i=Ke()))),i!==s?(o=function(){var e,r,n,a,i,o,l;e=Pe,r=Pe,64===t.charCodeAt(Pe)?(n=ne,Pe++):(n=s,He(ae));n!==s?(64===t.charCodeAt(Pe)?(a=ne,Pe++):(a=s,He(ae)),a===s&&(a=Pe,t.substr(Pe,2)===ie?(i=ie,Pe+=2):(i=s,He(oe)),i!==s?(se.test(t.charAt(Pe))?(o=t.charAt(Pe),Pe++):(o=s,He(le)),o!==s?a=i=[i,o]:(Pe=a,a=s)):(Pe=a,a=s),a===s&&(a=Pe,t.substr(Pe,2)===ce?(i=ce,Pe+=2):(i=s,He(de)),i!==s?(se.test(t.charAt(Pe))?(o=t.charAt(Pe),Pe++):(o=s,He(le)),o!==s?a=i=[i,o]:(Pe=a,a=s)):(Pe=a,a=s),a===s&&(a=Pe,t.substr(Pe,2)===ue?(i=ue,Pe+=2):(i=s,He(pe)),i!==s?(_e.test(t.charAt(Pe))?(o=t.charAt(Pe),Pe++):(o=s,He(me)),o!==s?a=i=[i,o]:(Pe=a,a=s)):(Pe=a,a=s),a===s&&(a=Pe,t.substr(Pe,2)===ge?(i=ge,Pe+=2):(i=s,He(he)),i!==s?(Z.test(t.charAt(Pe))?(o=t.charAt(Pe),Pe++):(o=s,He(J)),o!==s?(ee.test(t.charAt(Pe))?(l=t.charAt(Pe),Pe++):(l=s,He(te)),l===s&&(l=null),l!==s?a=i=[i,o,l]:(Pe=a,a=s)):(Pe=a,a=s)):(Pe=a,a=s),a===s&&(a=Pe,t.substr(Pe,2)===fe?(i=fe,Pe+=2):(i=s,He(Ee)),i!==s?(Z.test(t.charAt(Pe))?(o=t.charAt(Pe),Pe++):(o=s,He(J)),o!==s?(ee.test(t.charAt(Pe))?(l=t.charAt(Pe),Pe++):(l=s,He(te)),l===s&&(l=null),l!==s?a=i=[i,o,l]:(Pe=a,a=s)):(Pe=a,a=s)):(Pe=a,a=s)))))),a===s&&(a=null),a!==s?r=n=[n,a]:(Pe=r,r=s)):(Pe=r,r=s);r!==s&&(r=be(r));return e=r,e}(),o===s&&(o=null),o!==s?(l=function(){var e,r,n,a;e=Pe,r=Pe,72===t.charCodeAt(Pe)?(n=Ae,Pe++):(n=s,He(Oe));n!==s?(ee.test(t.charAt(Pe))?(a=t.charAt(Pe),Pe++):(a=s,He(te)),a===s&&(a=null),a!==s?r=n=[n,a]:(Pe=r,r=s)):(Pe=r,r=s);r!==s&&(r=Ie(r));return e=r,e}(),l===s&&(l=null),l!==s?(c=function(){var e,r;e=Pe,r=function(){var e,r,n,a,i,o;e=Pe,r=Pe,43===t.charCodeAt(Pe)?(n=ve,Pe++):(n=s,He(Te));n!==s?(43===t.charCodeAt(Pe)?(a=ve,Pe++):(a=s,He(Te)),a===s&&(a=Pe,Z.test(t.charAt(Pe))?(i=t.charAt(Pe),Pe++):(i=s,He(J)),i!==s?(ee.test(t.charAt(Pe))?(o=t.charAt(Pe),Pe++):(o=s,He(te)),o===s&&(o=null),o!==s?a=i=[i,o]:(Pe=a,a=s)):(Pe=a,a=s)),a===s&&(a=null),a!==s?r=n=[n,a]:(Pe=r,r=s)):(Pe=r,r=s);r!==s&&(r=ye(r));return e=r,e}(),r===s&&(r=function(){var e,r,n,a,i,o;e=Pe,r=Pe,45===t.charCodeAt(Pe)?(n=Ce,Pe++):(n=s,He(Ne));n!==s?(45===t.charCodeAt(Pe)?(a=Ce,Pe++):(a=s,He(Ne)),a===s&&(a=Pe,Z.test(t.charAt(Pe))?(i=t.charAt(Pe),Pe++):(i=s,He(J)),i!==s?(ee.test(t.charAt(Pe))?(o=t.charAt(Pe),Pe++):(o=s,He(te)),o===s&&(o=null),o!==s?a=i=[i,o]:(Pe=a,a=s)):(Pe=a,a=s)),a===s&&(a=null),a!==s?r=n=[n,a]:(Pe=r,r=s)):(Pe=r,r=s);r!==s&&(r=Re(r));return e=r,e}());r!==s&&(r=Se(r));return e=r,e}(),c===s&&(c=null),c!==s?(d=function(){var e,r,n,a,i,o,l;e=Pe,r=Pe,58===t.charCodeAt(Pe)?(n=xe,Pe++):(n=s,He(we));if(n!==s){if(a=Pe,Z.test(t.charAt(Pe))?(i=t.charAt(Pe),Pe++):(i=s,He(J)),i!==s){for(o=[],ee.test(t.charAt(Pe))?(l=t.charAt(Pe),Pe++):(l=s,He(te));l!==s;)o.push(l),ee.test(t.charAt(Pe))?(l=t.charAt(Pe),Pe++):(l=s,He(te));o!==s?a=i=[i,o]:(Pe=a,a=s)}else Pe=a,a=s;a===s&&(De.test(t.charAt(Pe))?(a=t.charAt(Pe),Pe++):(a=s,He(Me))),a!==s?r=n=[n,a]:(Pe=r,r=s)}else Pe=r,r=s;r!==s&&(r=ke(r));return e=r,e}(),d===s&&(d=null),d!==s?(93===t.charCodeAt(Pe)?(u=R,Pe++):(u=s,He(A)),u!==s?r=n=[n,a,i,o,l,c,d,u]:(Pe=r,r=s)):(Pe=r,r=s)):(Pe=r,r=s)):(Pe=r,r=s)):(Pe=r,r=s)):(Pe=r,r=s)):(Pe=r,r=s)):(Pe=r,r=s);r!==s&&(r=O(r));return e=r,e}(),r===s&&(r=Ke()));r!==s&&(r=h(r));return e=r,e}(),r!==s){for(n=[],a=We();a!==s;)n.push(a),a=We();if(n!==s){for(a=[],i=Pe,(o=je())===s&&(o=null),o!==s&&(l=Xe())!==s?i=o=[o,l]:(Pe=i,i=s);i!==s;)a.push(i),i=Pe,(o=je())===s&&(o=null),o!==s&&(l=Xe())!==s?i=o=[o,l]:(Pe=i,i=s);if(a!==s){for(i=[],o=We();o!==s;)i.push(o),o=We();if(i!==s)if((o=je())===s&&(o=null),o!==s)if((l=$e())===s&&(l=null),l!==s){for(c=[],u=We();u!==s;)c.push(u),u=We();c!==s?e=r=[r,n,a,i,o,l,c]:(Pe=e,e=s)}else Pe=e,e=s;else Pe=e,e=s;else Pe=e,e=s}else Pe=e,e=s}else Pe=e,e=s}else Pe=e,e=s;return e!==s&&(e=d(e)),e}function We(){var e,r,n,a,i;return e=Pe,40===t.charCodeAt(Pe)?(r=u,Pe++):(r=s,He(p)),r!==s?((n=je())===s&&(n=null),n!==s&&(a=$e())!==s?(41===t.charCodeAt(Pe)?(i=_,Pe++):(i=s,He(m)),i!==s?e=r=[r,n,a,i]:(Pe=e,e=s)):(Pe=e,e=s)):(Pe=e,e=s),e!==s&&(e=g(e)),e}function je(){var e;if(f.test(t.charAt(Pe))){if((e=t.charAt(Pe))===t.charAt(Pe+1))throw e=s,Ve("The parser encountered a bond repetition.",Pe+1);Pe++}else e=s,He(E);return e!==s&&(e=b(e)),e}function Qe(){var e;return G.test(t.charAt(Pe))?(e=t.charAt(Pe),Pe++):(e=s,He(z)),e!==s&&(e=h(e)),e}function Ke(){var e;return 42===t.charCodeAt(Pe)?(e=Y,Pe++):(e=s,He(q)),e!==s&&(e=H(e)),e}function Xe(){var e,r,n,a;return e=Pe,37===t.charCodeAt(Pe)?(r=K,Pe++):(r=s,He(X)),r!==s?(Z.test(t.charAt(Pe))?(n=t.charAt(Pe),Pe++):(n=s,He(J)),n!==s?(ee.test(t.charAt(Pe))?(a=t.charAt(Pe),Pe++):(a=s,He(te)),a!==s?e=r=[r,n,a]:(Pe=e,e=s)):(Pe=e,e=s)):(Pe=e,e=s),e===s&&(ee.test(t.charAt(Pe))?(e=t.charAt(Pe),Pe++):(e=s,He(te))),e!==s&&(e=re(e)),e}if((n=c())!==s&&Pe===t.length)return n;throw n!==s&&Pe<t.length&&He({type:"end"}),a=Ue,i=Be<t.length?t.charAt(Be):null,o=Be<t.length?qe(Be,Be+1):qe(Be,Be),new e(e.buildMessage(a,i),a,i,o)}}}();const In=On;var xn=class{constructor(e){this.reactantsSmiles=[],this.reagentsSmiles=[],this.productsSmiles=[],this.reactantsWeights=[],this.reagentsWeights=[],this.productsWeights=[],this.reactants=[],this.reagents=[],this.products=[];let t=e.split(">");if(3!==t.length)throw new Error("Invalid reaction SMILES. Did you add fewer than or more than two '>'?");""!==t[0]&&(this.reactantsSmiles=t[0].split(".")),""!==t[1]&&(this.reagentsSmiles=t[1].split(".")),""!==t[2]&&(this.productsSmiles=t[2].split("."));for(var r=0;r<this.reactantsSmiles.length;r++)this.reactants.push(In.parse(this.reactantsSmiles[r]));for(r=0;r<this.reagentsSmiles.length;r++)this.reagents.push(In.parse(this.reagentsSmiles[r]));for(r=0;r<this.productsSmiles.length;r++)this.products.push(In.parse(this.productsSmiles[r]))}};const wn=xn;var Dn=class{static parse(e){return new wn(e)}};const Mn=Nn,kn=dn,Ln=Hr,Pn=qr,Fn={C2H4O2:"acetic acid",C3H6O:"acetone",C2H3N:"acetonitrile",C6H6:"benzene",CCl4:"carbon tetrachloride",C6H5Cl:"chlorobenzene",CHCl3:"chloroform",C6H12:"cyclohexane",C2H4Cl2:"1,2-dichloroethane",C4H10O3:"diethylene glycol",C6H14O3:"diglyme",C4H10O2:"DME",C3H7NO:"DMF",C2H6OS:"DMSO",C2H6O:"ethanol",C2H6O2:"ethylene glycol",C3H8O3:"glycerin",C7H16:"heptane",C6H18N3OP:"HMPA",C6H18N3P:"HMPT",C6H14:"hexane",CH4O:"methanol",C5H12O:"MTBE",CH2Cl2:"methylene chloride",CH5H9NO:"NMP",CH3NO2:"nitromethane",C5H12:"pentane",C5H5N:"pyridine",C7H8:"toluene",C6H15N:"triethyl amine",H2O:"water"};var Bn=class{constructor(e,t){this.defaultOptions={scale:t.scale>0?t.scale:1,fontSize:.8*t.fontSizeLarge,fontFamily:"Arial, Helvetica, sans-serif",spacing:10,plus:{size:9,thickness:1},arrow:{length:4*t.bondLength,headSize:6,thickness:1,margin:3},weights:{normalize:!1}},this.opts=Ln.extend(!0,this.defaultOptions,e),this.drawer=new Mn(t),this.molOpts=this.drawer.opts}draw(e,t,r="light",n=null,a="{reagents}",i="",o=!1){if(this.themeManager=new Pn(this.molOpts.themes,r),this.opts.weights.normalize){let e=-Number.MAX_SAFE_INTEGER,t=Number.MAX_SAFE_INTEGER;if(n.hasOwnProperty("reactants"))for(let r=0;r<n.reactants.length;r++)for(let a=0;a<n.reactants[r].length;a++)n.reactants[r][a]<t&&(t=n.reactants[r][a]),n.reactants[r][a]>e&&(e=n.reactants[r][a]);if(n.hasOwnProperty("reagents"))for(let r=0;r<n.reagents.length;r++)for(let a=0;a<n.reagents[r].length;a++)n.reagents[r][a]<t&&(t=n.reagents[r][a]),n.reagents[r][a]>e&&(e=n.reagents[r][a]);if(n.hasOwnProperty("products"))for(let r=0;r<n.products.length;r++)for(let a=0;a<n.products[r].length;a++)n.products[r][a]<t&&(t=n.products[r][a]),n.products[r][a]>e&&(e=n.products[r][a]);let r=Math.max(Math.abs(t),Math.abs(e));if(0===r&&(r=1),n.hasOwnProperty("reactants"))for(let e=0;e<n.reactants.length;e++)for(let t=0;t<n.reactants[e].length;t++)n.reactants[e][t]/=r;if(n.hasOwnProperty("reagents"))for(let e=0;e<n.reagents.length;e++)for(let t=0;t<n.reagents[e].length;t++)n.reagents[e][t]/=r;if(n.hasOwnProperty("products"))for(let e=0;e<n.products.length;e++)for(let t=0;t<n.products[e].length;t++)n.products[e][t]/=r}let s=null;for(null===t||"svg"===t?(s=document.createElementNS("http://www.w3.org/2000/svg","svg"),s.setAttribute("xmlns","http://www.w3.org/2000/svg"),s.setAttributeNS(null,"width","500"),s.setAttributeNS(null,"height","500")):s="string"==typeof t||t instanceof String?document.getElementById(t):t;s.firstChild;)s.removeChild(s.firstChild);let l=[],c=0;for(var d=0;d<e.reactants.length;d++){d>0&&l.push({width:this.opts.plus.size*this.opts.scale,height:this.opts.plus.size*this.opts.scale,svg:this.getPlus()});let t=null;n&&n.hasOwnProperty("reactants")&&n.reactants.length>d&&(t=n.reactants[d]);let a=document.createElementNS("http://www.w3.org/2000/svg","svg");this.drawer.draw(e.reactants[d],a,r,t,o,[],this.opts.weights.normalize);let i={width:a.viewBox.baseVal.width*this.opts.scale,height:a.viewBox.baseVal.height*this.opts.scale,svg:a};l.push(i),i.height>c&&(c=i.height)}l.push({width:this.opts.arrow.length*this.opts.scale,height:2*this.opts.arrow.headSize*this.opts.scale,svg:this.getArrow()});let u="";for(d=0;d<e.reagents.length;d++){d>0&&(u+=", ");let t=this.drawer.getMolecularFormula(e.reagents[d]);t in Fn&&(t=Fn[t]),u+=kn.replaceNumbersWithSubscript(t)}a=a.replace("{reagents}",u);const p=kn.writeText(a,this.themeManager,this.opts.fontSize*this.opts.scale,this.opts.fontFamily,this.opts.arrow.length*this.opts.scale);let _=(this.opts.arrow.length*this.opts.scale-p.width)/2;l.push({svg:p.svg,height:p.height,width:this.opts.arrow.length*this.opts.scale,offsetX:-(this.opts.arrow.length*this.opts.scale+this.opts.spacing)+_,offsetY:-p.height/2-this.opts.arrow.margin,position:"relative"});const m=kn.writeText(i,this.themeManager,this.opts.fontSize*this.opts.scale,this.opts.fontFamily,this.opts.arrow.length*this.opts.scale);_=(this.opts.arrow.length*this.opts.scale-m.width)/2,l.push({svg:m.svg,height:m.height,width:this.opts.arrow.length*this.opts.scale,offsetX:-(this.opts.arrow.length*this.opts.scale+this.opts.spacing)+_,offsetY:m.height/2+this.opts.arrow.margin,position:"relative"});for(d=0;d<e.products.length;d++){d>0&&l.push({width:this.opts.plus.size*this.opts.scale,height:this.opts.plus.size*this.opts.scale,svg:this.getPlus()});let t=null;n&&n.hasOwnProperty("products")&&n.products.length>d&&(t=n.products[d]);let a=document.createElementNS("http://www.w3.org/2000/svg","svg");this.drawer.draw(e.products[d],a,r,t,o,[],this.opts.weights.normalize);let i={width:a.viewBox.baseVal.width*this.opts.scale,height:a.viewBox.baseVal.height*this.opts.scale,svg:a};l.push(i),i.height>c&&(c=i.height)}let g=0;return l.forEach(e=>{let t=e.offsetX??0,r=e.offsetY??0;e.svg.setAttributeNS(null,"x",Math.round(g+t)),e.svg.setAttributeNS(null,"y",Math.round((c-e.height)/2+r)),e.svg.setAttributeNS(null,"width",Math.round(e.width)),e.svg.setAttributeNS(null,"height",Math.round(e.height)),s.appendChild(e.svg),"relative"!==e.position&&(g+=Math.round(e.width+this.opts.spacing+t))}),s.setAttributeNS(null,"viewBox",`0 0 ${g} ${c}`),s.style.width=g+"px",s.style.height=c+"px",s}getPlus(){let e=this.opts.plus.size,t=this.opts.plus.thickness,r=document.createElementNS("http://www.w3.org/2000/svg","svg"),n=document.createElementNS("http://www.w3.org/2000/svg","rect"),a=document.createElementNS("http://www.w3.org/2000/svg","rect");return r.setAttributeNS(null,"id","plus"),n.setAttributeNS(null,"x",0),n.setAttributeNS(null,"y",e/2-t/2),n.setAttributeNS(null,"width",e),n.setAttributeNS(null,"height",t),n.setAttributeNS(null,"fill",this.themeManager.getColor("C")),a.setAttributeNS(null,"x",e/2-t/2),a.setAttributeNS(null,"y",0),a.setAttributeNS(null,"width",t),a.setAttributeNS(null,"height",e),a.setAttributeNS(null,"fill",this.themeManager.getColor("C")),r.appendChild(n),r.appendChild(a),r.setAttributeNS(null,"viewBox",`0 0 ${e} ${e}`),r}getArrowhead(){let e=this.opts.arrow.headSize,t=document.createElementNS("http://www.w3.org/2000/svg","marker"),r=document.createElementNS("http://www.w3.org/2000/svg","polygon");return t.setAttributeNS(null,"id","arrowhead"),t.setAttributeNS(null,"viewBox",`0 0 ${e} ${e}`),t.setAttributeNS(null,"markerUnits","userSpaceOnUse"),t.setAttributeNS(null,"markerWidth",e),t.setAttributeNS(null,"markerHeight",e),t.setAttributeNS(null,"refX",0),t.setAttributeNS(null,"refY",e/2),t.setAttributeNS(null,"orient","auto"),t.setAttributeNS(null,"fill",this.themeManager.getColor("C")),r.setAttributeNS(null,"points",`0 0, ${e} ${e/2}, 0 ${e}`),t.appendChild(r),t}getCDArrowhead(){let e=this.opts.arrow.headSize,t=e*(7/4.5),r=document.createElementNS("http://www.w3.org/2000/svg","marker"),n=document.createElementNS("http://www.w3.org/2000/svg","path");return r.setAttributeNS(null,"id","arrowhead"),r.setAttributeNS(null,"viewBox",`0 0 ${t} ${e}`),r.setAttributeNS(null,"markerUnits","userSpaceOnUse"),r.setAttributeNS(null,"markerWidth",2*t),r.setAttributeNS(null,"markerHeight",2*e),r.setAttributeNS(null,"refX",2.2),r.setAttributeNS(null,"refY",2.2),r.setAttributeNS(null,"orient","auto"),r.setAttributeNS(null,"fill",this.themeManager.getColor("C")),n.setAttributeNS(null,"style","fill-rule:nonzero;"),n.setAttributeNS(null,"d","m 0 0 l 7 2.25 l -7 2.25 c 0 0 0.735 -1.084 0.735 -2.28 c 0 -1.196 -0.735 -2.22 -0.735 -2.22 z"),r.appendChild(n),r}getArrow(){let e=this.opts.arrow.headSize,t=this.opts.arrow.length,r=document.createElementNS("http://www.w3.org/2000/svg","svg"),n=document.createElementNS("http://www.w3.org/2000/svg","defs"),a=document.createElementNS("http://www.w3.org/2000/svg","line");return n.appendChild(this.getCDArrowhead()),r.appendChild(n),r.setAttributeNS(null,"id","arrow"),a.setAttributeNS(null,"x1",0),a.setAttributeNS(null,"y1",-this.opts.arrow.thickness/2),a.setAttributeNS(null,"x2",t),a.setAttributeNS(null,"y2",-this.opts.arrow.thickness/2),a.setAttributeNS(null,"stroke-width",this.opts.arrow.thickness),a.setAttributeNS(null,"stroke",this.themeManager.getColor("C")),a.setAttributeNS(null,"marker-end","url(#arrowhead)"),r.appendChild(a),r.setAttributeNS(null,"viewBox",`0 ${-e/2} ${t+e*(7/4.5)} ${e}`),r}};const Un=On,Gn=Dn,zn=Nn,Yn=Bn,qn=dn,Hn=Hr;var Vn=class e{constructor(e={},t={}){this.drawer=new zn(e),this.reactionDrawer=new Yn(t,JSON.parse(JSON.stringify(this.drawer.opts)))}static apply(t={},r={},n="data-smiles",a="light",i=null,o=null){new e(t,r).apply(n,a,i,o)}apply(t="data-smiles",r="light",n=null,a=null){document.querySelectorAll(`[${t}]`).forEach(i=>{let o=i.getAttribute(t);if(null===o)throw Error("No SMILES provided.");let s=r,l=null;if(i.hasAttribute("data-smiles-theme")&&(s=i.getAttribute("data-smiles-theme")),i.hasAttribute("data-smiles-weights")&&(l=i.getAttribute("data-smiles-weights").split(",").map(parseFloat)),(i.hasAttribute("data-smiles-reactant-weights")||i.hasAttribute("data-smiles-reagent-weights")||i.hasAttribute("data-smiles-product-weights"))&&(l={reactants:[],reagents:[],products:[]},i.hasAttribute("data-smiles-reactant-weights")&&(l.reactants=i.getAttribute("data-smiles-reactant-weights").split(";").map(e=>e.split(",").map(parseFloat))),i.hasAttribute("data-smiles-reagent-weights")&&(l.reagents=i.getAttribute("data-smiles-reagent-weights").split(";").map(e=>e.split(",").map(parseFloat))),i.hasAttribute("data-smiles-product-weights")&&(l.products=i.getAttribute("data-smiles-product-weights").split(";").map(e=>e.split(",").map(parseFloat)))),i.hasAttribute("data-smiles-options")||i.hasAttribute("data-smiles-reaction-options")){let t={};i.hasAttribute("data-smiles-options")&&(t=JSON.parse(i.getAttribute("data-smiles-options").replaceAll("'",'"')));let r={};i.hasAttribute("data-smiles-reaction-options")&&(r=JSON.parse(i.getAttribute("data-smiles-reaction-options").replaceAll("'",'"'))),new e(t,r).draw(o,i,s,n,a,l)}else this.draw(o,i,s,n,a,l)})}draw(e,t,r="light",n=null,a=null,i=null){let o=[];[e,...o]=e.split(" ");let s=o.join(" "),l={};if(s.includes("__")){let e=s.substring(s.indexOf("__")+2,s.lastIndexOf("__"));l=JSON.parse(e.replaceAll("'",'"'))}if(l=Hn.extend(!0,{textAboveArrow:"{reagents}",textBelowArrow:""},l),e.includes(">"))try{this.drawReaction(e,t,r,l,i,n)}catch(e){a?a(e):console.error(e)}else try{this.drawMolecule(e,t,r,i,n)}catch(e){a?a(e):console.error(e)}}drawMolecule(e,t,r,n,a){let i=Un.parse(e);if(null===t||"svg"===t){let e=this.drawer.draw(i,null,r,n),t=this.getDimensions(e);e.setAttributeNS(null,"width",""+t.w),e.setAttributeNS(null,"height",""+t.h),a&&a(e)}else if("canvas"===t){let e=this.svgToCanvas(this.drawer.draw(i,null,r,n));a&&a(e)}else if("img"===t){let e=this.svgToImg(this.drawer.draw(i,null,r,n));a&&a(e)}else if(t instanceof HTMLImageElement)this.svgToImg(this.drawer.draw(i,null,r,n),t),a&&a(t);else if(t instanceof SVGElement)this.drawer.draw(i,t,r,n),a&&a(t);else{document.querySelectorAll(t).forEach(e=>{let t=e.nodeName.toLowerCase();"svg"===t?(this.drawer.draw(i,e,r,n),a&&a(e)):"canvas"===t?(this.svgToCanvas(this.drawer.draw(i,null,r,n),e),a&&a(e)):"img"===t&&(this.svgToImg(this.drawer.draw(i,null,r,n),e),a&&a(e))})}}drawReaction(e,t,r,n,a,i){let o=Gn.parse(e);if(null===t||"svg"===t){let e=this.reactionDrawer.draw(o,null,r),t=this.getDimensions(e);e.setAttributeNS(null,"width",""+t.w),e.setAttributeNS(null,"height",""+t.h),i&&i(e)}else if("canvas"===t){let e=this.svgToCanvas(this.reactionDrawer.draw(o,null,r,a,n.textAboveArrow,n.textBelowArrow));i&&i(e)}else if("img"===t){let e=this.svgToImg(this.reactionDrawer.draw(o,null,r,a,n.textAboveArrow,n.textBelowArrow));i&&i(e)}else if(t instanceof HTMLImageElement)this.svgToImg(this.reactionDrawer.draw(o,null,r,a,n.textAboveArrow,n.textBelowArrow),t),i&&i(t);else if(t instanceof SVGElement)this.reactionDrawer.draw(o,t,r,a,n.textAboveArrow,n.textBelowArrow),i&&i(t);else{document.querySelectorAll(t).forEach(e=>{let t=e.nodeName.toLowerCase();"svg"===t?(this.reactionDrawer.draw(o,e,r,a,n.textAboveArrow,n.textBelowArrow),this.reactionDrawer.opts.scale<=0&&(e.style.width=null,e.style.height=null),i&&i(e)):"canvas"===t?(this.svgToCanvas(this.reactionDrawer.draw(o,null,r,a,n.textAboveArrow,n.textBelowArrow),e),i&&i(e)):"img"===t&&(this.svgToImg(this.reactionDrawer.draw(o,null,r,a,n.textAboveArrow,n.textBelowArrow),e),i&&i(e))})}}svgToCanvas(e,t=null){null===t&&(t=document.createElement("canvas"));let r=this.getDimensions(t,e);return qn.svgToCanvas(e,t,r.w,r.h),t}svgToImg(e,t=null){null===t&&(t=document.createElement("img"));let r=this.getDimensions(t,e);return qn.svgToImg(e,t,r.w,r.h),t}getDimensions(e,t=null){let r=this.drawer.opts.width,n=this.drawer.opts.height;return this.drawer.opts.scale<=0?(null===r&&(r=e.width),null===n&&(n=e.height),""!==e.style.width&&(r=parseInt(e.style.width)),""!==e.style.height&&(n=parseInt(e.style.height))):t&&(r=parseFloat(t.style.width),n=parseFloat(t.style.height)),{w:r,h:n}}};const $n=An,Wn=On,jn=Dn,Qn=Nn,Kn=Bn,Xn=Vn,Zn=hn;var Jn=!("undefined"==typeof window||!window.document||!window.document.createElement),ea={Version:"1.0.0"};ea.Drawer=$n,ea.Parser=Wn,ea.SvgDrawer=Qn,ea.ReactionDrawer=Kn,ea.ReactionParser=jn,ea.GaussDrawer=Zn,ea.clean=function(e){return e.replace(/[^A-Za-z0-9@\.\+\-\?!\(\)\[\]\{\}/\\=#\$:\*]/g,"")},ea.apply=function(e,t="canvas[data-smiles]",r="light",n=null){let a=new $n(e),i=document.querySelectorAll(t);for(var o=0;o<i.length;o++){let e=i[o];ea.parse(e.getAttribute("data-smiles"),function(t){a.draw(t,e,r,!1)},function(e){n&&n(e)})}},ea.parse=function(e,t,r){try{t&&t(Wn.parse(e))}catch(e){r&&r(e)}},ea.parseReaction=function(e,t,r){try{t&&t(jn.parse(e))}catch(e){r&&r(e)}},Jn&&(window.SmilesDrawer=ea,window.SmiDrawer=Xn),ea.SmiDrawer=Xn,Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{value:function(e){if(null==this)throw new TypeError("this is null or not defined");for(var t=Object(this),r=t.length>>>0,n=arguments[1]|0,a=n<0?Math.max(r+n,0):Math.min(n,r),i=arguments[2],o=void 0===i?r:i|0,s=o<0?Math.max(r+o,0):Math.min(o,r);a<s;)t[a]=e,a++;return t}});var ta=pr(ea),ra=function(){return r(function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t(this,e),this.width=r.width||150,this.height=r.height||150,this.maxSizePx=r.maxSizePx||150,this.theme=r.theme||"light",this.stretch=Boolean(r.stretch);var n=o({width:this.width,height:this.height},r.drawerOptions||{});r.fontSize&&(n=function(e,t){if(!e)return t;var r=3*Number(e)/4,n=r/5;return t.bondThickness=.6*n,t.bondLength=15*n,t.bondSpacing=.18*15*n,t.fontSizeLarge=r,t.fontSizeLargePx=e,t.fontSizeSmall=3*n,t.fontSizeSmallPx=3*n*4/3,t.padding=5*n,t}(r.fontSize,n));var a="var(--somarkdown-smiles-color-text, currentColor)",i=r.darkTextColor||a,s=r.lightTextColor||a;n=r.disableColors?function(e,t,r){return e.themes={dark:{C:t,O:t,N:t,F:t,CL:t,BR:t,I:t,P:t,S:t,B:t,SI:t,H:t,BACKGROUND:"#141414"},light:{C:r,O:r,N:r,F:r,CL:r,BR:r,I:r,P:r,S:r,B:r,SI:r,H:r,BACKGROUND:"#fff"}},e}(n,i,s):function(e,t,r){return e.themes={dark:{C:t,O:"#e74c3c",N:"#3498db",F:"#27ae60",CL:"#16a085",BR:"#d35400",I:"#8e44ad",P:"#d35400",S:"#f1c40f",B:"#e67e22",SI:"#e67e22",H:t,BACKGROUND:"#141414"},light:{C:r,O:"#e74c3c",N:"#3498db",F:"#27ae60",CL:"#16a085",BR:"#d35400",I:"#8e44ad",P:"#d35400",S:"#f1c40f",B:"#e67e22",SI:"#e67e22",H:r,BACKGROUND:"#fff"}},e}(n,i,s),this.svgDrawer=new ta.SvgDrawer(n)},[{key:"render",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)return"";var n=(null==r?void 0:r.theme)||this.theme,a=document.createElementNS("http://www.w3.org/2000/svg","svg");a.setAttribute("xmlns","http://www.w3.org/2000/svg"),a.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");var i="",o=null,s=null,l=null;if(ta.parse(e,function(e){t.svgDrawer.draw(e,a,n,null,!1);var r=null,o=null,c=t.svgDrawer.svgWrapper;if(c&&Number.isFinite(c.drawingWidth)&&Number.isFinite(c.drawingHeight)&&(c.drawingWidth>0&&(r=c.drawingWidth),c.drawingHeight>0&&(o=c.drawingHeight)),!r||!o){var d=Number.parseFloat(a.getAttribute("width")||""),u=Number.parseFloat(a.getAttribute("height")||"");!r&&Number.isFinite(d)&&d>0&&(r=d),!o&&Number.isFinite(u)&&u>0&&(o=u)}if(!r||!o){var p=function(e){if(!e)return null;var t=e.trim().split(/[\s,]+/).map(function(e){return Number.parseFloat(e)});if(4!==t.length)return null;var r=t[2],n=t[3];return!Number.isFinite(r)||!Number.isFinite(n)||r<=0||n<=0?null:{width:r,height:n}}(a.getAttribute("viewBox"));p&&(r||(r=p.width),o||(o=p.height))}r||(r=t.width),o||(o=t.height);var _=1;if(!t.stretch&&t.maxSizePx){var m=t.maxSizePx/Math.max(r,o);Number.isFinite(m)&&m>0&&(_=Math.min(1,m))}s=Math.max(1,Math.round(r*_)),l=Math.max(1,Math.round(o*_)),a.style.width="".concat(s,"px"),a.style.height="".concat(l,"px"),a.setAttribute("width","".concat(s)),a.setAttribute("height","".concat(l)),a.style.display="block",a.style.overflow="visible",a.setAttribute("preserveAspectRatio","xMidYMid meet"),i=a.outerHTML},function(t){o=t,console.error("[SmilesDrawer Error]"+t),i='<span style="background-color: yellow; color:red">[SyntaxError Error for: '.concat(e,"] ").concat(t,"</span>")}),o)return i;var c=s&&l?"width:".concat(s,"px; height:").concat(l,"px;"):"width:".concat(this.width,"px; height:").concat(this.height,"px;");return'<span style="display:inline-block; vertical-align: middle; line-height:0; overflow: visible; '.concat(c,'">').concat(i,"</span>")}}])}(),na=function(){return function(e){var t,r=e.consumeArgs(1)[0].reverse().map(function(e){return e.text}).join(""),n=(t=r,"undefined"!=typeof Buffer?Buffer.from(t).toString("base64"):btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)})));return"\\htmlClass{smiles-node}{\\text{".concat(n,"}}")}},aa=function(e,t){if(!e||!e.includes("smiles-node"))return e;if(!t)return e;var r=document.createElement("div");r.innerHTML=e;var n=r.querySelectorAll(".smiles-node");return n&&0!==n.length?(n.forEach(function(e){var r,n=e.textContent;try{var a=(r=n,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString():decodeURIComponent(atob(r).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join("")));e.outerHTML=t.render(a)}catch(e){console.error("Error decoding/rendering smiles",e)}}),r.innerHTML):e};class ia{constructor(e,t,r){this.lexer=void 0,this.start=void 0,this.end=void 0,this.lexer=e,this.start=t,this.end=r}static range(e,t){return t?e&&e.loc&&t.loc&&e.loc.lexer===t.loc.lexer?new ia(e.loc.lexer,e.loc.start,t.loc.end):null:e&&e.loc}}class oa{constructor(e,t){this.text=void 0,this.loc=void 0,this.noexpand=void 0,this.treatAsRelax=void 0,this.text=e,this.loc=t}range(e,t){return new oa(t,ia.range(this,e))}}class sa{constructor(e,t){this.name=void 0,this.position=void 0,this.length=void 0,this.rawMessage=void 0;var r,n,a="KaTeX parse error: "+e,i=t&&t.loc;if(i&&i.start<=i.end){var o=i.lexer.input;r=i.start,n=i.end,r===o.length?a+=" at end of input: ":a+=" at position "+(r+1)+": ";var s=o.slice(r,n).replace(/[^]/g,"$&̲");a+=(r>15?"…"+o.slice(r-15,r):o.slice(0,r))+s+(n+15<o.length?o.slice(n,n+15)+"…":o.slice(n))}var l=new Error(a);return l.name="ParseError",l.__proto__=sa.prototype,l.position=r,null!=r&&null!=n&&(l.length=n-r),l.rawMessage=e,l}}sa.prototype.__proto__=Error.prototype;var la=/([A-Z])/g,ca={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},da=/[&><"']/g;var ua=function e(t){return"ordgroup"===t.type||"color"===t.type?1===t.body.length?e(t.body[0]):t:"font"===t.type?e(t.body):t},pa={deflt:function(e,t){return void 0===e?t:e},escape:function(e){return String(e).replace(da,e=>ca[e])},hyphenate:function(e){return e.replace(la,"-$1").toLowerCase()},getBaseElem:ua,isCharacterBox:function(e){var t=ua(e);return"mathord"===t.type||"textord"===t.type||"atom"===t.type},protocolFromUrl:function(e){var t=/^[\x00-\x20]*([^\\/#?]*?)(:|&#0*58|&#x0*3a|&colon)/i.exec(e);return t?":"!==t[2]?null:/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(t[1])?t[1].toLowerCase():null:"_relative"}},_a={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format <type>"},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color <color>",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:e=>"#"+e},macros:{type:"object",cli:"-m, --macro <def>",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:(e,t)=>(t.push(e),t)},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:e=>Math.max(0,e),cli:"--min-rule-thickness <size>",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:e=>Math.max(0,e),cli:"-s, --max-size <n>",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:e=>Math.max(0,e),cli:"-e, --max-expand <n>",cliProcessor:e=>"Infinity"===e?1/0:parseInt(e)},globalGroup:{type:"boolean",cli:!1}};function ma(e){if(e.default)return e.default;var t=e.type,r=Array.isArray(t)?t[0]:t;if("string"!=typeof r)return r.enum[0];switch(r){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{}}}class ga{constructor(e){for(var t in this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e=e||{},_a)if(_a.hasOwnProperty(t)){var r=_a[t];this[t]=void 0!==e[t]?r.processor?r.processor(e[t]):e[t]:ma(r)}}reportNonstrict(e,t,r){var n=this.strict;if("function"==typeof n&&(n=n(e,t,r)),n&&"ignore"!==n){if(!0===n||"error"===n)throw new sa("LaTeX-incompatible input and strict mode is set to 'error': "+t+" ["+e+"]",r);"warn"===n?"undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+t+" ["+e+"]"):"undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to unrecognized '"+n+"': "+t+" ["+e+"]")}}useStrictBehavior(e,t,r){var n=this.strict;if("function"==typeof n)try{n=n(e,t,r)}catch(e){n="error"}return!(!n||"ignore"===n)&&(!0===n||"error"===n||("warn"===n?("undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+t+" ["+e+"]"),!1):("undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to unrecognized '"+n+"': "+t+" ["+e+"]"),!1)))}isTrusted(e){if(e.url&&!e.protocol){var t=pa.protocolFromUrl(e.url);if(null==t)return!1;e.protocol=t}var r="function"==typeof this.trust?this.trust(e):this.trust;return Boolean(r)}}class ha{constructor(e,t,r){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=t,this.cramped=r}sup(){return fa[Ea[this.id]]}sub(){return fa[ba[this.id]]}fracNum(){return fa[Sa[this.id]]}fracDen(){return fa[va[this.id]]}cramp(){return fa[Ta[this.id]]}text(){return fa[ya[this.id]]}isTight(){return this.size>=2}}var fa=[new ha(0,0,!1),new ha(1,0,!0),new ha(2,1,!1),new ha(3,1,!0),new ha(4,2,!1),new ha(5,2,!0),new ha(6,3,!1),new ha(7,3,!0)],Ea=[4,5,4,5,6,7,6,7],ba=[5,5,5,5,7,7,7,7],Sa=[2,3,4,5,6,7,6,7],va=[3,3,5,5,7,7,7,7],Ta=[1,1,3,3,5,5,7,7],ya=[0,1,2,3,2,3,2,3],Ca={DISPLAY:fa[0],TEXT:fa[2],SCRIPT:fa[4],SCRIPTSCRIPT:fa[6]},Na=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"armenian",blocks:[[1328,1423]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];var Ra=[];function Aa(e){for(var t=0;t<Ra.length;t+=2)if(e>=Ra[t]&&e<=Ra[t+1])return!0;return!1}Na.forEach(e=>e.blocks.forEach(e=>Ra.push(...e)));var Oa=80,Ia={doubleleftarrow:"M262 157\nl10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3\n 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28\n 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5\nc2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5\n 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87\n-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7\n-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z\nm8 0v40h399730v-40zm0 194v40h399730v-40z",doublerightarrow:"M399738 392l\n-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5\n 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88\n-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68\n-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18\n-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782\nc-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3\n-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z",leftarrow:"M400000 241H110l3-3c68.7-52.7 113.7-120\n 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8\n-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247\nc-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208\n 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3\n 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202\n l-3-3h399890zM100 241v40h399900v-40z",leftbrace:"M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117\n-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7\n 5-6 9-10 13-.7 1-7.3 1-20 1H6z",leftbraceunder:"M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13\n 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688\n 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7\n-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z",leftgroup:"M400000 80\nH435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0\n 435 0h399565z",leftgroupunder:"M400000 262\nH435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219\n 435 219h399565z",leftharpoon:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3\n-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5\n-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7\n-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z",leftharpoonplus:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5\n 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3\n-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7\n-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z\nm0 0v40h400000v-40z",leftharpoondown:"M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333\n 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5\n 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667\n-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z",leftharpoondownplus:"M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12\n 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7\n-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0\nv40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z",lefthook:"M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5\n-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3\n-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21\n 71.5 23h399859zM103 281v-40h399897v40z",leftlinesegment:"M40 281 V428 H0 V94 H40 V241 H400000 v40z\nM40 281 V428 H0 V94 H40 V241 H400000 v40z",leftmapsto:"M40 281 V448H0V74H40V241H400000v40z\nM40 281 V448H0V74H40V241H400000v40z",leftToFrom:"M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23\n-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8\nc28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3\n 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z",longequal:"M0 50 h400000 v40H0z m0 194h40000v40H0z\nM0 50 h400000 v40H0z m0 194h40000v40H0z",midbrace:"M200428 334\nc-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14\n-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7\n 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11\n 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z",midbraceunder:"M199572 214\nc100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14\n 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3\n 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0\n-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z",oiintSize1:"M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6\n-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z\nm368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8\n60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z",oiintSize2:"M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8\n-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z\nm502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2\nc0 110 84 276 504 276s502.4-166 502.4-276z",oiiintSize1:"M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6\n-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z\nm525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0\n85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z",oiiintSize2:"M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8\n-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z\nm770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1\nc0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z",rightarrow:"M0 241v40h399891c-47.3 35.3-84 78-110 128\n-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20\n 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7\n 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85\n-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n 151.7 139 205zm0 0v40h399900v-40z",rightbrace:"M400000 542l\n-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5\ns-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1\nc124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z",rightbraceunder:"M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3\n 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237\n-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z",rightgroup:"M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0\n 3-1 3-3v-38c-76-158-257-219-435-219H0z",rightgroupunder:"M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18\n 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z",rightharpoon:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3\n-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2\n-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58\n 69.2 92 94.5zm0 0v40h399900v-40z",rightharpoonplus:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11\n-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7\n 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z\nm0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z",rightharpoondown:"M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8\n 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5\n-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95\n-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z",rightharpoondownplus:"M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8\n 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3\n 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3\n-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z\nm0-194v40h400000v-40zm0 0v40h400000v-40z",righthook:"M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3\n 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0\n-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21\n 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z",rightlinesegment:"M399960 241 V94 h40 V428 h-40 V281 H0 v-40z\nM399960 241 V94 h40 V428 h-40 V281 H0 v-40z",rightToFrom:"M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23\n 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32\n-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142\n-167z M100 147v40h399900v-40zM0 341v40h399900v-40z",twoheadleftarrow:"M0 167c68 40\n 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69\n-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3\n-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19\n-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101\n 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z",twoheadrightarrow:"M400000 167\nc-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3\n 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42\n 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333\n-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70\n 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z",tilde1:"M200 55.538c-77 0-168 73.953-177 73.953-3 0-7\n-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0\n 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0\n 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128\n-68.267.847-113-73.952-191-73.952z",tilde2:"M344 55.266c-142 0-300.638 81.316-311.5 86.418\n-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9\n 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114\nc1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751\n 181.476 676 181.476c-149 0-189-126.21-332-126.21z",tilde3:"M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457\n-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0\n 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697\n 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696\n -338 0-409-156.573-744-156.573z",tilde4:"M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345\n-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409\n 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9\n 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409\n -175.236-744-175.236z",vec:"M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5\n3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11\n10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63\n-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1\n-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59\nH213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359\nc-16-25.333-24-45-24-59z",widehat1:"M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22\nc-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z",widehat2:"M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat3:"M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat4:"M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widecheck1:"M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,\n-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z",widecheck2:"M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck3:"M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck4:"M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",baraboveleftarrow:"M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202\nc4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5\nc-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130\ns-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47\n121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6\ns2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11\nc0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z\nM100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z",rightarrowabovebar:"M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32\n-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0\n13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39\n-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5\n-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z",baraboveshortleftharpoon:"M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17\nc2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21\nc-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40\nc-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z\nM0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z",rightharpoonaboveshortbar:"M0,241 l0,40c399126,0,399993,0,399993,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z",shortbaraboveleftharpoon:"M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,\n1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,\n-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z\nM93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z",shortrightharpoonabovebar:"M53,241l0,40c398570,0,399437,0,399437,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z"};class xa{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t<this.children.length;t++)e.appendChild(this.children[t].toNode());return e}toMarkup(){for(var e="",t=0;t<this.children.length;t++)e+=this.children[t].toMarkup();return e}toText(){return this.children.map(e=>e.toText()).join("")}}var wa={"AMS-Regular":{32:[0,0,0,0,.25],65:[0,.68889,0,0,.72222],66:[0,.68889,0,0,.66667],67:[0,.68889,0,0,.72222],68:[0,.68889,0,0,.72222],69:[0,.68889,0,0,.66667],70:[0,.68889,0,0,.61111],71:[0,.68889,0,0,.77778],72:[0,.68889,0,0,.77778],73:[0,.68889,0,0,.38889],74:[.16667,.68889,0,0,.5],75:[0,.68889,0,0,.77778],76:[0,.68889,0,0,.66667],77:[0,.68889,0,0,.94445],78:[0,.68889,0,0,.72222],79:[.16667,.68889,0,0,.77778],80:[0,.68889,0,0,.61111],81:[.16667,.68889,0,0,.77778],82:[0,.68889,0,0,.72222],83:[0,.68889,0,0,.55556],84:[0,.68889,0,0,.66667],85:[0,.68889,0,0,.72222],86:[0,.68889,0,0,.72222],87:[0,.68889,0,0,1],88:[0,.68889,0,0,.72222],89:[0,.68889,0,0,.72222],90:[0,.68889,0,0,.66667],107:[0,.68889,0,0,.55556],160:[0,0,0,0,.25],165:[0,.675,.025,0,.75],174:[.15559,.69224,0,0,.94666],240:[0,.68889,0,0,.55556],295:[0,.68889,0,0,.54028],710:[0,.825,0,0,2.33334],732:[0,.9,0,0,2.33334],770:[0,.825,0,0,2.33334],771:[0,.9,0,0,2.33334],989:[.08167,.58167,0,0,.77778],1008:[0,.43056,.04028,0,.66667],8245:[0,.54986,0,0,.275],8463:[0,.68889,0,0,.54028],8487:[0,.68889,0,0,.72222],8498:[0,.68889,0,0,.55556],8502:[0,.68889,0,0,.66667],8503:[0,.68889,0,0,.44445],8504:[0,.68889,0,0,.66667],8513:[0,.68889,0,0,.63889],8592:[-.03598,.46402,0,0,.5],8594:[-.03598,.46402,0,0,.5],8602:[-.13313,.36687,0,0,1],8603:[-.13313,.36687,0,0,1],8606:[.01354,.52239,0,0,1],8608:[.01354,.52239,0,0,1],8610:[.01354,.52239,0,0,1.11111],8611:[.01354,.52239,0,0,1.11111],8619:[0,.54986,0,0,1],8620:[0,.54986,0,0,1],8621:[-.13313,.37788,0,0,1.38889],8622:[-.13313,.36687,0,0,1],8624:[0,.69224,0,0,.5],8625:[0,.69224,0,0,.5],8630:[0,.43056,0,0,1],8631:[0,.43056,0,0,1],8634:[.08198,.58198,0,0,.77778],8635:[.08198,.58198,0,0,.77778],8638:[.19444,.69224,0,0,.41667],8639:[.19444,.69224,0,0,.41667],8642:[.19444,.69224,0,0,.41667],8643:[.19444,.69224,0,0,.41667],8644:[.1808,.675,0,0,1],8646:[.1808,.675,0,0,1],8647:[.1808,.675,0,0,1],8648:[.19444,.69224,0,0,.83334],8649:[.1808,.675,0,0,1],8650:[.19444,.69224,0,0,.83334],8651:[.01354,.52239,0,0,1],8652:[.01354,.52239,0,0,1],8653:[-.13313,.36687,0,0,1],8654:[-.13313,.36687,0,0,1],8655:[-.13313,.36687,0,0,1],8666:[.13667,.63667,0,0,1],8667:[.13667,.63667,0,0,1],8669:[-.13313,.37788,0,0,1],8672:[-.064,.437,0,0,1.334],8674:[-.064,.437,0,0,1.334],8705:[0,.825,0,0,.5],8708:[0,.68889,0,0,.55556],8709:[.08167,.58167,0,0,.77778],8717:[0,.43056,0,0,.42917],8722:[-.03598,.46402,0,0,.5],8724:[.08198,.69224,0,0,.77778],8726:[.08167,.58167,0,0,.77778],8733:[0,.69224,0,0,.77778],8736:[0,.69224,0,0,.72222],8737:[0,.69224,0,0,.72222],8738:[.03517,.52239,0,0,.72222],8739:[.08167,.58167,0,0,.22222],8740:[.25142,.74111,0,0,.27778],8741:[.08167,.58167,0,0,.38889],8742:[.25142,.74111,0,0,.5],8756:[0,.69224,0,0,.66667],8757:[0,.69224,0,0,.66667],8764:[-.13313,.36687,0,0,.77778],8765:[-.13313,.37788,0,0,.77778],8769:[-.13313,.36687,0,0,.77778],8770:[-.03625,.46375,0,0,.77778],8774:[.30274,.79383,0,0,.77778],8776:[-.01688,.48312,0,0,.77778],8778:[.08167,.58167,0,0,.77778],8782:[.06062,.54986,0,0,.77778],8783:[.06062,.54986,0,0,.77778],8785:[.08198,.58198,0,0,.77778],8786:[.08198,.58198,0,0,.77778],8787:[.08198,.58198,0,0,.77778],8790:[0,.69224,0,0,.77778],8791:[.22958,.72958,0,0,.77778],8796:[.08198,.91667,0,0,.77778],8806:[.25583,.75583,0,0,.77778],8807:[.25583,.75583,0,0,.77778],8808:[.25142,.75726,0,0,.77778],8809:[.25142,.75726,0,0,.77778],8812:[.25583,.75583,0,0,.5],8814:[.20576,.70576,0,0,.77778],8815:[.20576,.70576,0,0,.77778],8816:[.30274,.79383,0,0,.77778],8817:[.30274,.79383,0,0,.77778],8818:[.22958,.72958,0,0,.77778],8819:[.22958,.72958,0,0,.77778],8822:[.1808,.675,0,0,.77778],8823:[.1808,.675,0,0,.77778],8828:[.13667,.63667,0,0,.77778],8829:[.13667,.63667,0,0,.77778],8830:[.22958,.72958,0,0,.77778],8831:[.22958,.72958,0,0,.77778],8832:[.20576,.70576,0,0,.77778],8833:[.20576,.70576,0,0,.77778],8840:[.30274,.79383,0,0,.77778],8841:[.30274,.79383,0,0,.77778],8842:[.13597,.63597,0,0,.77778],8843:[.13597,.63597,0,0,.77778],8847:[.03517,.54986,0,0,.77778],8848:[.03517,.54986,0,0,.77778],8858:[.08198,.58198,0,0,.77778],8859:[.08198,.58198,0,0,.77778],8861:[.08198,.58198,0,0,.77778],8862:[0,.675,0,0,.77778],8863:[0,.675,0,0,.77778],8864:[0,.675,0,0,.77778],8865:[0,.675,0,0,.77778],8872:[0,.69224,0,0,.61111],8873:[0,.69224,0,0,.72222],8874:[0,.69224,0,0,.88889],8876:[0,.68889,0,0,.61111],8877:[0,.68889,0,0,.61111],8878:[0,.68889,0,0,.72222],8879:[0,.68889,0,0,.72222],8882:[.03517,.54986,0,0,.77778],8883:[.03517,.54986,0,0,.77778],8884:[.13667,.63667,0,0,.77778],8885:[.13667,.63667,0,0,.77778],8888:[0,.54986,0,0,1.11111],8890:[.19444,.43056,0,0,.55556],8891:[.19444,.69224,0,0,.61111],8892:[.19444,.69224,0,0,.61111],8901:[0,.54986,0,0,.27778],8903:[.08167,.58167,0,0,.77778],8905:[.08167,.58167,0,0,.77778],8906:[.08167,.58167,0,0,.77778],8907:[0,.69224,0,0,.77778],8908:[0,.69224,0,0,.77778],8909:[-.03598,.46402,0,0,.77778],8910:[0,.54986,0,0,.76042],8911:[0,.54986,0,0,.76042],8912:[.03517,.54986,0,0,.77778],8913:[.03517,.54986,0,0,.77778],8914:[0,.54986,0,0,.66667],8915:[0,.54986,0,0,.66667],8916:[0,.69224,0,0,.66667],8918:[.0391,.5391,0,0,.77778],8919:[.0391,.5391,0,0,.77778],8920:[.03517,.54986,0,0,1.33334],8921:[.03517,.54986,0,0,1.33334],8922:[.38569,.88569,0,0,.77778],8923:[.38569,.88569,0,0,.77778],8926:[.13667,.63667,0,0,.77778],8927:[.13667,.63667,0,0,.77778],8928:[.30274,.79383,0,0,.77778],8929:[.30274,.79383,0,0,.77778],8934:[.23222,.74111,0,0,.77778],8935:[.23222,.74111,0,0,.77778],8936:[.23222,.74111,0,0,.77778],8937:[.23222,.74111,0,0,.77778],8938:[.20576,.70576,0,0,.77778],8939:[.20576,.70576,0,0,.77778],8940:[.30274,.79383,0,0,.77778],8941:[.30274,.79383,0,0,.77778],8994:[.19444,.69224,0,0,.77778],8995:[.19444,.69224,0,0,.77778],9416:[.15559,.69224,0,0,.90222],9484:[0,.69224,0,0,.5],9488:[0,.69224,0,0,.5],9492:[0,.37788,0,0,.5],9496:[0,.37788,0,0,.5],9585:[.19444,.68889,0,0,.88889],9586:[.19444,.74111,0,0,.88889],9632:[0,.675,0,0,.77778],9633:[0,.675,0,0,.77778],9650:[0,.54986,0,0,.72222],9651:[0,.54986,0,0,.72222],9654:[.03517,.54986,0,0,.77778],9660:[0,.54986,0,0,.72222],9661:[0,.54986,0,0,.72222],9664:[.03517,.54986,0,0,.77778],9674:[.11111,.69224,0,0,.66667],9733:[.19444,.69224,0,0,.94445],10003:[0,.69224,0,0,.83334],10016:[0,.69224,0,0,.83334],10731:[.11111,.69224,0,0,.66667],10846:[.19444,.75583,0,0,.61111],10877:[.13667,.63667,0,0,.77778],10878:[.13667,.63667,0,0,.77778],10885:[.25583,.75583,0,0,.77778],10886:[.25583,.75583,0,0,.77778],10887:[.13597,.63597,0,0,.77778],10888:[.13597,.63597,0,0,.77778],10889:[.26167,.75726,0,0,.77778],10890:[.26167,.75726,0,0,.77778],10891:[.48256,.98256,0,0,.77778],10892:[.48256,.98256,0,0,.77778],10901:[.13667,.63667,0,0,.77778],10902:[.13667,.63667,0,0,.77778],10933:[.25142,.75726,0,0,.77778],10934:[.25142,.75726,0,0,.77778],10935:[.26167,.75726,0,0,.77778],10936:[.26167,.75726,0,0,.77778],10937:[.26167,.75726,0,0,.77778],10938:[.26167,.75726,0,0,.77778],10949:[.25583,.75583,0,0,.77778],10950:[.25583,.75583,0,0,.77778],10955:[.28481,.79383,0,0,.77778],10956:[.28481,.79383,0,0,.77778],57350:[.08167,.58167,0,0,.22222],57351:[.08167,.58167,0,0,.38889],57352:[.08167,.58167,0,0,.77778],57353:[0,.43056,.04028,0,.66667],57356:[.25142,.75726,0,0,.77778],57357:[.25142,.75726,0,0,.77778],57358:[.41951,.91951,0,0,.77778],57359:[.30274,.79383,0,0,.77778],57360:[.30274,.79383,0,0,.77778],57361:[.41951,.91951,0,0,.77778],57366:[.25142,.75726,0,0,.77778],57367:[.25142,.75726,0,0,.77778],57368:[.25142,.75726,0,0,.77778],57369:[.25142,.75726,0,0,.77778],57370:[.13597,.63597,0,0,.77778],57371:[.13597,.63597,0,0,.77778]},"Caligraphic-Regular":{32:[0,0,0,0,.25],65:[0,.68333,0,.19445,.79847],66:[0,.68333,.03041,.13889,.65681],67:[0,.68333,.05834,.13889,.52653],68:[0,.68333,.02778,.08334,.77139],69:[0,.68333,.08944,.11111,.52778],70:[0,.68333,.09931,.11111,.71875],71:[.09722,.68333,.0593,.11111,.59487],72:[0,.68333,.00965,.11111,.84452],73:[0,.68333,.07382,0,.54452],74:[.09722,.68333,.18472,.16667,.67778],75:[0,.68333,.01445,.05556,.76195],76:[0,.68333,0,.13889,.68972],77:[0,.68333,0,.13889,1.2009],78:[0,.68333,.14736,.08334,.82049],79:[0,.68333,.02778,.11111,.79611],80:[0,.68333,.08222,.08334,.69556],81:[.09722,.68333,0,.11111,.81667],82:[0,.68333,0,.08334,.8475],83:[0,.68333,.075,.13889,.60556],84:[0,.68333,.25417,0,.54464],85:[0,.68333,.09931,.08334,.62583],86:[0,.68333,.08222,0,.61278],87:[0,.68333,.08222,.08334,.98778],88:[0,.68333,.14643,.13889,.7133],89:[.09722,.68333,.08222,.08334,.66834],90:[0,.68333,.07944,.13889,.72473],160:[0,0,0,0,.25]},"Fraktur-Regular":{32:[0,0,0,0,.25],33:[0,.69141,0,0,.29574],34:[0,.69141,0,0,.21471],38:[0,.69141,0,0,.73786],39:[0,.69141,0,0,.21201],40:[.24982,.74947,0,0,.38865],41:[.24982,.74947,0,0,.38865],42:[0,.62119,0,0,.27764],43:[.08319,.58283,0,0,.75623],44:[0,.10803,0,0,.27764],45:[.08319,.58283,0,0,.75623],46:[0,.10803,0,0,.27764],47:[.24982,.74947,0,0,.50181],48:[0,.47534,0,0,.50181],49:[0,.47534,0,0,.50181],50:[0,.47534,0,0,.50181],51:[.18906,.47534,0,0,.50181],52:[.18906,.47534,0,0,.50181],53:[.18906,.47534,0,0,.50181],54:[0,.69141,0,0,.50181],55:[.18906,.47534,0,0,.50181],56:[0,.69141,0,0,.50181],57:[.18906,.47534,0,0,.50181],58:[0,.47534,0,0,.21606],59:[.12604,.47534,0,0,.21606],61:[-.13099,.36866,0,0,.75623],63:[0,.69141,0,0,.36245],65:[0,.69141,0,0,.7176],66:[0,.69141,0,0,.88397],67:[0,.69141,0,0,.61254],68:[0,.69141,0,0,.83158],69:[0,.69141,0,0,.66278],70:[.12604,.69141,0,0,.61119],71:[0,.69141,0,0,.78539],72:[.06302,.69141,0,0,.7203],73:[0,.69141,0,0,.55448],74:[.12604,.69141,0,0,.55231],75:[0,.69141,0,0,.66845],76:[0,.69141,0,0,.66602],77:[0,.69141,0,0,1.04953],78:[0,.69141,0,0,.83212],79:[0,.69141,0,0,.82699],80:[.18906,.69141,0,0,.82753],81:[.03781,.69141,0,0,.82699],82:[0,.69141,0,0,.82807],83:[0,.69141,0,0,.82861],84:[0,.69141,0,0,.66899],85:[0,.69141,0,0,.64576],86:[0,.69141,0,0,.83131],87:[0,.69141,0,0,1.04602],88:[0,.69141,0,0,.71922],89:[.18906,.69141,0,0,.83293],90:[.12604,.69141,0,0,.60201],91:[.24982,.74947,0,0,.27764],93:[.24982,.74947,0,0,.27764],94:[0,.69141,0,0,.49965],97:[0,.47534,0,0,.50046],98:[0,.69141,0,0,.51315],99:[0,.47534,0,0,.38946],100:[0,.62119,0,0,.49857],101:[0,.47534,0,0,.40053],102:[.18906,.69141,0,0,.32626],103:[.18906,.47534,0,0,.5037],104:[.18906,.69141,0,0,.52126],105:[0,.69141,0,0,.27899],106:[0,.69141,0,0,.28088],107:[0,.69141,0,0,.38946],108:[0,.69141,0,0,.27953],109:[0,.47534,0,0,.76676],110:[0,.47534,0,0,.52666],111:[0,.47534,0,0,.48885],112:[.18906,.52396,0,0,.50046],113:[.18906,.47534,0,0,.48912],114:[0,.47534,0,0,.38919],115:[0,.47534,0,0,.44266],116:[0,.62119,0,0,.33301],117:[0,.47534,0,0,.5172],118:[0,.52396,0,0,.5118],119:[0,.52396,0,0,.77351],120:[.18906,.47534,0,0,.38865],121:[.18906,.47534,0,0,.49884],122:[.18906,.47534,0,0,.39054],160:[0,0,0,0,.25],8216:[0,.69141,0,0,.21471],8217:[0,.69141,0,0,.21471],58112:[0,.62119,0,0,.49749],58113:[0,.62119,0,0,.4983],58114:[.18906,.69141,0,0,.33328],58115:[.18906,.69141,0,0,.32923],58116:[.18906,.47534,0,0,.50343],58117:[0,.69141,0,0,.33301],58118:[0,.62119,0,0,.33409],58119:[0,.47534,0,0,.50073]},"Main-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.35],34:[0,.69444,0,0,.60278],35:[.19444,.69444,0,0,.95833],36:[.05556,.75,0,0,.575],37:[.05556,.75,0,0,.95833],38:[0,.69444,0,0,.89444],39:[0,.69444,0,0,.31944],40:[.25,.75,0,0,.44722],41:[.25,.75,0,0,.44722],42:[0,.75,0,0,.575],43:[.13333,.63333,0,0,.89444],44:[.19444,.15556,0,0,.31944],45:[0,.44444,0,0,.38333],46:[0,.15556,0,0,.31944],47:[.25,.75,0,0,.575],48:[0,.64444,0,0,.575],49:[0,.64444,0,0,.575],50:[0,.64444,0,0,.575],51:[0,.64444,0,0,.575],52:[0,.64444,0,0,.575],53:[0,.64444,0,0,.575],54:[0,.64444,0,0,.575],55:[0,.64444,0,0,.575],56:[0,.64444,0,0,.575],57:[0,.64444,0,0,.575],58:[0,.44444,0,0,.31944],59:[.19444,.44444,0,0,.31944],60:[.08556,.58556,0,0,.89444],61:[-.10889,.39111,0,0,.89444],62:[.08556,.58556,0,0,.89444],63:[0,.69444,0,0,.54305],64:[0,.69444,0,0,.89444],65:[0,.68611,0,0,.86944],66:[0,.68611,0,0,.81805],67:[0,.68611,0,0,.83055],68:[0,.68611,0,0,.88194],69:[0,.68611,0,0,.75555],70:[0,.68611,0,0,.72361],71:[0,.68611,0,0,.90416],72:[0,.68611,0,0,.9],73:[0,.68611,0,0,.43611],74:[0,.68611,0,0,.59444],75:[0,.68611,0,0,.90138],76:[0,.68611,0,0,.69166],77:[0,.68611,0,0,1.09166],78:[0,.68611,0,0,.9],79:[0,.68611,0,0,.86388],80:[0,.68611,0,0,.78611],81:[.19444,.68611,0,0,.86388],82:[0,.68611,0,0,.8625],83:[0,.68611,0,0,.63889],84:[0,.68611,0,0,.8],85:[0,.68611,0,0,.88472],86:[0,.68611,.01597,0,.86944],87:[0,.68611,.01597,0,1.18888],88:[0,.68611,0,0,.86944],89:[0,.68611,.02875,0,.86944],90:[0,.68611,0,0,.70277],91:[.25,.75,0,0,.31944],92:[.25,.75,0,0,.575],93:[.25,.75,0,0,.31944],94:[0,.69444,0,0,.575],95:[.31,.13444,.03194,0,.575],97:[0,.44444,0,0,.55902],98:[0,.69444,0,0,.63889],99:[0,.44444,0,0,.51111],100:[0,.69444,0,0,.63889],101:[0,.44444,0,0,.52708],102:[0,.69444,.10903,0,.35139],103:[.19444,.44444,.01597,0,.575],104:[0,.69444,0,0,.63889],105:[0,.69444,0,0,.31944],106:[.19444,.69444,0,0,.35139],107:[0,.69444,0,0,.60694],108:[0,.69444,0,0,.31944],109:[0,.44444,0,0,.95833],110:[0,.44444,0,0,.63889],111:[0,.44444,0,0,.575],112:[.19444,.44444,0,0,.63889],113:[.19444,.44444,0,0,.60694],114:[0,.44444,0,0,.47361],115:[0,.44444,0,0,.45361],116:[0,.63492,0,0,.44722],117:[0,.44444,0,0,.63889],118:[0,.44444,.01597,0,.60694],119:[0,.44444,.01597,0,.83055],120:[0,.44444,0,0,.60694],121:[.19444,.44444,.01597,0,.60694],122:[0,.44444,0,0,.51111],123:[.25,.75,0,0,.575],124:[.25,.75,0,0,.31944],125:[.25,.75,0,0,.575],126:[.35,.34444,0,0,.575],160:[0,0,0,0,.25],163:[0,.69444,0,0,.86853],168:[0,.69444,0,0,.575],172:[0,.44444,0,0,.76666],176:[0,.69444,0,0,.86944],177:[.13333,.63333,0,0,.89444],184:[.17014,0,0,0,.51111],198:[0,.68611,0,0,1.04166],215:[.13333,.63333,0,0,.89444],216:[.04861,.73472,0,0,.89444],223:[0,.69444,0,0,.59722],230:[0,.44444,0,0,.83055],247:[.13333,.63333,0,0,.89444],248:[.09722,.54167,0,0,.575],305:[0,.44444,0,0,.31944],338:[0,.68611,0,0,1.16944],339:[0,.44444,0,0,.89444],567:[.19444,.44444,0,0,.35139],710:[0,.69444,0,0,.575],711:[0,.63194,0,0,.575],713:[0,.59611,0,0,.575],714:[0,.69444,0,0,.575],715:[0,.69444,0,0,.575],728:[0,.69444,0,0,.575],729:[0,.69444,0,0,.31944],730:[0,.69444,0,0,.86944],732:[0,.69444,0,0,.575],733:[0,.69444,0,0,.575],915:[0,.68611,0,0,.69166],916:[0,.68611,0,0,.95833],920:[0,.68611,0,0,.89444],923:[0,.68611,0,0,.80555],926:[0,.68611,0,0,.76666],928:[0,.68611,0,0,.9],931:[0,.68611,0,0,.83055],933:[0,.68611,0,0,.89444],934:[0,.68611,0,0,.83055],936:[0,.68611,0,0,.89444],937:[0,.68611,0,0,.83055],8211:[0,.44444,.03194,0,.575],8212:[0,.44444,.03194,0,1.14999],8216:[0,.69444,0,0,.31944],8217:[0,.69444,0,0,.31944],8220:[0,.69444,0,0,.60278],8221:[0,.69444,0,0,.60278],8224:[.19444,.69444,0,0,.51111],8225:[.19444,.69444,0,0,.51111],8242:[0,.55556,0,0,.34444],8407:[0,.72444,.15486,0,.575],8463:[0,.69444,0,0,.66759],8465:[0,.69444,0,0,.83055],8467:[0,.69444,0,0,.47361],8472:[.19444,.44444,0,0,.74027],8476:[0,.69444,0,0,.83055],8501:[0,.69444,0,0,.70277],8592:[-.10889,.39111,0,0,1.14999],8593:[.19444,.69444,0,0,.575],8594:[-.10889,.39111,0,0,1.14999],8595:[.19444,.69444,0,0,.575],8596:[-.10889,.39111,0,0,1.14999],8597:[.25,.75,0,0,.575],8598:[.19444,.69444,0,0,1.14999],8599:[.19444,.69444,0,0,1.14999],8600:[.19444,.69444,0,0,1.14999],8601:[.19444,.69444,0,0,1.14999],8636:[-.10889,.39111,0,0,1.14999],8637:[-.10889,.39111,0,0,1.14999],8640:[-.10889,.39111,0,0,1.14999],8641:[-.10889,.39111,0,0,1.14999],8656:[-.10889,.39111,0,0,1.14999],8657:[.19444,.69444,0,0,.70277],8658:[-.10889,.39111,0,0,1.14999],8659:[.19444,.69444,0,0,.70277],8660:[-.10889,.39111,0,0,1.14999],8661:[.25,.75,0,0,.70277],8704:[0,.69444,0,0,.63889],8706:[0,.69444,.06389,0,.62847],8707:[0,.69444,0,0,.63889],8709:[.05556,.75,0,0,.575],8711:[0,.68611,0,0,.95833],8712:[.08556,.58556,0,0,.76666],8715:[.08556,.58556,0,0,.76666],8722:[.13333,.63333,0,0,.89444],8723:[.13333,.63333,0,0,.89444],8725:[.25,.75,0,0,.575],8726:[.25,.75,0,0,.575],8727:[-.02778,.47222,0,0,.575],8728:[-.02639,.47361,0,0,.575],8729:[-.02639,.47361,0,0,.575],8730:[.18,.82,0,0,.95833],8733:[0,.44444,0,0,.89444],8734:[0,.44444,0,0,1.14999],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.31944],8741:[.25,.75,0,0,.575],8743:[0,.55556,0,0,.76666],8744:[0,.55556,0,0,.76666],8745:[0,.55556,0,0,.76666],8746:[0,.55556,0,0,.76666],8747:[.19444,.69444,.12778,0,.56875],8764:[-.10889,.39111,0,0,.89444],8768:[.19444,.69444,0,0,.31944],8771:[.00222,.50222,0,0,.89444],8773:[.027,.638,0,0,.894],8776:[.02444,.52444,0,0,.89444],8781:[.00222,.50222,0,0,.89444],8801:[.00222,.50222,0,0,.89444],8804:[.19667,.69667,0,0,.89444],8805:[.19667,.69667,0,0,.89444],8810:[.08556,.58556,0,0,1.14999],8811:[.08556,.58556,0,0,1.14999],8826:[.08556,.58556,0,0,.89444],8827:[.08556,.58556,0,0,.89444],8834:[.08556,.58556,0,0,.89444],8835:[.08556,.58556,0,0,.89444],8838:[.19667,.69667,0,0,.89444],8839:[.19667,.69667,0,0,.89444],8846:[0,.55556,0,0,.76666],8849:[.19667,.69667,0,0,.89444],8850:[.19667,.69667,0,0,.89444],8851:[0,.55556,0,0,.76666],8852:[0,.55556,0,0,.76666],8853:[.13333,.63333,0,0,.89444],8854:[.13333,.63333,0,0,.89444],8855:[.13333,.63333,0,0,.89444],8856:[.13333,.63333,0,0,.89444],8857:[.13333,.63333,0,0,.89444],8866:[0,.69444,0,0,.70277],8867:[0,.69444,0,0,.70277],8868:[0,.69444,0,0,.89444],8869:[0,.69444,0,0,.89444],8900:[-.02639,.47361,0,0,.575],8901:[-.02639,.47361,0,0,.31944],8902:[-.02778,.47222,0,0,.575],8968:[.25,.75,0,0,.51111],8969:[.25,.75,0,0,.51111],8970:[.25,.75,0,0,.51111],8971:[.25,.75,0,0,.51111],8994:[-.13889,.36111,0,0,1.14999],8995:[-.13889,.36111,0,0,1.14999],9651:[.19444,.69444,0,0,1.02222],9657:[-.02778,.47222,0,0,.575],9661:[.19444,.69444,0,0,1.02222],9667:[-.02778,.47222,0,0,.575],9711:[.19444,.69444,0,0,1.14999],9824:[.12963,.69444,0,0,.89444],9825:[.12963,.69444,0,0,.89444],9826:[.12963,.69444,0,0,.89444],9827:[.12963,.69444,0,0,.89444],9837:[0,.75,0,0,.44722],9838:[.19444,.69444,0,0,.44722],9839:[.19444,.69444,0,0,.44722],10216:[.25,.75,0,0,.44722],10217:[.25,.75,0,0,.44722],10815:[0,.68611,0,0,.9],10927:[.19667,.69667,0,0,.89444],10928:[.19667,.69667,0,0,.89444],57376:[.19444,.69444,0,0,0]},"Main-BoldItalic":{32:[0,0,0,0,.25],33:[0,.69444,.11417,0,.38611],34:[0,.69444,.07939,0,.62055],35:[.19444,.69444,.06833,0,.94444],37:[.05556,.75,.12861,0,.94444],38:[0,.69444,.08528,0,.88555],39:[0,.69444,.12945,0,.35555],40:[.25,.75,.15806,0,.47333],41:[.25,.75,.03306,0,.47333],42:[0,.75,.14333,0,.59111],43:[.10333,.60333,.03306,0,.88555],44:[.19444,.14722,0,0,.35555],45:[0,.44444,.02611,0,.41444],46:[0,.14722,0,0,.35555],47:[.25,.75,.15806,0,.59111],48:[0,.64444,.13167,0,.59111],49:[0,.64444,.13167,0,.59111],50:[0,.64444,.13167,0,.59111],51:[0,.64444,.13167,0,.59111],52:[.19444,.64444,.13167,0,.59111],53:[0,.64444,.13167,0,.59111],54:[0,.64444,.13167,0,.59111],55:[.19444,.64444,.13167,0,.59111],56:[0,.64444,.13167,0,.59111],57:[0,.64444,.13167,0,.59111],58:[0,.44444,.06695,0,.35555],59:[.19444,.44444,.06695,0,.35555],61:[-.10889,.39111,.06833,0,.88555],63:[0,.69444,.11472,0,.59111],64:[0,.69444,.09208,0,.88555],65:[0,.68611,0,0,.86555],66:[0,.68611,.0992,0,.81666],67:[0,.68611,.14208,0,.82666],68:[0,.68611,.09062,0,.87555],69:[0,.68611,.11431,0,.75666],70:[0,.68611,.12903,0,.72722],71:[0,.68611,.07347,0,.89527],72:[0,.68611,.17208,0,.8961],73:[0,.68611,.15681,0,.47166],74:[0,.68611,.145,0,.61055],75:[0,.68611,.14208,0,.89499],76:[0,.68611,0,0,.69777],77:[0,.68611,.17208,0,1.07277],78:[0,.68611,.17208,0,.8961],79:[0,.68611,.09062,0,.85499],80:[0,.68611,.0992,0,.78721],81:[.19444,.68611,.09062,0,.85499],82:[0,.68611,.02559,0,.85944],83:[0,.68611,.11264,0,.64999],84:[0,.68611,.12903,0,.7961],85:[0,.68611,.17208,0,.88083],86:[0,.68611,.18625,0,.86555],87:[0,.68611,.18625,0,1.15999],88:[0,.68611,.15681,0,.86555],89:[0,.68611,.19803,0,.86555],90:[0,.68611,.14208,0,.70888],91:[.25,.75,.1875,0,.35611],93:[.25,.75,.09972,0,.35611],94:[0,.69444,.06709,0,.59111],95:[.31,.13444,.09811,0,.59111],97:[0,.44444,.09426,0,.59111],98:[0,.69444,.07861,0,.53222],99:[0,.44444,.05222,0,.53222],100:[0,.69444,.10861,0,.59111],101:[0,.44444,.085,0,.53222],102:[.19444,.69444,.21778,0,.4],103:[.19444,.44444,.105,0,.53222],104:[0,.69444,.09426,0,.59111],105:[0,.69326,.11387,0,.35555],106:[.19444,.69326,.1672,0,.35555],107:[0,.69444,.11111,0,.53222],108:[0,.69444,.10861,0,.29666],109:[0,.44444,.09426,0,.94444],110:[0,.44444,.09426,0,.64999],111:[0,.44444,.07861,0,.59111],112:[.19444,.44444,.07861,0,.59111],113:[.19444,.44444,.105,0,.53222],114:[0,.44444,.11111,0,.50167],115:[0,.44444,.08167,0,.48694],116:[0,.63492,.09639,0,.385],117:[0,.44444,.09426,0,.62055],118:[0,.44444,.11111,0,.53222],119:[0,.44444,.11111,0,.76777],120:[0,.44444,.12583,0,.56055],121:[.19444,.44444,.105,0,.56166],122:[0,.44444,.13889,0,.49055],126:[.35,.34444,.11472,0,.59111],160:[0,0,0,0,.25],168:[0,.69444,.11473,0,.59111],176:[0,.69444,0,0,.94888],184:[.17014,0,0,0,.53222],198:[0,.68611,.11431,0,1.02277],216:[.04861,.73472,.09062,0,.88555],223:[.19444,.69444,.09736,0,.665],230:[0,.44444,.085,0,.82666],248:[.09722,.54167,.09458,0,.59111],305:[0,.44444,.09426,0,.35555],338:[0,.68611,.11431,0,1.14054],339:[0,.44444,.085,0,.82666],567:[.19444,.44444,.04611,0,.385],710:[0,.69444,.06709,0,.59111],711:[0,.63194,.08271,0,.59111],713:[0,.59444,.10444,0,.59111],714:[0,.69444,.08528,0,.59111],715:[0,.69444,0,0,.59111],728:[0,.69444,.10333,0,.59111],729:[0,.69444,.12945,0,.35555],730:[0,.69444,0,0,.94888],732:[0,.69444,.11472,0,.59111],733:[0,.69444,.11472,0,.59111],915:[0,.68611,.12903,0,.69777],916:[0,.68611,0,0,.94444],920:[0,.68611,.09062,0,.88555],923:[0,.68611,0,0,.80666],926:[0,.68611,.15092,0,.76777],928:[0,.68611,.17208,0,.8961],931:[0,.68611,.11431,0,.82666],933:[0,.68611,.10778,0,.88555],934:[0,.68611,.05632,0,.82666],936:[0,.68611,.10778,0,.88555],937:[0,.68611,.0992,0,.82666],8211:[0,.44444,.09811,0,.59111],8212:[0,.44444,.09811,0,1.18221],8216:[0,.69444,.12945,0,.35555],8217:[0,.69444,.12945,0,.35555],8220:[0,.69444,.16772,0,.62055],8221:[0,.69444,.07939,0,.62055]},"Main-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.12417,0,.30667],34:[0,.69444,.06961,0,.51444],35:[.19444,.69444,.06616,0,.81777],37:[.05556,.75,.13639,0,.81777],38:[0,.69444,.09694,0,.76666],39:[0,.69444,.12417,0,.30667],40:[.25,.75,.16194,0,.40889],41:[.25,.75,.03694,0,.40889],42:[0,.75,.14917,0,.51111],43:[.05667,.56167,.03694,0,.76666],44:[.19444,.10556,0,0,.30667],45:[0,.43056,.02826,0,.35778],46:[0,.10556,0,0,.30667],47:[.25,.75,.16194,0,.51111],48:[0,.64444,.13556,0,.51111],49:[0,.64444,.13556,0,.51111],50:[0,.64444,.13556,0,.51111],51:[0,.64444,.13556,0,.51111],52:[.19444,.64444,.13556,0,.51111],53:[0,.64444,.13556,0,.51111],54:[0,.64444,.13556,0,.51111],55:[.19444,.64444,.13556,0,.51111],56:[0,.64444,.13556,0,.51111],57:[0,.64444,.13556,0,.51111],58:[0,.43056,.0582,0,.30667],59:[.19444,.43056,.0582,0,.30667],61:[-.13313,.36687,.06616,0,.76666],63:[0,.69444,.1225,0,.51111],64:[0,.69444,.09597,0,.76666],65:[0,.68333,0,0,.74333],66:[0,.68333,.10257,0,.70389],67:[0,.68333,.14528,0,.71555],68:[0,.68333,.09403,0,.755],69:[0,.68333,.12028,0,.67833],70:[0,.68333,.13305,0,.65277],71:[0,.68333,.08722,0,.77361],72:[0,.68333,.16389,0,.74333],73:[0,.68333,.15806,0,.38555],74:[0,.68333,.14028,0,.525],75:[0,.68333,.14528,0,.76888],76:[0,.68333,0,0,.62722],77:[0,.68333,.16389,0,.89666],78:[0,.68333,.16389,0,.74333],79:[0,.68333,.09403,0,.76666],80:[0,.68333,.10257,0,.67833],81:[.19444,.68333,.09403,0,.76666],82:[0,.68333,.03868,0,.72944],83:[0,.68333,.11972,0,.56222],84:[0,.68333,.13305,0,.71555],85:[0,.68333,.16389,0,.74333],86:[0,.68333,.18361,0,.74333],87:[0,.68333,.18361,0,.99888],88:[0,.68333,.15806,0,.74333],89:[0,.68333,.19383,0,.74333],90:[0,.68333,.14528,0,.61333],91:[.25,.75,.1875,0,.30667],93:[.25,.75,.10528,0,.30667],94:[0,.69444,.06646,0,.51111],95:[.31,.12056,.09208,0,.51111],97:[0,.43056,.07671,0,.51111],98:[0,.69444,.06312,0,.46],99:[0,.43056,.05653,0,.46],100:[0,.69444,.10333,0,.51111],101:[0,.43056,.07514,0,.46],102:[.19444,.69444,.21194,0,.30667],103:[.19444,.43056,.08847,0,.46],104:[0,.69444,.07671,0,.51111],105:[0,.65536,.1019,0,.30667],106:[.19444,.65536,.14467,0,.30667],107:[0,.69444,.10764,0,.46],108:[0,.69444,.10333,0,.25555],109:[0,.43056,.07671,0,.81777],110:[0,.43056,.07671,0,.56222],111:[0,.43056,.06312,0,.51111],112:[.19444,.43056,.06312,0,.51111],113:[.19444,.43056,.08847,0,.46],114:[0,.43056,.10764,0,.42166],115:[0,.43056,.08208,0,.40889],116:[0,.61508,.09486,0,.33222],117:[0,.43056,.07671,0,.53666],118:[0,.43056,.10764,0,.46],119:[0,.43056,.10764,0,.66444],120:[0,.43056,.12042,0,.46389],121:[.19444,.43056,.08847,0,.48555],122:[0,.43056,.12292,0,.40889],126:[.35,.31786,.11585,0,.51111],160:[0,0,0,0,.25],168:[0,.66786,.10474,0,.51111],176:[0,.69444,0,0,.83129],184:[.17014,0,0,0,.46],198:[0,.68333,.12028,0,.88277],216:[.04861,.73194,.09403,0,.76666],223:[.19444,.69444,.10514,0,.53666],230:[0,.43056,.07514,0,.71555],248:[.09722,.52778,.09194,0,.51111],338:[0,.68333,.12028,0,.98499],339:[0,.43056,.07514,0,.71555],710:[0,.69444,.06646,0,.51111],711:[0,.62847,.08295,0,.51111],713:[0,.56167,.10333,0,.51111],714:[0,.69444,.09694,0,.51111],715:[0,.69444,0,0,.51111],728:[0,.69444,.10806,0,.51111],729:[0,.66786,.11752,0,.30667],730:[0,.69444,0,0,.83129],732:[0,.66786,.11585,0,.51111],733:[0,.69444,.1225,0,.51111],915:[0,.68333,.13305,0,.62722],916:[0,.68333,0,0,.81777],920:[0,.68333,.09403,0,.76666],923:[0,.68333,0,0,.69222],926:[0,.68333,.15294,0,.66444],928:[0,.68333,.16389,0,.74333],931:[0,.68333,.12028,0,.71555],933:[0,.68333,.11111,0,.76666],934:[0,.68333,.05986,0,.71555],936:[0,.68333,.11111,0,.76666],937:[0,.68333,.10257,0,.71555],8211:[0,.43056,.09208,0,.51111],8212:[0,.43056,.09208,0,1.02222],8216:[0,.69444,.12417,0,.30667],8217:[0,.69444,.12417,0,.30667],8220:[0,.69444,.1685,0,.51444],8221:[0,.69444,.06961,0,.51444],8463:[0,.68889,0,0,.54028]},"Main-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.27778],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.77778],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.19444,.10556,0,0,.27778],45:[0,.43056,0,0,.33333],46:[0,.10556,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.64444,0,0,.5],49:[0,.64444,0,0,.5],50:[0,.64444,0,0,.5],51:[0,.64444,0,0,.5],52:[0,.64444,0,0,.5],53:[0,.64444,0,0,.5],54:[0,.64444,0,0,.5],55:[0,.64444,0,0,.5],56:[0,.64444,0,0,.5],57:[0,.64444,0,0,.5],58:[0,.43056,0,0,.27778],59:[.19444,.43056,0,0,.27778],60:[.0391,.5391,0,0,.77778],61:[-.13313,.36687,0,0,.77778],62:[.0391,.5391,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.77778],65:[0,.68333,0,0,.75],66:[0,.68333,0,0,.70834],67:[0,.68333,0,0,.72222],68:[0,.68333,0,0,.76389],69:[0,.68333,0,0,.68056],70:[0,.68333,0,0,.65278],71:[0,.68333,0,0,.78472],72:[0,.68333,0,0,.75],73:[0,.68333,0,0,.36111],74:[0,.68333,0,0,.51389],75:[0,.68333,0,0,.77778],76:[0,.68333,0,0,.625],77:[0,.68333,0,0,.91667],78:[0,.68333,0,0,.75],79:[0,.68333,0,0,.77778],80:[0,.68333,0,0,.68056],81:[.19444,.68333,0,0,.77778],82:[0,.68333,0,0,.73611],83:[0,.68333,0,0,.55556],84:[0,.68333,0,0,.72222],85:[0,.68333,0,0,.75],86:[0,.68333,.01389,0,.75],87:[0,.68333,.01389,0,1.02778],88:[0,.68333,0,0,.75],89:[0,.68333,.025,0,.75],90:[0,.68333,0,0,.61111],91:[.25,.75,0,0,.27778],92:[.25,.75,0,0,.5],93:[.25,.75,0,0,.27778],94:[0,.69444,0,0,.5],95:[.31,.12056,.02778,0,.5],97:[0,.43056,0,0,.5],98:[0,.69444,0,0,.55556],99:[0,.43056,0,0,.44445],100:[0,.69444,0,0,.55556],101:[0,.43056,0,0,.44445],102:[0,.69444,.07778,0,.30556],103:[.19444,.43056,.01389,0,.5],104:[0,.69444,0,0,.55556],105:[0,.66786,0,0,.27778],106:[.19444,.66786,0,0,.30556],107:[0,.69444,0,0,.52778],108:[0,.69444,0,0,.27778],109:[0,.43056,0,0,.83334],110:[0,.43056,0,0,.55556],111:[0,.43056,0,0,.5],112:[.19444,.43056,0,0,.55556],113:[.19444,.43056,0,0,.52778],114:[0,.43056,0,0,.39167],115:[0,.43056,0,0,.39445],116:[0,.61508,0,0,.38889],117:[0,.43056,0,0,.55556],118:[0,.43056,.01389,0,.52778],119:[0,.43056,.01389,0,.72222],120:[0,.43056,0,0,.52778],121:[.19444,.43056,.01389,0,.52778],122:[0,.43056,0,0,.44445],123:[.25,.75,0,0,.5],124:[.25,.75,0,0,.27778],125:[.25,.75,0,0,.5],126:[.35,.31786,0,0,.5],160:[0,0,0,0,.25],163:[0,.69444,0,0,.76909],167:[.19444,.69444,0,0,.44445],168:[0,.66786,0,0,.5],172:[0,.43056,0,0,.66667],176:[0,.69444,0,0,.75],177:[.08333,.58333,0,0,.77778],182:[.19444,.69444,0,0,.61111],184:[.17014,0,0,0,.44445],198:[0,.68333,0,0,.90278],215:[.08333,.58333,0,0,.77778],216:[.04861,.73194,0,0,.77778],223:[0,.69444,0,0,.5],230:[0,.43056,0,0,.72222],247:[.08333,.58333,0,0,.77778],248:[.09722,.52778,0,0,.5],305:[0,.43056,0,0,.27778],338:[0,.68333,0,0,1.01389],339:[0,.43056,0,0,.77778],567:[.19444,.43056,0,0,.30556],710:[0,.69444,0,0,.5],711:[0,.62847,0,0,.5],713:[0,.56778,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.66786,0,0,.27778],730:[0,.69444,0,0,.75],732:[0,.66786,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.68333,0,0,.625],916:[0,.68333,0,0,.83334],920:[0,.68333,0,0,.77778],923:[0,.68333,0,0,.69445],926:[0,.68333,0,0,.66667],928:[0,.68333,0,0,.75],931:[0,.68333,0,0,.72222],933:[0,.68333,0,0,.77778],934:[0,.68333,0,0,.72222],936:[0,.68333,0,0,.77778],937:[0,.68333,0,0,.72222],8211:[0,.43056,.02778,0,.5],8212:[0,.43056,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5],8224:[.19444,.69444,0,0,.44445],8225:[.19444,.69444,0,0,.44445],8230:[0,.123,0,0,1.172],8242:[0,.55556,0,0,.275],8407:[0,.71444,.15382,0,.5],8463:[0,.68889,0,0,.54028],8465:[0,.69444,0,0,.72222],8467:[0,.69444,0,.11111,.41667],8472:[.19444,.43056,0,.11111,.63646],8476:[0,.69444,0,0,.72222],8501:[0,.69444,0,0,.61111],8592:[-.13313,.36687,0,0,1],8593:[.19444,.69444,0,0,.5],8594:[-.13313,.36687,0,0,1],8595:[.19444,.69444,0,0,.5],8596:[-.13313,.36687,0,0,1],8597:[.25,.75,0,0,.5],8598:[.19444,.69444,0,0,1],8599:[.19444,.69444,0,0,1],8600:[.19444,.69444,0,0,1],8601:[.19444,.69444,0,0,1],8614:[.011,.511,0,0,1],8617:[.011,.511,0,0,1.126],8618:[.011,.511,0,0,1.126],8636:[-.13313,.36687,0,0,1],8637:[-.13313,.36687,0,0,1],8640:[-.13313,.36687,0,0,1],8641:[-.13313,.36687,0,0,1],8652:[.011,.671,0,0,1],8656:[-.13313,.36687,0,0,1],8657:[.19444,.69444,0,0,.61111],8658:[-.13313,.36687,0,0,1],8659:[.19444,.69444,0,0,.61111],8660:[-.13313,.36687,0,0,1],8661:[.25,.75,0,0,.61111],8704:[0,.69444,0,0,.55556],8706:[0,.69444,.05556,.08334,.5309],8707:[0,.69444,0,0,.55556],8709:[.05556,.75,0,0,.5],8711:[0,.68333,0,0,.83334],8712:[.0391,.5391,0,0,.66667],8715:[.0391,.5391,0,0,.66667],8722:[.08333,.58333,0,0,.77778],8723:[.08333,.58333,0,0,.77778],8725:[.25,.75,0,0,.5],8726:[.25,.75,0,0,.5],8727:[-.03472,.46528,0,0,.5],8728:[-.05555,.44445,0,0,.5],8729:[-.05555,.44445,0,0,.5],8730:[.2,.8,0,0,.83334],8733:[0,.43056,0,0,.77778],8734:[0,.43056,0,0,1],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.27778],8741:[.25,.75,0,0,.5],8743:[0,.55556,0,0,.66667],8744:[0,.55556,0,0,.66667],8745:[0,.55556,0,0,.66667],8746:[0,.55556,0,0,.66667],8747:[.19444,.69444,.11111,0,.41667],8764:[-.13313,.36687,0,0,.77778],8768:[.19444,.69444,0,0,.27778],8771:[-.03625,.46375,0,0,.77778],8773:[-.022,.589,0,0,.778],8776:[-.01688,.48312,0,0,.77778],8781:[-.03625,.46375,0,0,.77778],8784:[-.133,.673,0,0,.778],8801:[-.03625,.46375,0,0,.77778],8804:[.13597,.63597,0,0,.77778],8805:[.13597,.63597,0,0,.77778],8810:[.0391,.5391,0,0,1],8811:[.0391,.5391,0,0,1],8826:[.0391,.5391,0,0,.77778],8827:[.0391,.5391,0,0,.77778],8834:[.0391,.5391,0,0,.77778],8835:[.0391,.5391,0,0,.77778],8838:[.13597,.63597,0,0,.77778],8839:[.13597,.63597,0,0,.77778],8846:[0,.55556,0,0,.66667],8849:[.13597,.63597,0,0,.77778],8850:[.13597,.63597,0,0,.77778],8851:[0,.55556,0,0,.66667],8852:[0,.55556,0,0,.66667],8853:[.08333,.58333,0,0,.77778],8854:[.08333,.58333,0,0,.77778],8855:[.08333,.58333,0,0,.77778],8856:[.08333,.58333,0,0,.77778],8857:[.08333,.58333,0,0,.77778],8866:[0,.69444,0,0,.61111],8867:[0,.69444,0,0,.61111],8868:[0,.69444,0,0,.77778],8869:[0,.69444,0,0,.77778],8872:[.249,.75,0,0,.867],8900:[-.05555,.44445,0,0,.5],8901:[-.05555,.44445,0,0,.27778],8902:[-.03472,.46528,0,0,.5],8904:[.005,.505,0,0,.9],8942:[.03,.903,0,0,.278],8943:[-.19,.313,0,0,1.172],8945:[-.1,.823,0,0,1.282],8968:[.25,.75,0,0,.44445],8969:[.25,.75,0,0,.44445],8970:[.25,.75,0,0,.44445],8971:[.25,.75,0,0,.44445],8994:[-.14236,.35764,0,0,1],8995:[-.14236,.35764,0,0,1],9136:[.244,.744,0,0,.412],9137:[.244,.745,0,0,.412],9651:[.19444,.69444,0,0,.88889],9657:[-.03472,.46528,0,0,.5],9661:[.19444,.69444,0,0,.88889],9667:[-.03472,.46528,0,0,.5],9711:[.19444,.69444,0,0,1],9824:[.12963,.69444,0,0,.77778],9825:[.12963,.69444,0,0,.77778],9826:[.12963,.69444,0,0,.77778],9827:[.12963,.69444,0,0,.77778],9837:[0,.75,0,0,.38889],9838:[.19444,.69444,0,0,.38889],9839:[.19444,.69444,0,0,.38889],10216:[.25,.75,0,0,.38889],10217:[.25,.75,0,0,.38889],10222:[.244,.744,0,0,.412],10223:[.244,.745,0,0,.412],10229:[.011,.511,0,0,1.609],10230:[.011,.511,0,0,1.638],10231:[.011,.511,0,0,1.859],10232:[.024,.525,0,0,1.609],10233:[.024,.525,0,0,1.638],10234:[.024,.525,0,0,1.858],10236:[.011,.511,0,0,1.638],10815:[0,.68333,0,0,.75],10927:[.13597,.63597,0,0,.77778],10928:[.13597,.63597,0,0,.77778],57376:[.19444,.69444,0,0,0]},"Math-BoldItalic":{32:[0,0,0,0,.25],48:[0,.44444,0,0,.575],49:[0,.44444,0,0,.575],50:[0,.44444,0,0,.575],51:[.19444,.44444,0,0,.575],52:[.19444,.44444,0,0,.575],53:[.19444,.44444,0,0,.575],54:[0,.64444,0,0,.575],55:[.19444,.44444,0,0,.575],56:[0,.64444,0,0,.575],57:[.19444,.44444,0,0,.575],65:[0,.68611,0,0,.86944],66:[0,.68611,.04835,0,.8664],67:[0,.68611,.06979,0,.81694],68:[0,.68611,.03194,0,.93812],69:[0,.68611,.05451,0,.81007],70:[0,.68611,.15972,0,.68889],71:[0,.68611,0,0,.88673],72:[0,.68611,.08229,0,.98229],73:[0,.68611,.07778,0,.51111],74:[0,.68611,.10069,0,.63125],75:[0,.68611,.06979,0,.97118],76:[0,.68611,0,0,.75555],77:[0,.68611,.11424,0,1.14201],78:[0,.68611,.11424,0,.95034],79:[0,.68611,.03194,0,.83666],80:[0,.68611,.15972,0,.72309],81:[.19444,.68611,0,0,.86861],82:[0,.68611,.00421,0,.87235],83:[0,.68611,.05382,0,.69271],84:[0,.68611,.15972,0,.63663],85:[0,.68611,.11424,0,.80027],86:[0,.68611,.25555,0,.67778],87:[0,.68611,.15972,0,1.09305],88:[0,.68611,.07778,0,.94722],89:[0,.68611,.25555,0,.67458],90:[0,.68611,.06979,0,.77257],97:[0,.44444,0,0,.63287],98:[0,.69444,0,0,.52083],99:[0,.44444,0,0,.51342],100:[0,.69444,0,0,.60972],101:[0,.44444,0,0,.55361],102:[.19444,.69444,.11042,0,.56806],103:[.19444,.44444,.03704,0,.5449],104:[0,.69444,0,0,.66759],105:[0,.69326,0,0,.4048],106:[.19444,.69326,.0622,0,.47083],107:[0,.69444,.01852,0,.6037],108:[0,.69444,.0088,0,.34815],109:[0,.44444,0,0,1.0324],110:[0,.44444,0,0,.71296],111:[0,.44444,0,0,.58472],112:[.19444,.44444,0,0,.60092],113:[.19444,.44444,.03704,0,.54213],114:[0,.44444,.03194,0,.5287],115:[0,.44444,0,0,.53125],116:[0,.63492,0,0,.41528],117:[0,.44444,0,0,.68102],118:[0,.44444,.03704,0,.56666],119:[0,.44444,.02778,0,.83148],120:[0,.44444,0,0,.65903],121:[.19444,.44444,.03704,0,.59028],122:[0,.44444,.04213,0,.55509],160:[0,0,0,0,.25],915:[0,.68611,.15972,0,.65694],916:[0,.68611,0,0,.95833],920:[0,.68611,.03194,0,.86722],923:[0,.68611,0,0,.80555],926:[0,.68611,.07458,0,.84125],928:[0,.68611,.08229,0,.98229],931:[0,.68611,.05451,0,.88507],933:[0,.68611,.15972,0,.67083],934:[0,.68611,0,0,.76666],936:[0,.68611,.11653,0,.71402],937:[0,.68611,.04835,0,.8789],945:[0,.44444,0,0,.76064],946:[.19444,.69444,.03403,0,.65972],947:[.19444,.44444,.06389,0,.59003],948:[0,.69444,.03819,0,.52222],949:[0,.44444,0,0,.52882],950:[.19444,.69444,.06215,0,.50833],951:[.19444,.44444,.03704,0,.6],952:[0,.69444,.03194,0,.5618],953:[0,.44444,0,0,.41204],954:[0,.44444,0,0,.66759],955:[0,.69444,0,0,.67083],956:[.19444,.44444,0,0,.70787],957:[0,.44444,.06898,0,.57685],958:[.19444,.69444,.03021,0,.50833],959:[0,.44444,0,0,.58472],960:[0,.44444,.03704,0,.68241],961:[.19444,.44444,0,0,.6118],962:[.09722,.44444,.07917,0,.42361],963:[0,.44444,.03704,0,.68588],964:[0,.44444,.13472,0,.52083],965:[0,.44444,.03704,0,.63055],966:[.19444,.44444,0,0,.74722],967:[.19444,.44444,0,0,.71805],968:[.19444,.69444,.03704,0,.75833],969:[0,.44444,.03704,0,.71782],977:[0,.69444,0,0,.69155],981:[.19444,.69444,0,0,.7125],982:[0,.44444,.03194,0,.975],1009:[.19444,.44444,0,0,.6118],1013:[0,.44444,0,0,.48333],57649:[0,.44444,0,0,.39352],57911:[.19444,.44444,0,0,.43889]},"Math-Italic":{32:[0,0,0,0,.25],48:[0,.43056,0,0,.5],49:[0,.43056,0,0,.5],50:[0,.43056,0,0,.5],51:[.19444,.43056,0,0,.5],52:[.19444,.43056,0,0,.5],53:[.19444,.43056,0,0,.5],54:[0,.64444,0,0,.5],55:[.19444,.43056,0,0,.5],56:[0,.64444,0,0,.5],57:[.19444,.43056,0,0,.5],65:[0,.68333,0,.13889,.75],66:[0,.68333,.05017,.08334,.75851],67:[0,.68333,.07153,.08334,.71472],68:[0,.68333,.02778,.05556,.82792],69:[0,.68333,.05764,.08334,.7382],70:[0,.68333,.13889,.08334,.64306],71:[0,.68333,0,.08334,.78625],72:[0,.68333,.08125,.05556,.83125],73:[0,.68333,.07847,.11111,.43958],74:[0,.68333,.09618,.16667,.55451],75:[0,.68333,.07153,.05556,.84931],76:[0,.68333,0,.02778,.68056],77:[0,.68333,.10903,.08334,.97014],78:[0,.68333,.10903,.08334,.80347],79:[0,.68333,.02778,.08334,.76278],80:[0,.68333,.13889,.08334,.64201],81:[.19444,.68333,0,.08334,.79056],82:[0,.68333,.00773,.08334,.75929],83:[0,.68333,.05764,.08334,.6132],84:[0,.68333,.13889,.08334,.58438],85:[0,.68333,.10903,.02778,.68278],86:[0,.68333,.22222,0,.58333],87:[0,.68333,.13889,0,.94445],88:[0,.68333,.07847,.08334,.82847],89:[0,.68333,.22222,0,.58056],90:[0,.68333,.07153,.08334,.68264],97:[0,.43056,0,0,.52859],98:[0,.69444,0,0,.42917],99:[0,.43056,0,.05556,.43276],100:[0,.69444,0,.16667,.52049],101:[0,.43056,0,.05556,.46563],102:[.19444,.69444,.10764,.16667,.48959],103:[.19444,.43056,.03588,.02778,.47697],104:[0,.69444,0,0,.57616],105:[0,.65952,0,0,.34451],106:[.19444,.65952,.05724,0,.41181],107:[0,.69444,.03148,0,.5206],108:[0,.69444,.01968,.08334,.29838],109:[0,.43056,0,0,.87801],110:[0,.43056,0,0,.60023],111:[0,.43056,0,.05556,.48472],112:[.19444,.43056,0,.08334,.50313],113:[.19444,.43056,.03588,.08334,.44641],114:[0,.43056,.02778,.05556,.45116],115:[0,.43056,0,.05556,.46875],116:[0,.61508,0,.08334,.36111],117:[0,.43056,0,.02778,.57246],118:[0,.43056,.03588,.02778,.48472],119:[0,.43056,.02691,.08334,.71592],120:[0,.43056,0,.02778,.57153],121:[.19444,.43056,.03588,.05556,.49028],122:[0,.43056,.04398,.05556,.46505],160:[0,0,0,0,.25],915:[0,.68333,.13889,.08334,.61528],916:[0,.68333,0,.16667,.83334],920:[0,.68333,.02778,.08334,.76278],923:[0,.68333,0,.16667,.69445],926:[0,.68333,.07569,.08334,.74236],928:[0,.68333,.08125,.05556,.83125],931:[0,.68333,.05764,.08334,.77986],933:[0,.68333,.13889,.05556,.58333],934:[0,.68333,0,.08334,.66667],936:[0,.68333,.11,.05556,.61222],937:[0,.68333,.05017,.08334,.7724],945:[0,.43056,.0037,.02778,.6397],946:[.19444,.69444,.05278,.08334,.56563],947:[.19444,.43056,.05556,0,.51773],948:[0,.69444,.03785,.05556,.44444],949:[0,.43056,0,.08334,.46632],950:[.19444,.69444,.07378,.08334,.4375],951:[.19444,.43056,.03588,.05556,.49653],952:[0,.69444,.02778,.08334,.46944],953:[0,.43056,0,.05556,.35394],954:[0,.43056,0,0,.57616],955:[0,.69444,0,0,.58334],956:[.19444,.43056,0,.02778,.60255],957:[0,.43056,.06366,.02778,.49398],958:[.19444,.69444,.04601,.11111,.4375],959:[0,.43056,0,.05556,.48472],960:[0,.43056,.03588,0,.57003],961:[.19444,.43056,0,.08334,.51702],962:[.09722,.43056,.07986,.08334,.36285],963:[0,.43056,.03588,0,.57141],964:[0,.43056,.1132,.02778,.43715],965:[0,.43056,.03588,.02778,.54028],966:[.19444,.43056,0,.08334,.65417],967:[.19444,.43056,0,.05556,.62569],968:[.19444,.69444,.03588,.11111,.65139],969:[0,.43056,.03588,0,.62245],977:[0,.69444,0,.08334,.59144],981:[.19444,.69444,0,.08334,.59583],982:[0,.43056,.02778,0,.82813],1009:[.19444,.43056,0,.08334,.51702],1013:[0,.43056,0,.05556,.4059],57649:[0,.43056,0,.02778,.32246],57911:[.19444,.43056,0,.08334,.38403]},"SansSerif-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.36667],34:[0,.69444,0,0,.55834],35:[.19444,.69444,0,0,.91667],36:[.05556,.75,0,0,.55],37:[.05556,.75,0,0,1.02912],38:[0,.69444,0,0,.83056],39:[0,.69444,0,0,.30556],40:[.25,.75,0,0,.42778],41:[.25,.75,0,0,.42778],42:[0,.75,0,0,.55],43:[.11667,.61667,0,0,.85556],44:[.10556,.13056,0,0,.30556],45:[0,.45833,0,0,.36667],46:[0,.13056,0,0,.30556],47:[.25,.75,0,0,.55],48:[0,.69444,0,0,.55],49:[0,.69444,0,0,.55],50:[0,.69444,0,0,.55],51:[0,.69444,0,0,.55],52:[0,.69444,0,0,.55],53:[0,.69444,0,0,.55],54:[0,.69444,0,0,.55],55:[0,.69444,0,0,.55],56:[0,.69444,0,0,.55],57:[0,.69444,0,0,.55],58:[0,.45833,0,0,.30556],59:[.10556,.45833,0,0,.30556],61:[-.09375,.40625,0,0,.85556],63:[0,.69444,0,0,.51945],64:[0,.69444,0,0,.73334],65:[0,.69444,0,0,.73334],66:[0,.69444,0,0,.73334],67:[0,.69444,0,0,.70278],68:[0,.69444,0,0,.79445],69:[0,.69444,0,0,.64167],70:[0,.69444,0,0,.61111],71:[0,.69444,0,0,.73334],72:[0,.69444,0,0,.79445],73:[0,.69444,0,0,.33056],74:[0,.69444,0,0,.51945],75:[0,.69444,0,0,.76389],76:[0,.69444,0,0,.58056],77:[0,.69444,0,0,.97778],78:[0,.69444,0,0,.79445],79:[0,.69444,0,0,.79445],80:[0,.69444,0,0,.70278],81:[.10556,.69444,0,0,.79445],82:[0,.69444,0,0,.70278],83:[0,.69444,0,0,.61111],84:[0,.69444,0,0,.73334],85:[0,.69444,0,0,.76389],86:[0,.69444,.01528,0,.73334],87:[0,.69444,.01528,0,1.03889],88:[0,.69444,0,0,.73334],89:[0,.69444,.0275,0,.73334],90:[0,.69444,0,0,.67223],91:[.25,.75,0,0,.34306],93:[.25,.75,0,0,.34306],94:[0,.69444,0,0,.55],95:[.35,.10833,.03056,0,.55],97:[0,.45833,0,0,.525],98:[0,.69444,0,0,.56111],99:[0,.45833,0,0,.48889],100:[0,.69444,0,0,.56111],101:[0,.45833,0,0,.51111],102:[0,.69444,.07639,0,.33611],103:[.19444,.45833,.01528,0,.55],104:[0,.69444,0,0,.56111],105:[0,.69444,0,0,.25556],106:[.19444,.69444,0,0,.28611],107:[0,.69444,0,0,.53056],108:[0,.69444,0,0,.25556],109:[0,.45833,0,0,.86667],110:[0,.45833,0,0,.56111],111:[0,.45833,0,0,.55],112:[.19444,.45833,0,0,.56111],113:[.19444,.45833,0,0,.56111],114:[0,.45833,.01528,0,.37222],115:[0,.45833,0,0,.42167],116:[0,.58929,0,0,.40417],117:[0,.45833,0,0,.56111],118:[0,.45833,.01528,0,.5],119:[0,.45833,.01528,0,.74445],120:[0,.45833,0,0,.5],121:[.19444,.45833,.01528,0,.5],122:[0,.45833,0,0,.47639],126:[.35,.34444,0,0,.55],160:[0,0,0,0,.25],168:[0,.69444,0,0,.55],176:[0,.69444,0,0,.73334],180:[0,.69444,0,0,.55],184:[.17014,0,0,0,.48889],305:[0,.45833,0,0,.25556],567:[.19444,.45833,0,0,.28611],710:[0,.69444,0,0,.55],711:[0,.63542,0,0,.55],713:[0,.63778,0,0,.55],728:[0,.69444,0,0,.55],729:[0,.69444,0,0,.30556],730:[0,.69444,0,0,.73334],732:[0,.69444,0,0,.55],733:[0,.69444,0,0,.55],915:[0,.69444,0,0,.58056],916:[0,.69444,0,0,.91667],920:[0,.69444,0,0,.85556],923:[0,.69444,0,0,.67223],926:[0,.69444,0,0,.73334],928:[0,.69444,0,0,.79445],931:[0,.69444,0,0,.79445],933:[0,.69444,0,0,.85556],934:[0,.69444,0,0,.79445],936:[0,.69444,0,0,.85556],937:[0,.69444,0,0,.79445],8211:[0,.45833,.03056,0,.55],8212:[0,.45833,.03056,0,1.10001],8216:[0,.69444,0,0,.30556],8217:[0,.69444,0,0,.30556],8220:[0,.69444,0,0,.55834],8221:[0,.69444,0,0,.55834]},"SansSerif-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.05733,0,.31945],34:[0,.69444,.00316,0,.5],35:[.19444,.69444,.05087,0,.83334],36:[.05556,.75,.11156,0,.5],37:[.05556,.75,.03126,0,.83334],38:[0,.69444,.03058,0,.75834],39:[0,.69444,.07816,0,.27778],40:[.25,.75,.13164,0,.38889],41:[.25,.75,.02536,0,.38889],42:[0,.75,.11775,0,.5],43:[.08333,.58333,.02536,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,.01946,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,.13164,0,.5],48:[0,.65556,.11156,0,.5],49:[0,.65556,.11156,0,.5],50:[0,.65556,.11156,0,.5],51:[0,.65556,.11156,0,.5],52:[0,.65556,.11156,0,.5],53:[0,.65556,.11156,0,.5],54:[0,.65556,.11156,0,.5],55:[0,.65556,.11156,0,.5],56:[0,.65556,.11156,0,.5],57:[0,.65556,.11156,0,.5],58:[0,.44444,.02502,0,.27778],59:[.125,.44444,.02502,0,.27778],61:[-.13,.37,.05087,0,.77778],63:[0,.69444,.11809,0,.47222],64:[0,.69444,.07555,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,.08293,0,.66667],67:[0,.69444,.11983,0,.63889],68:[0,.69444,.07555,0,.72223],69:[0,.69444,.11983,0,.59722],70:[0,.69444,.13372,0,.56945],71:[0,.69444,.11983,0,.66667],72:[0,.69444,.08094,0,.70834],73:[0,.69444,.13372,0,.27778],74:[0,.69444,.08094,0,.47222],75:[0,.69444,.11983,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,.08094,0,.875],78:[0,.69444,.08094,0,.70834],79:[0,.69444,.07555,0,.73611],80:[0,.69444,.08293,0,.63889],81:[.125,.69444,.07555,0,.73611],82:[0,.69444,.08293,0,.64584],83:[0,.69444,.09205,0,.55556],84:[0,.69444,.13372,0,.68056],85:[0,.69444,.08094,0,.6875],86:[0,.69444,.1615,0,.66667],87:[0,.69444,.1615,0,.94445],88:[0,.69444,.13372,0,.66667],89:[0,.69444,.17261,0,.66667],90:[0,.69444,.11983,0,.61111],91:[.25,.75,.15942,0,.28889],93:[.25,.75,.08719,0,.28889],94:[0,.69444,.0799,0,.5],95:[.35,.09444,.08616,0,.5],97:[0,.44444,.00981,0,.48056],98:[0,.69444,.03057,0,.51667],99:[0,.44444,.08336,0,.44445],100:[0,.69444,.09483,0,.51667],101:[0,.44444,.06778,0,.44445],102:[0,.69444,.21705,0,.30556],103:[.19444,.44444,.10836,0,.5],104:[0,.69444,.01778,0,.51667],105:[0,.67937,.09718,0,.23889],106:[.19444,.67937,.09162,0,.26667],107:[0,.69444,.08336,0,.48889],108:[0,.69444,.09483,0,.23889],109:[0,.44444,.01778,0,.79445],110:[0,.44444,.01778,0,.51667],111:[0,.44444,.06613,0,.5],112:[.19444,.44444,.0389,0,.51667],113:[.19444,.44444,.04169,0,.51667],114:[0,.44444,.10836,0,.34167],115:[0,.44444,.0778,0,.38333],116:[0,.57143,.07225,0,.36111],117:[0,.44444,.04169,0,.51667],118:[0,.44444,.10836,0,.46111],119:[0,.44444,.10836,0,.68334],120:[0,.44444,.09169,0,.46111],121:[.19444,.44444,.10836,0,.46111],122:[0,.44444,.08752,0,.43472],126:[.35,.32659,.08826,0,.5],160:[0,0,0,0,.25],168:[0,.67937,.06385,0,.5],176:[0,.69444,0,0,.73752],184:[.17014,0,0,0,.44445],305:[0,.44444,.04169,0,.23889],567:[.19444,.44444,.04169,0,.26667],710:[0,.69444,.0799,0,.5],711:[0,.63194,.08432,0,.5],713:[0,.60889,.08776,0,.5],714:[0,.69444,.09205,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,.09483,0,.5],729:[0,.67937,.07774,0,.27778],730:[0,.69444,0,0,.73752],732:[0,.67659,.08826,0,.5],733:[0,.69444,.09205,0,.5],915:[0,.69444,.13372,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,.07555,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,.12816,0,.66667],928:[0,.69444,.08094,0,.70834],931:[0,.69444,.11983,0,.72222],933:[0,.69444,.09031,0,.77778],934:[0,.69444,.04603,0,.72222],936:[0,.69444,.09031,0,.77778],937:[0,.69444,.08293,0,.72222],8211:[0,.44444,.08616,0,.5],8212:[0,.44444,.08616,0,1],8216:[0,.69444,.07816,0,.27778],8217:[0,.69444,.07816,0,.27778],8220:[0,.69444,.14205,0,.5],8221:[0,.69444,.00316,0,.5]},"SansSerif-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.31945],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.75834],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,0,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.65556,0,0,.5],49:[0,.65556,0,0,.5],50:[0,.65556,0,0,.5],51:[0,.65556,0,0,.5],52:[0,.65556,0,0,.5],53:[0,.65556,0,0,.5],54:[0,.65556,0,0,.5],55:[0,.65556,0,0,.5],56:[0,.65556,0,0,.5],57:[0,.65556,0,0,.5],58:[0,.44444,0,0,.27778],59:[.125,.44444,0,0,.27778],61:[-.13,.37,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,0,0,.66667],67:[0,.69444,0,0,.63889],68:[0,.69444,0,0,.72223],69:[0,.69444,0,0,.59722],70:[0,.69444,0,0,.56945],71:[0,.69444,0,0,.66667],72:[0,.69444,0,0,.70834],73:[0,.69444,0,0,.27778],74:[0,.69444,0,0,.47222],75:[0,.69444,0,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,0,0,.875],78:[0,.69444,0,0,.70834],79:[0,.69444,0,0,.73611],80:[0,.69444,0,0,.63889],81:[.125,.69444,0,0,.73611],82:[0,.69444,0,0,.64584],83:[0,.69444,0,0,.55556],84:[0,.69444,0,0,.68056],85:[0,.69444,0,0,.6875],86:[0,.69444,.01389,0,.66667],87:[0,.69444,.01389,0,.94445],88:[0,.69444,0,0,.66667],89:[0,.69444,.025,0,.66667],90:[0,.69444,0,0,.61111],91:[.25,.75,0,0,.28889],93:[.25,.75,0,0,.28889],94:[0,.69444,0,0,.5],95:[.35,.09444,.02778,0,.5],97:[0,.44444,0,0,.48056],98:[0,.69444,0,0,.51667],99:[0,.44444,0,0,.44445],100:[0,.69444,0,0,.51667],101:[0,.44444,0,0,.44445],102:[0,.69444,.06944,0,.30556],103:[.19444,.44444,.01389,0,.5],104:[0,.69444,0,0,.51667],105:[0,.67937,0,0,.23889],106:[.19444,.67937,0,0,.26667],107:[0,.69444,0,0,.48889],108:[0,.69444,0,0,.23889],109:[0,.44444,0,0,.79445],110:[0,.44444,0,0,.51667],111:[0,.44444,0,0,.5],112:[.19444,.44444,0,0,.51667],113:[.19444,.44444,0,0,.51667],114:[0,.44444,.01389,0,.34167],115:[0,.44444,0,0,.38333],116:[0,.57143,0,0,.36111],117:[0,.44444,0,0,.51667],118:[0,.44444,.01389,0,.46111],119:[0,.44444,.01389,0,.68334],120:[0,.44444,0,0,.46111],121:[.19444,.44444,.01389,0,.46111],122:[0,.44444,0,0,.43472],126:[.35,.32659,0,0,.5],160:[0,0,0,0,.25],168:[0,.67937,0,0,.5],176:[0,.69444,0,0,.66667],184:[.17014,0,0,0,.44445],305:[0,.44444,0,0,.23889],567:[.19444,.44444,0,0,.26667],710:[0,.69444,0,0,.5],711:[0,.63194,0,0,.5],713:[0,.60889,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.67937,0,0,.27778],730:[0,.69444,0,0,.66667],732:[0,.67659,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.69444,0,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,0,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,0,0,.66667],928:[0,.69444,0,0,.70834],931:[0,.69444,0,0,.72222],933:[0,.69444,0,0,.77778],934:[0,.69444,0,0,.72222],936:[0,.69444,0,0,.77778],937:[0,.69444,0,0,.72222],8211:[0,.44444,.02778,0,.5],8212:[0,.44444,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5]},"Script-Regular":{32:[0,0,0,0,.25],65:[0,.7,.22925,0,.80253],66:[0,.7,.04087,0,.90757],67:[0,.7,.1689,0,.66619],68:[0,.7,.09371,0,.77443],69:[0,.7,.18583,0,.56162],70:[0,.7,.13634,0,.89544],71:[0,.7,.17322,0,.60961],72:[0,.7,.29694,0,.96919],73:[0,.7,.19189,0,.80907],74:[.27778,.7,.19189,0,1.05159],75:[0,.7,.31259,0,.91364],76:[0,.7,.19189,0,.87373],77:[0,.7,.15981,0,1.08031],78:[0,.7,.3525,0,.9015],79:[0,.7,.08078,0,.73787],80:[0,.7,.08078,0,1.01262],81:[0,.7,.03305,0,.88282],82:[0,.7,.06259,0,.85],83:[0,.7,.19189,0,.86767],84:[0,.7,.29087,0,.74697],85:[0,.7,.25815,0,.79996],86:[0,.7,.27523,0,.62204],87:[0,.7,.27523,0,.80532],88:[0,.7,.26006,0,.94445],89:[0,.7,.2939,0,.70961],90:[0,.7,.24037,0,.8212],160:[0,0,0,0,.25]},"Size1-Regular":{32:[0,0,0,0,.25],40:[.35001,.85,0,0,.45834],41:[.35001,.85,0,0,.45834],47:[.35001,.85,0,0,.57778],91:[.35001,.85,0,0,.41667],92:[.35001,.85,0,0,.57778],93:[.35001,.85,0,0,.41667],123:[.35001,.85,0,0,.58334],125:[.35001,.85,0,0,.58334],160:[0,0,0,0,.25],710:[0,.72222,0,0,.55556],732:[0,.72222,0,0,.55556],770:[0,.72222,0,0,.55556],771:[0,.72222,0,0,.55556],8214:[-99e-5,.601,0,0,.77778],8593:[1e-5,.6,0,0,.66667],8595:[1e-5,.6,0,0,.66667],8657:[1e-5,.6,0,0,.77778],8659:[1e-5,.6,0,0,.77778],8719:[.25001,.75,0,0,.94445],8720:[.25001,.75,0,0,.94445],8721:[.25001,.75,0,0,1.05556],8730:[.35001,.85,0,0,1],8739:[-.00599,.606,0,0,.33333],8741:[-.00599,.606,0,0,.55556],8747:[.30612,.805,.19445,0,.47222],8748:[.306,.805,.19445,0,.47222],8749:[.306,.805,.19445,0,.47222],8750:[.30612,.805,.19445,0,.47222],8896:[.25001,.75,0,0,.83334],8897:[.25001,.75,0,0,.83334],8898:[.25001,.75,0,0,.83334],8899:[.25001,.75,0,0,.83334],8968:[.35001,.85,0,0,.47222],8969:[.35001,.85,0,0,.47222],8970:[.35001,.85,0,0,.47222],8971:[.35001,.85,0,0,.47222],9168:[-99e-5,.601,0,0,.66667],10216:[.35001,.85,0,0,.47222],10217:[.35001,.85,0,0,.47222],10752:[.25001,.75,0,0,1.11111],10753:[.25001,.75,0,0,1.11111],10754:[.25001,.75,0,0,1.11111],10756:[.25001,.75,0,0,.83334],10758:[.25001,.75,0,0,.83334]},"Size2-Regular":{32:[0,0,0,0,.25],40:[.65002,1.15,0,0,.59722],41:[.65002,1.15,0,0,.59722],47:[.65002,1.15,0,0,.81111],91:[.65002,1.15,0,0,.47222],92:[.65002,1.15,0,0,.81111],93:[.65002,1.15,0,0,.47222],123:[.65002,1.15,0,0,.66667],125:[.65002,1.15,0,0,.66667],160:[0,0,0,0,.25],710:[0,.75,0,0,1],732:[0,.75,0,0,1],770:[0,.75,0,0,1],771:[0,.75,0,0,1],8719:[.55001,1.05,0,0,1.27778],8720:[.55001,1.05,0,0,1.27778],8721:[.55001,1.05,0,0,1.44445],8730:[.65002,1.15,0,0,1],8747:[.86225,1.36,.44445,0,.55556],8748:[.862,1.36,.44445,0,.55556],8749:[.862,1.36,.44445,0,.55556],8750:[.86225,1.36,.44445,0,.55556],8896:[.55001,1.05,0,0,1.11111],8897:[.55001,1.05,0,0,1.11111],8898:[.55001,1.05,0,0,1.11111],8899:[.55001,1.05,0,0,1.11111],8968:[.65002,1.15,0,0,.52778],8969:[.65002,1.15,0,0,.52778],8970:[.65002,1.15,0,0,.52778],8971:[.65002,1.15,0,0,.52778],10216:[.65002,1.15,0,0,.61111],10217:[.65002,1.15,0,0,.61111],10752:[.55001,1.05,0,0,1.51112],10753:[.55001,1.05,0,0,1.51112],10754:[.55001,1.05,0,0,1.51112],10756:[.55001,1.05,0,0,1.11111],10758:[.55001,1.05,0,0,1.11111]},"Size3-Regular":{32:[0,0,0,0,.25],40:[.95003,1.45,0,0,.73611],41:[.95003,1.45,0,0,.73611],47:[.95003,1.45,0,0,1.04445],91:[.95003,1.45,0,0,.52778],92:[.95003,1.45,0,0,1.04445],93:[.95003,1.45,0,0,.52778],123:[.95003,1.45,0,0,.75],125:[.95003,1.45,0,0,.75],160:[0,0,0,0,.25],710:[0,.75,0,0,1.44445],732:[0,.75,0,0,1.44445],770:[0,.75,0,0,1.44445],771:[0,.75,0,0,1.44445],8730:[.95003,1.45,0,0,1],8968:[.95003,1.45,0,0,.58334],8969:[.95003,1.45,0,0,.58334],8970:[.95003,1.45,0,0,.58334],8971:[.95003,1.45,0,0,.58334],10216:[.95003,1.45,0,0,.75],10217:[.95003,1.45,0,0,.75]},"Size4-Regular":{32:[0,0,0,0,.25],40:[1.25003,1.75,0,0,.79167],41:[1.25003,1.75,0,0,.79167],47:[1.25003,1.75,0,0,1.27778],91:[1.25003,1.75,0,0,.58334],92:[1.25003,1.75,0,0,1.27778],93:[1.25003,1.75,0,0,.58334],123:[1.25003,1.75,0,0,.80556],125:[1.25003,1.75,0,0,.80556],160:[0,0,0,0,.25],710:[0,.825,0,0,1.8889],732:[0,.825,0,0,1.8889],770:[0,.825,0,0,1.8889],771:[0,.825,0,0,1.8889],8730:[1.25003,1.75,0,0,1],8968:[1.25003,1.75,0,0,.63889],8969:[1.25003,1.75,0,0,.63889],8970:[1.25003,1.75,0,0,.63889],8971:[1.25003,1.75,0,0,.63889],9115:[.64502,1.155,0,0,.875],9116:[1e-5,.6,0,0,.875],9117:[.64502,1.155,0,0,.875],9118:[.64502,1.155,0,0,.875],9119:[1e-5,.6,0,0,.875],9120:[.64502,1.155,0,0,.875],9121:[.64502,1.155,0,0,.66667],9122:[-99e-5,.601,0,0,.66667],9123:[.64502,1.155,0,0,.66667],9124:[.64502,1.155,0,0,.66667],9125:[-99e-5,.601,0,0,.66667],9126:[.64502,1.155,0,0,.66667],9127:[1e-5,.9,0,0,.88889],9128:[.65002,1.15,0,0,.88889],9129:[.90001,0,0,0,.88889],9130:[0,.3,0,0,.88889],9131:[1e-5,.9,0,0,.88889],9132:[.65002,1.15,0,0,.88889],9133:[.90001,0,0,0,.88889],9143:[.88502,.915,0,0,1.05556],10216:[1.25003,1.75,0,0,.80556],10217:[1.25003,1.75,0,0,.80556],57344:[-.00499,.605,0,0,1.05556],57345:[-.00499,.605,0,0,1.05556],57680:[0,.12,0,0,.45],57681:[0,.12,0,0,.45],57682:[0,.12,0,0,.45],57683:[0,.12,0,0,.45]},"Typewriter-Regular":{32:[0,0,0,0,.525],33:[0,.61111,0,0,.525],34:[0,.61111,0,0,.525],35:[0,.61111,0,0,.525],36:[.08333,.69444,0,0,.525],37:[.08333,.69444,0,0,.525],38:[0,.61111,0,0,.525],39:[0,.61111,0,0,.525],40:[.08333,.69444,0,0,.525],41:[.08333,.69444,0,0,.525],42:[0,.52083,0,0,.525],43:[-.08056,.53055,0,0,.525],44:[.13889,.125,0,0,.525],45:[-.08056,.53055,0,0,.525],46:[0,.125,0,0,.525],47:[.08333,.69444,0,0,.525],48:[0,.61111,0,0,.525],49:[0,.61111,0,0,.525],50:[0,.61111,0,0,.525],51:[0,.61111,0,0,.525],52:[0,.61111,0,0,.525],53:[0,.61111,0,0,.525],54:[0,.61111,0,0,.525],55:[0,.61111,0,0,.525],56:[0,.61111,0,0,.525],57:[0,.61111,0,0,.525],58:[0,.43056,0,0,.525],59:[.13889,.43056,0,0,.525],60:[-.05556,.55556,0,0,.525],61:[-.19549,.41562,0,0,.525],62:[-.05556,.55556,0,0,.525],63:[0,.61111,0,0,.525],64:[0,.61111,0,0,.525],65:[0,.61111,0,0,.525],66:[0,.61111,0,0,.525],67:[0,.61111,0,0,.525],68:[0,.61111,0,0,.525],69:[0,.61111,0,0,.525],70:[0,.61111,0,0,.525],71:[0,.61111,0,0,.525],72:[0,.61111,0,0,.525],73:[0,.61111,0,0,.525],74:[0,.61111,0,0,.525],75:[0,.61111,0,0,.525],76:[0,.61111,0,0,.525],77:[0,.61111,0,0,.525],78:[0,.61111,0,0,.525],79:[0,.61111,0,0,.525],80:[0,.61111,0,0,.525],81:[.13889,.61111,0,0,.525],82:[0,.61111,0,0,.525],83:[0,.61111,0,0,.525],84:[0,.61111,0,0,.525],85:[0,.61111,0,0,.525],86:[0,.61111,0,0,.525],87:[0,.61111,0,0,.525],88:[0,.61111,0,0,.525],89:[0,.61111,0,0,.525],90:[0,.61111,0,0,.525],91:[.08333,.69444,0,0,.525],92:[.08333,.69444,0,0,.525],93:[.08333,.69444,0,0,.525],94:[0,.61111,0,0,.525],95:[.09514,0,0,0,.525],96:[0,.61111,0,0,.525],97:[0,.43056,0,0,.525],98:[0,.61111,0,0,.525],99:[0,.43056,0,0,.525],100:[0,.61111,0,0,.525],101:[0,.43056,0,0,.525],102:[0,.61111,0,0,.525],103:[.22222,.43056,0,0,.525],104:[0,.61111,0,0,.525],105:[0,.61111,0,0,.525],106:[.22222,.61111,0,0,.525],107:[0,.61111,0,0,.525],108:[0,.61111,0,0,.525],109:[0,.43056,0,0,.525],110:[0,.43056,0,0,.525],111:[0,.43056,0,0,.525],112:[.22222,.43056,0,0,.525],113:[.22222,.43056,0,0,.525],114:[0,.43056,0,0,.525],115:[0,.43056,0,0,.525],116:[0,.55358,0,0,.525],117:[0,.43056,0,0,.525],118:[0,.43056,0,0,.525],119:[0,.43056,0,0,.525],120:[0,.43056,0,0,.525],121:[.22222,.43056,0,0,.525],122:[0,.43056,0,0,.525],123:[.08333,.69444,0,0,.525],124:[.08333,.69444,0,0,.525],125:[.08333,.69444,0,0,.525],126:[0,.61111,0,0,.525],127:[0,.61111,0,0,.525],160:[0,0,0,0,.525],176:[0,.61111,0,0,.525],184:[.19445,0,0,0,.525],305:[0,.43056,0,0,.525],567:[.22222,.43056,0,0,.525],711:[0,.56597,0,0,.525],713:[0,.56555,0,0,.525],714:[0,.61111,0,0,.525],715:[0,.61111,0,0,.525],728:[0,.61111,0,0,.525],730:[0,.61111,0,0,.525],770:[0,.61111,0,0,.525],771:[0,.61111,0,0,.525],776:[0,.61111,0,0,.525],915:[0,.61111,0,0,.525],916:[0,.61111,0,0,.525],920:[0,.61111,0,0,.525],923:[0,.61111,0,0,.525],926:[0,.61111,0,0,.525],928:[0,.61111,0,0,.525],931:[0,.61111,0,0,.525],933:[0,.61111,0,0,.525],934:[0,.61111,0,0,.525],936:[0,.61111,0,0,.525],937:[0,.61111,0,0,.525],8216:[0,.61111,0,0,.525],8217:[0,.61111,0,0,.525],8242:[0,.61111,0,0,.525],9251:[.11111,.21944,0,0,.525]}},Da={slant:[.25,.25,.25],space:[0,0,0],stretch:[0,0,0],shrink:[0,0,0],xHeight:[.431,.431,.431],quad:[1,1.171,1.472],extraSpace:[0,0,0],num1:[.677,.732,.925],num2:[.394,.384,.387],num3:[.444,.471,.504],denom1:[.686,.752,1.025],denom2:[.345,.344,.532],sup1:[.413,.503,.504],sup2:[.363,.431,.404],sup3:[.289,.286,.294],sub1:[.15,.143,.2],sub2:[.247,.286,.4],supDrop:[.386,.353,.494],subDrop:[.05,.071,.1],delim1:[2.39,1.7,1.98],delim2:[1.01,1.157,1.42],axisHeight:[.25,.25,.25],defaultRuleThickness:[.04,.049,.049],bigOpSpacing1:[.111,.111,.111],bigOpSpacing2:[.166,.166,.166],bigOpSpacing3:[.2,.2,.2],bigOpSpacing4:[.6,.611,.611],bigOpSpacing5:[.1,.143,.143],sqrtRuleThickness:[.04,.04,.04],ptPerEm:[10,10,10],doubleRuleSep:[.2,.2,.2],arrayRuleWidth:[.04,.04,.04],fboxsep:[.3,.3,.3],fboxrule:[.04,.04,.04]},Ma={"Å":"A","Ð":"D","Þ":"o","å":"a","ð":"d","þ":"o","А":"A","Б":"B","В":"B","Г":"F","Д":"A","Е":"E","Ж":"K","З":"3","И":"N","Й":"N","К":"K","Л":"N","М":"M","Н":"H","О":"O","П":"N","Р":"P","С":"C","Т":"T","У":"y","Ф":"O","Х":"X","Ц":"U","Ч":"h","Ш":"W","Щ":"W","Ъ":"B","Ы":"X","Ь":"B","Э":"3","Ю":"X","Я":"R","а":"a","б":"b","в":"a","г":"r","д":"y","е":"e","ж":"m","з":"e","и":"n","й":"n","к":"n","л":"n","м":"m","н":"n","о":"o","п":"n","р":"p","с":"c","т":"o","у":"y","ф":"b","х":"x","ц":"n","ч":"n","ш":"w","щ":"w","ъ":"a","ы":"m","ь":"a","э":"e","ю":"m","я":"r"};function ka(e,t,r){if(!wa[t])throw new Error("Font metrics not found for font: "+t+".");var n=e.charCodeAt(0),a=wa[t][n];if(!a&&e[0]in Ma&&(n=Ma[e[0]].charCodeAt(0),a=wa[t][n]),a||"text"!==r||Aa(n)&&(a=wa[t][77]),a)return{depth:a[0],height:a[1],italic:a[2],skew:a[3],width:a[4]}}var La={};var Pa=[[1,1,1],[2,1,1],[3,1,1],[4,2,1],[5,2,1],[6,3,1],[7,4,2],[8,6,3],[9,7,6],[10,8,7],[11,10,9]],Fa=[.5,.6,.7,.8,.9,1,1.2,1.44,1.728,2.074,2.488],Ba=function(e,t){return t.size<2?e:Pa[e-1][t.size-1]};class Ua{constructor(e){this.style=void 0,this.color=void 0,this.size=void 0,this.textSize=void 0,this.phantom=void 0,this.font=void 0,this.fontFamily=void 0,this.fontWeight=void 0,this.fontShape=void 0,this.sizeMultiplier=void 0,this.maxSize=void 0,this.minRuleThickness=void 0,this._fontMetrics=void 0,this.style=e.style,this.color=e.color,this.size=e.size||Ua.BASESIZE,this.textSize=e.textSize||this.size,this.phantom=!!e.phantom,this.font=e.font||"",this.fontFamily=e.fontFamily||"",this.fontWeight=e.fontWeight||"",this.fontShape=e.fontShape||"",this.sizeMultiplier=Fa[this.size-1],this.maxSize=e.maxSize,this.minRuleThickness=e.minRuleThickness,this._fontMetrics=void 0}extend(e){var t={style:this.style,size:this.size,textSize:this.textSize,color:this.color,phantom:this.phantom,font:this.font,fontFamily:this.fontFamily,fontWeight:this.fontWeight,fontShape:this.fontShape,maxSize:this.maxSize,minRuleThickness:this.minRuleThickness};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return new Ua(t)}havingStyle(e){return this.style===e?this:this.extend({style:e,size:Ba(this.textSize,e)})}havingCrampedStyle(){return this.havingStyle(this.style.cramp())}havingSize(e){return this.size===e&&this.textSize===e?this:this.extend({style:this.style.text(),size:e,textSize:e,sizeMultiplier:Fa[e-1]})}havingBaseStyle(e){e=e||this.style.text();var t=Ba(Ua.BASESIZE,e);return this.size===t&&this.textSize===Ua.BASESIZE&&this.style===e?this:this.extend({style:e,size:t})}havingBaseSizing(){var e;switch(this.style.id){case 4:case 5:e=3;break;case 6:case 7:e=1;break;default:e=6}return this.extend({style:this.style.text(),size:e})}withColor(e){return this.extend({color:e})}withPhantom(){return this.extend({phantom:!0})}withFont(e){return this.extend({font:e})}withTextFontFamily(e){return this.extend({fontFamily:e,font:""})}withTextFontWeight(e){return this.extend({fontWeight:e,font:""})}withTextFontShape(e){return this.extend({fontShape:e,font:""})}sizingClasses(e){return e.size!==this.size?["sizing","reset-size"+e.size,"size"+this.size]:[]}baseSizingClasses(){return this.size!==Ua.BASESIZE?["sizing","reset-size"+this.size,"size"+Ua.BASESIZE]:[]}fontMetrics(){return this._fontMetrics||(this._fontMetrics=function(e){var t;if(!La[t=e>=5?0:e>=3?1:2]){var r=La[t]={cssEmPerMu:Da.quad[t]/18};for(var n in Da)Da.hasOwnProperty(n)&&(r[n]=Da[n][t])}return La[t]}(this.size)),this._fontMetrics}getColor(){return this.phantom?"transparent":this.color}}Ua.BASESIZE=6;var Ga={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:1.00375,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:1.00375},za={ex:!0,em:!0,mu:!0},Ya=function(e){return"string"!=typeof e&&(e=e.unit),e in Ga||e in za||"ex"===e},qa=function(e,t){var r;if(e.unit in Ga)r=Ga[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if("mu"===e.unit)r=t.fontMetrics().cssEmPerMu;else{var n;if(n=t.style.isTight()?t.havingStyle(t.style.text()):t,"ex"===e.unit)r=n.fontMetrics().xHeight;else{if("em"!==e.unit)throw new sa("Invalid unit: '"+e.unit+"'");r=n.fontMetrics().quad}n!==t&&(r*=n.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*r,t.maxSize)},Ha=function(e){return+e.toFixed(4)+"em"},Va=function(e){return e.filter(e=>e).join(" ")},$a=function(e,t,r){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=r||{},t){t.style.isTight()&&this.classes.push("mtight");var n=t.getColor();n&&(this.style.color=n)}},Wa=function(e){var t=document.createElement(e);for(var r in t.className=Va(this.classes),this.style)this.style.hasOwnProperty(r)&&(t.style[r]=this.style[r]);for(var n in this.attributes)this.attributes.hasOwnProperty(n)&&t.setAttribute(n,this.attributes[n]);for(var a=0;a<this.children.length;a++)t.appendChild(this.children[a].toNode());return t},ja=/[\s"'>/=\x00-\x1f]/,Qa=function(e){var t="<"+e;this.classes.length&&(t+=' class="'+pa.escape(Va(this.classes))+'"');var r="";for(var n in this.style)this.style.hasOwnProperty(n)&&(r+=pa.hyphenate(n)+":"+this.style[n]+";");for(var a in r&&(t+=' style="'+pa.escape(r)+'"'),this.attributes)if(this.attributes.hasOwnProperty(a)){if(ja.test(a))throw new sa("Invalid attribute name '"+a+"'");t+=" "+a+'="'+pa.escape(this.attributes[a])+'"'}t+=">";for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+="</"+e+">"};class Ka{constructor(e,t,r,n){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,$a.call(this,e,r,n),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return Wa.call(this,"span")}toMarkup(){return Qa.call(this,"span")}}class Xa{constructor(e,t,r,n){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,$a.call(this,t,n),this.children=r||[],this.setAttribute("href",e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return Wa.call(this,"a")}toMarkup(){return Qa.call(this,"a")}}class Za{constructor(e,t,r){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=["mord"],this.style=r}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement("img");for(var t in e.src=this.src,e.alt=this.alt,e.className="mord",this.style)this.style.hasOwnProperty(t)&&(e.style[t]=this.style[t]);return e}toMarkup(){var e='<img src="'+pa.escape(this.src)+'" alt="'+pa.escape(this.alt)+'"',t="";for(var r in this.style)this.style.hasOwnProperty(r)&&(t+=pa.hyphenate(r)+":"+this.style[r]+";");return t&&(e+=' style="'+pa.escape(t)+'"'),e+="'/>"}}var Ja={"î":"ı̂","ï":"ı̈","í":"ı́","ì":"ı̀"};class ei{constructor(e,t,r,n,a,i,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=r||0,this.italic=n||0,this.skew=a||0,this.width=i||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var l=function(e){for(var t=0;t<Na.length;t++)for(var r=Na[t],n=0;n<r.blocks.length;n++){var a=r.blocks[n];if(e>=a[0]&&e<=a[1])return r.name}return null}(this.text.charCodeAt(0));l&&this.classes.push(l+"_fallback"),/[îïíì]/.test(this.text)&&(this.text=Ja[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;for(var r in this.italic>0&&((t=document.createElement("span")).style.marginRight=Ha(this.italic)),this.classes.length>0&&((t=t||document.createElement("span")).className=Va(this.classes)),this.style)this.style.hasOwnProperty(r)&&((t=t||document.createElement("span")).style[r]=this.style[r]);return t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t="<span";this.classes.length&&(e=!0,t+=' class="',t+=pa.escape(Va(this.classes)),t+='"');var r="";for(var n in this.italic>0&&(r+="margin-right:"+this.italic+"em;"),this.style)this.style.hasOwnProperty(n)&&(r+=pa.hyphenate(n)+":"+this.style[n]+";");r&&(e=!0,t+=' style="'+pa.escape(r)+'"');var a=pa.escape(this.text);return e?(t+=">",t+=a,t+="</span>"):a}}class ti{constructor(e,t){this.children=void 0,this.attributes=void 0,this.children=e||[],this.attributes=t||{}}toNode(){var e=document.createElementNS("http://www.w3.org/2000/svg","svg");for(var t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&e.setAttribute(t,this.attributes[t]);for(var r=0;r<this.children.length;r++)e.appendChild(this.children[r].toNode());return e}toMarkup(){var e='<svg xmlns="http://www.w3.org/2000/svg"';for(var t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&(e+=" "+t+'="'+pa.escape(this.attributes[t])+'"');e+=">";for(var r=0;r<this.children.length;r++)e+=this.children[r].toMarkup();return e+="</svg>"}}class ri{constructor(e,t){this.pathName=void 0,this.alternate=void 0,this.pathName=e,this.alternate=t}toNode(){var e=document.createElementNS("http://www.w3.org/2000/svg","path");return this.alternate?e.setAttribute("d",this.alternate):e.setAttribute("d",Ia[this.pathName]),e}toMarkup(){return this.alternate?'<path d="'+pa.escape(this.alternate)+'"/>':'<path d="'+pa.escape(Ia[this.pathName])+'"/>'}}class ni{constructor(e){this.attributes=void 0,this.attributes=e||{}}toNode(){var e=document.createElementNS("http://www.w3.org/2000/svg","line");for(var t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&e.setAttribute(t,this.attributes[t]);return e}toMarkup(){var e="<line";for(var t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&(e+=" "+t+'="'+pa.escape(this.attributes[t])+'"');return e+="/>"}}function ai(e){if(e instanceof ei)return e;throw new Error("Expected symbolNode but got "+String(e)+".")}var ii={bin:1,close:1,inner:1,open:1,punct:1,rel:1},oi={"accent-token":1,mathord:1,"op-token":1,spacing:1,textord:1},si={math:{},text:{}};function li(e,t,r,n,a,i){si[e][a]={font:t,group:r,replace:n},i&&n&&(si[e][n]=si[e][a])}var ci="math",di="text",ui="main",pi="ams",_i="accent-token",mi="bin",gi="close",hi="inner",fi="mathord",Ei="op-token",bi="open",Si="punct",vi="rel",Ti="spacing",yi="textord";li(ci,ui,vi,"≡","\\equiv",!0),li(ci,ui,vi,"≺","\\prec",!0),li(ci,ui,vi,"≻","\\succ",!0),li(ci,ui,vi,"∼","\\sim",!0),li(ci,ui,vi,"⊥","\\perp"),li(ci,ui,vi,"⪯","\\preceq",!0),li(ci,ui,vi,"⪰","\\succeq",!0),li(ci,ui,vi,"≃","\\simeq",!0),li(ci,ui,vi,"∣","\\mid",!0),li(ci,ui,vi,"≪","\\ll",!0),li(ci,ui,vi,"≫","\\gg",!0),li(ci,ui,vi,"≍","\\asymp",!0),li(ci,ui,vi,"∥","\\parallel"),li(ci,ui,vi,"⋈","\\bowtie",!0),li(ci,ui,vi,"⌣","\\smile",!0),li(ci,ui,vi,"⊑","\\sqsubseteq",!0),li(ci,ui,vi,"⊒","\\sqsupseteq",!0),li(ci,ui,vi,"≐","\\doteq",!0),li(ci,ui,vi,"⌢","\\frown",!0),li(ci,ui,vi,"∋","\\ni",!0),li(ci,ui,vi,"∝","\\propto",!0),li(ci,ui,vi,"⊢","\\vdash",!0),li(ci,ui,vi,"⊣","\\dashv",!0),li(ci,ui,vi,"∋","\\owns"),li(ci,ui,Si,".","\\ldotp"),li(ci,ui,Si,"⋅","\\cdotp"),li(ci,ui,yi,"#","\\#"),li(di,ui,yi,"#","\\#"),li(ci,ui,yi,"&","\\&"),li(di,ui,yi,"&","\\&"),li(ci,ui,yi,"ℵ","\\aleph",!0),li(ci,ui,yi,"∀","\\forall",!0),li(ci,ui,yi,"ℏ","\\hbar",!0),li(ci,ui,yi,"∃","\\exists",!0),li(ci,ui,yi,"∇","\\nabla",!0),li(ci,ui,yi,"♭","\\flat",!0),li(ci,ui,yi,"ℓ","\\ell",!0),li(ci,ui,yi,"♮","\\natural",!0),li(ci,ui,yi,"♣","\\clubsuit",!0),li(ci,ui,yi,"℘","\\wp",!0),li(ci,ui,yi,"♯","\\sharp",!0),li(ci,ui,yi,"♢","\\diamondsuit",!0),li(ci,ui,yi,"ℜ","\\Re",!0),li(ci,ui,yi,"♡","\\heartsuit",!0),li(ci,ui,yi,"ℑ","\\Im",!0),li(ci,ui,yi,"♠","\\spadesuit",!0),li(ci,ui,yi,"§","\\S",!0),li(di,ui,yi,"§","\\S"),li(ci,ui,yi,"¶","\\P",!0),li(di,ui,yi,"¶","\\P"),li(ci,ui,yi,"†","\\dag"),li(di,ui,yi,"†","\\dag"),li(di,ui,yi,"†","\\textdagger"),li(ci,ui,yi,"‡","\\ddag"),li(di,ui,yi,"‡","\\ddag"),li(di,ui,yi,"‡","\\textdaggerdbl"),li(ci,ui,gi,"⎱","\\rmoustache",!0),li(ci,ui,bi,"⎰","\\lmoustache",!0),li(ci,ui,gi,"⟯","\\rgroup",!0),li(ci,ui,bi,"⟮","\\lgroup",!0),li(ci,ui,mi,"∓","\\mp",!0),li(ci,ui,mi,"⊖","\\ominus",!0),li(ci,ui,mi,"⊎","\\uplus",!0),li(ci,ui,mi,"⊓","\\sqcap",!0),li(ci,ui,mi,"∗","\\ast"),li(ci,ui,mi,"⊔","\\sqcup",!0),li(ci,ui,mi,"◯","\\bigcirc",!0),li(ci,ui,mi,"∙","\\bullet",!0),li(ci,ui,mi,"‡","\\ddagger"),li(ci,ui,mi,"≀","\\wr",!0),li(ci,ui,mi,"⨿","\\amalg"),li(ci,ui,mi,"&","\\And"),li(ci,ui,vi,"⟵","\\longleftarrow",!0),li(ci,ui,vi,"⇐","\\Leftarrow",!0),li(ci,ui,vi,"⟸","\\Longleftarrow",!0),li(ci,ui,vi,"⟶","\\longrightarrow",!0),li(ci,ui,vi,"⇒","\\Rightarrow",!0),li(ci,ui,vi,"⟹","\\Longrightarrow",!0),li(ci,ui,vi,"↔","\\leftrightarrow",!0),li(ci,ui,vi,"⟷","\\longleftrightarrow",!0),li(ci,ui,vi,"⇔","\\Leftrightarrow",!0),li(ci,ui,vi,"⟺","\\Longleftrightarrow",!0),li(ci,ui,vi,"↦","\\mapsto",!0),li(ci,ui,vi,"⟼","\\longmapsto",!0),li(ci,ui,vi,"↗","\\nearrow",!0),li(ci,ui,vi,"↩","\\hookleftarrow",!0),li(ci,ui,vi,"↪","\\hookrightarrow",!0),li(ci,ui,vi,"↘","\\searrow",!0),li(ci,ui,vi,"↼","\\leftharpoonup",!0),li(ci,ui,vi,"⇀","\\rightharpoonup",!0),li(ci,ui,vi,"↙","\\swarrow",!0),li(ci,ui,vi,"↽","\\leftharpoondown",!0),li(ci,ui,vi,"⇁","\\rightharpoondown",!0),li(ci,ui,vi,"↖","\\nwarrow",!0),li(ci,ui,vi,"⇌","\\rightleftharpoons",!0),li(ci,pi,vi,"≮","\\nless",!0),li(ci,pi,vi,"","\\@nleqslant"),li(ci,pi,vi,"","\\@nleqq"),li(ci,pi,vi,"⪇","\\lneq",!0),li(ci,pi,vi,"≨","\\lneqq",!0),li(ci,pi,vi,"","\\@lvertneqq"),li(ci,pi,vi,"⋦","\\lnsim",!0),li(ci,pi,vi,"⪉","\\lnapprox",!0),li(ci,pi,vi,"⊀","\\nprec",!0),li(ci,pi,vi,"⋠","\\npreceq",!0),li(ci,pi,vi,"⋨","\\precnsim",!0),li(ci,pi,vi,"⪹","\\precnapprox",!0),li(ci,pi,vi,"≁","\\nsim",!0),li(ci,pi,vi,"","\\@nshortmid"),li(ci,pi,vi,"∤","\\nmid",!0),li(ci,pi,vi,"⊬","\\nvdash",!0),li(ci,pi,vi,"⊭","\\nvDash",!0),li(ci,pi,vi,"⋪","\\ntriangleleft"),li(ci,pi,vi,"⋬","\\ntrianglelefteq",!0),li(ci,pi,vi,"⊊","\\subsetneq",!0),li(ci,pi,vi,"","\\@varsubsetneq"),li(ci,pi,vi,"⫋","\\subsetneqq",!0),li(ci,pi,vi,"","\\@varsubsetneqq"),li(ci,pi,vi,"≯","\\ngtr",!0),li(ci,pi,vi,"","\\@ngeqslant"),li(ci,pi,vi,"","\\@ngeqq"),li(ci,pi,vi,"⪈","\\gneq",!0),li(ci,pi,vi,"≩","\\gneqq",!0),li(ci,pi,vi,"","\\@gvertneqq"),li(ci,pi,vi,"⋧","\\gnsim",!0),li(ci,pi,vi,"⪊","\\gnapprox",!0),li(ci,pi,vi,"⊁","\\nsucc",!0),li(ci,pi,vi,"⋡","\\nsucceq",!0),li(ci,pi,vi,"⋩","\\succnsim",!0),li(ci,pi,vi,"⪺","\\succnapprox",!0),li(ci,pi,vi,"≆","\\ncong",!0),li(ci,pi,vi,"","\\@nshortparallel"),li(ci,pi,vi,"∦","\\nparallel",!0),li(ci,pi,vi,"⊯","\\nVDash",!0),li(ci,pi,vi,"⋫","\\ntriangleright"),li(ci,pi,vi,"⋭","\\ntrianglerighteq",!0),li(ci,pi,vi,"","\\@nsupseteqq"),li(ci,pi,vi,"⊋","\\supsetneq",!0),li(ci,pi,vi,"","\\@varsupsetneq"),li(ci,pi,vi,"⫌","\\supsetneqq",!0),li(ci,pi,vi,"","\\@varsupsetneqq"),li(ci,pi,vi,"⊮","\\nVdash",!0),li(ci,pi,vi,"⪵","\\precneqq",!0),li(ci,pi,vi,"⪶","\\succneqq",!0),li(ci,pi,vi,"","\\@nsubseteqq"),li(ci,pi,mi,"⊴","\\unlhd"),li(ci,pi,mi,"⊵","\\unrhd"),li(ci,pi,vi,"↚","\\nleftarrow",!0),li(ci,pi,vi,"↛","\\nrightarrow",!0),li(ci,pi,vi,"⇍","\\nLeftarrow",!0),li(ci,pi,vi,"⇏","\\nRightarrow",!0),li(ci,pi,vi,"↮","\\nleftrightarrow",!0),li(ci,pi,vi,"⇎","\\nLeftrightarrow",!0),li(ci,pi,vi,"△","\\vartriangle"),li(ci,pi,yi,"ℏ","\\hslash"),li(ci,pi,yi,"▽","\\triangledown"),li(ci,pi,yi,"◊","\\lozenge"),li(ci,pi,yi,"Ⓢ","\\circledS"),li(ci,pi,yi,"®","\\circledR"),li(di,pi,yi,"®","\\circledR"),li(ci,pi,yi,"∡","\\measuredangle",!0),li(ci,pi,yi,"∄","\\nexists"),li(ci,pi,yi,"℧","\\mho"),li(ci,pi,yi,"Ⅎ","\\Finv",!0),li(ci,pi,yi,"⅁","\\Game",!0),li(ci,pi,yi,"‵","\\backprime"),li(ci,pi,yi,"▲","\\blacktriangle"),li(ci,pi,yi,"▼","\\blacktriangledown"),li(ci,pi,yi,"■","\\blacksquare"),li(ci,pi,yi,"⧫","\\blacklozenge"),li(ci,pi,yi,"★","\\bigstar"),li(ci,pi,yi,"∢","\\sphericalangle",!0),li(ci,pi,yi,"∁","\\complement",!0),li(ci,pi,yi,"ð","\\eth",!0),li(di,ui,yi,"ð","ð"),li(ci,pi,yi,"╱","\\diagup"),li(ci,pi,yi,"╲","\\diagdown"),li(ci,pi,yi,"□","\\square"),li(ci,pi,yi,"□","\\Box"),li(ci,pi,yi,"◊","\\Diamond"),li(ci,pi,yi,"¥","\\yen",!0),li(di,pi,yi,"¥","\\yen",!0),li(ci,pi,yi,"✓","\\checkmark",!0),li(di,pi,yi,"✓","\\checkmark"),li(ci,pi,yi,"ℶ","\\beth",!0),li(ci,pi,yi,"ℸ","\\daleth",!0),li(ci,pi,yi,"ℷ","\\gimel",!0),li(ci,pi,yi,"ϝ","\\digamma",!0),li(ci,pi,yi,"ϰ","\\varkappa"),li(ci,pi,bi,"┌","\\@ulcorner",!0),li(ci,pi,gi,"┐","\\@urcorner",!0),li(ci,pi,bi,"└","\\@llcorner",!0),li(ci,pi,gi,"┘","\\@lrcorner",!0),li(ci,pi,vi,"≦","\\leqq",!0),li(ci,pi,vi,"⩽","\\leqslant",!0),li(ci,pi,vi,"⪕","\\eqslantless",!0),li(ci,pi,vi,"≲","\\lesssim",!0),li(ci,pi,vi,"⪅","\\lessapprox",!0),li(ci,pi,vi,"≊","\\approxeq",!0),li(ci,pi,mi,"⋖","\\lessdot"),li(ci,pi,vi,"⋘","\\lll",!0),li(ci,pi,vi,"≶","\\lessgtr",!0),li(ci,pi,vi,"⋚","\\lesseqgtr",!0),li(ci,pi,vi,"⪋","\\lesseqqgtr",!0),li(ci,pi,vi,"≑","\\doteqdot"),li(ci,pi,vi,"≓","\\risingdotseq",!0),li(ci,pi,vi,"≒","\\fallingdotseq",!0),li(ci,pi,vi,"∽","\\backsim",!0),li(ci,pi,vi,"⋍","\\backsimeq",!0),li(ci,pi,vi,"⫅","\\subseteqq",!0),li(ci,pi,vi,"⋐","\\Subset",!0),li(ci,pi,vi,"⊏","\\sqsubset",!0),li(ci,pi,vi,"≼","\\preccurlyeq",!0),li(ci,pi,vi,"⋞","\\curlyeqprec",!0),li(ci,pi,vi,"≾","\\precsim",!0),li(ci,pi,vi,"⪷","\\precapprox",!0),li(ci,pi,vi,"⊲","\\vartriangleleft"),li(ci,pi,vi,"⊴","\\trianglelefteq"),li(ci,pi,vi,"⊨","\\vDash",!0),li(ci,pi,vi,"⊪","\\Vvdash",!0),li(ci,pi,vi,"⌣","\\smallsmile"),li(ci,pi,vi,"⌢","\\smallfrown"),li(ci,pi,vi,"≏","\\bumpeq",!0),li(ci,pi,vi,"≎","\\Bumpeq",!0),li(ci,pi,vi,"≧","\\geqq",!0),li(ci,pi,vi,"⩾","\\geqslant",!0),li(ci,pi,vi,"⪖","\\eqslantgtr",!0),li(ci,pi,vi,"≳","\\gtrsim",!0),li(ci,pi,vi,"⪆","\\gtrapprox",!0),li(ci,pi,mi,"⋗","\\gtrdot"),li(ci,pi,vi,"⋙","\\ggg",!0),li(ci,pi,vi,"≷","\\gtrless",!0),li(ci,pi,vi,"⋛","\\gtreqless",!0),li(ci,pi,vi,"⪌","\\gtreqqless",!0),li(ci,pi,vi,"≖","\\eqcirc",!0),li(ci,pi,vi,"≗","\\circeq",!0),li(ci,pi,vi,"≜","\\triangleq",!0),li(ci,pi,vi,"∼","\\thicksim"),li(ci,pi,vi,"≈","\\thickapprox"),li(ci,pi,vi,"⫆","\\supseteqq",!0),li(ci,pi,vi,"⋑","\\Supset",!0),li(ci,pi,vi,"⊐","\\sqsupset",!0),li(ci,pi,vi,"≽","\\succcurlyeq",!0),li(ci,pi,vi,"⋟","\\curlyeqsucc",!0),li(ci,pi,vi,"≿","\\succsim",!0),li(ci,pi,vi,"⪸","\\succapprox",!0),li(ci,pi,vi,"⊳","\\vartriangleright"),li(ci,pi,vi,"⊵","\\trianglerighteq"),li(ci,pi,vi,"⊩","\\Vdash",!0),li(ci,pi,vi,"∣","\\shortmid"),li(ci,pi,vi,"∥","\\shortparallel"),li(ci,pi,vi,"≬","\\between",!0),li(ci,pi,vi,"⋔","\\pitchfork",!0),li(ci,pi,vi,"∝","\\varpropto"),li(ci,pi,vi,"◀","\\blacktriangleleft"),li(ci,pi,vi,"∴","\\therefore",!0),li(ci,pi,vi,"∍","\\backepsilon"),li(ci,pi,vi,"▶","\\blacktriangleright"),li(ci,pi,vi,"∵","\\because",!0),li(ci,pi,vi,"⋘","\\llless"),li(ci,pi,vi,"⋙","\\gggtr"),li(ci,pi,mi,"⊲","\\lhd"),li(ci,pi,mi,"⊳","\\rhd"),li(ci,pi,vi,"≂","\\eqsim",!0),li(ci,ui,vi,"⋈","\\Join"),li(ci,pi,vi,"≑","\\Doteq",!0),li(ci,pi,mi,"∔","\\dotplus",!0),li(ci,pi,mi,"∖","\\smallsetminus"),li(ci,pi,mi,"⋒","\\Cap",!0),li(ci,pi,mi,"⋓","\\Cup",!0),li(ci,pi,mi,"⩞","\\doublebarwedge",!0),li(ci,pi,mi,"⊟","\\boxminus",!0),li(ci,pi,mi,"⊞","\\boxplus",!0),li(ci,pi,mi,"⋇","\\divideontimes",!0),li(ci,pi,mi,"⋉","\\ltimes",!0),li(ci,pi,mi,"⋊","\\rtimes",!0),li(ci,pi,mi,"⋋","\\leftthreetimes",!0),li(ci,pi,mi,"⋌","\\rightthreetimes",!0),li(ci,pi,mi,"⋏","\\curlywedge",!0),li(ci,pi,mi,"⋎","\\curlyvee",!0),li(ci,pi,mi,"⊝","\\circleddash",!0),li(ci,pi,mi,"⊛","\\circledast",!0),li(ci,pi,mi,"⋅","\\centerdot"),li(ci,pi,mi,"⊺","\\intercal",!0),li(ci,pi,mi,"⋒","\\doublecap"),li(ci,pi,mi,"⋓","\\doublecup"),li(ci,pi,mi,"⊠","\\boxtimes",!0),li(ci,pi,vi,"⇢","\\dashrightarrow",!0),li(ci,pi,vi,"⇠","\\dashleftarrow",!0),li(ci,pi,vi,"⇇","\\leftleftarrows",!0),li(ci,pi,vi,"⇆","\\leftrightarrows",!0),li(ci,pi,vi,"⇚","\\Lleftarrow",!0),li(ci,pi,vi,"↞","\\twoheadleftarrow",!0),li(ci,pi,vi,"↢","\\leftarrowtail",!0),li(ci,pi,vi,"↫","\\looparrowleft",!0),li(ci,pi,vi,"⇋","\\leftrightharpoons",!0),li(ci,pi,vi,"↶","\\curvearrowleft",!0),li(ci,pi,vi,"↺","\\circlearrowleft",!0),li(ci,pi,vi,"↰","\\Lsh",!0),li(ci,pi,vi,"⇈","\\upuparrows",!0),li(ci,pi,vi,"↿","\\upharpoonleft",!0),li(ci,pi,vi,"⇃","\\downharpoonleft",!0),li(ci,ui,vi,"⊶","\\origof",!0),li(ci,ui,vi,"⊷","\\imageof",!0),li(ci,pi,vi,"⊸","\\multimap",!0),li(ci,pi,vi,"↭","\\leftrightsquigarrow",!0),li(ci,pi,vi,"⇉","\\rightrightarrows",!0),li(ci,pi,vi,"⇄","\\rightleftarrows",!0),li(ci,pi,vi,"↠","\\twoheadrightarrow",!0),li(ci,pi,vi,"↣","\\rightarrowtail",!0),li(ci,pi,vi,"↬","\\looparrowright",!0),li(ci,pi,vi,"↷","\\curvearrowright",!0),li(ci,pi,vi,"↻","\\circlearrowright",!0),li(ci,pi,vi,"↱","\\Rsh",!0),li(ci,pi,vi,"⇊","\\downdownarrows",!0),li(ci,pi,vi,"↾","\\upharpoonright",!0),li(ci,pi,vi,"⇂","\\downharpoonright",!0),li(ci,pi,vi,"⇝","\\rightsquigarrow",!0),li(ci,pi,vi,"⇝","\\leadsto"),li(ci,pi,vi,"⇛","\\Rrightarrow",!0),li(ci,pi,vi,"↾","\\restriction"),li(ci,ui,yi,"‘","`"),li(ci,ui,yi,"$","\\$"),li(di,ui,yi,"$","\\$"),li(di,ui,yi,"$","\\textdollar"),li(ci,ui,yi,"%","\\%"),li(di,ui,yi,"%","\\%"),li(ci,ui,yi,"_","\\_"),li(di,ui,yi,"_","\\_"),li(di,ui,yi,"_","\\textunderscore"),li(ci,ui,yi,"∠","\\angle",!0),li(ci,ui,yi,"∞","\\infty",!0),li(ci,ui,yi,"′","\\prime"),li(ci,ui,yi,"△","\\triangle"),li(ci,ui,yi,"Γ","\\Gamma",!0),li(ci,ui,yi,"Δ","\\Delta",!0),li(ci,ui,yi,"Θ","\\Theta",!0),li(ci,ui,yi,"Λ","\\Lambda",!0),li(ci,ui,yi,"Ξ","\\Xi",!0),li(ci,ui,yi,"Π","\\Pi",!0),li(ci,ui,yi,"Σ","\\Sigma",!0),li(ci,ui,yi,"Υ","\\Upsilon",!0),li(ci,ui,yi,"Φ","\\Phi",!0),li(ci,ui,yi,"Ψ","\\Psi",!0),li(ci,ui,yi,"Ω","\\Omega",!0),li(ci,ui,yi,"A","Α"),li(ci,ui,yi,"B","Β"),li(ci,ui,yi,"E","Ε"),li(ci,ui,yi,"Z","Ζ"),li(ci,ui,yi,"H","Η"),li(ci,ui,yi,"I","Ι"),li(ci,ui,yi,"K","Κ"),li(ci,ui,yi,"M","Μ"),li(ci,ui,yi,"N","Ν"),li(ci,ui,yi,"O","Ο"),li(ci,ui,yi,"P","Ρ"),li(ci,ui,yi,"T","Τ"),li(ci,ui,yi,"X","Χ"),li(ci,ui,yi,"¬","\\neg",!0),li(ci,ui,yi,"¬","\\lnot"),li(ci,ui,yi,"⊤","\\top"),li(ci,ui,yi,"⊥","\\bot"),li(ci,ui,yi,"∅","\\emptyset"),li(ci,pi,yi,"∅","\\varnothing"),li(ci,ui,fi,"α","\\alpha",!0),li(ci,ui,fi,"β","\\beta",!0),li(ci,ui,fi,"γ","\\gamma",!0),li(ci,ui,fi,"δ","\\delta",!0),li(ci,ui,fi,"ϵ","\\epsilon",!0),li(ci,ui,fi,"ζ","\\zeta",!0),li(ci,ui,fi,"η","\\eta",!0),li(ci,ui,fi,"θ","\\theta",!0),li(ci,ui,fi,"ι","\\iota",!0),li(ci,ui,fi,"κ","\\kappa",!0),li(ci,ui,fi,"λ","\\lambda",!0),li(ci,ui,fi,"μ","\\mu",!0),li(ci,ui,fi,"ν","\\nu",!0),li(ci,ui,fi,"ξ","\\xi",!0),li(ci,ui,fi,"ο","\\omicron",!0),li(ci,ui,fi,"π","\\pi",!0),li(ci,ui,fi,"ρ","\\rho",!0),li(ci,ui,fi,"σ","\\sigma",!0),li(ci,ui,fi,"τ","\\tau",!0),li(ci,ui,fi,"υ","\\upsilon",!0),li(ci,ui,fi,"ϕ","\\phi",!0),li(ci,ui,fi,"χ","\\chi",!0),li(ci,ui,fi,"ψ","\\psi",!0),li(ci,ui,fi,"ω","\\omega",!0),li(ci,ui,fi,"ε","\\varepsilon",!0),li(ci,ui,fi,"ϑ","\\vartheta",!0),li(ci,ui,fi,"ϖ","\\varpi",!0),li(ci,ui,fi,"ϱ","\\varrho",!0),li(ci,ui,fi,"ς","\\varsigma",!0),li(ci,ui,fi,"φ","\\varphi",!0),li(ci,ui,mi,"∗","*",!0),li(ci,ui,mi,"+","+"),li(ci,ui,mi,"−","-",!0),li(ci,ui,mi,"⋅","\\cdot",!0),li(ci,ui,mi,"∘","\\circ",!0),li(ci,ui,mi,"÷","\\div",!0),li(ci,ui,mi,"±","\\pm",!0),li(ci,ui,mi,"×","\\times",!0),li(ci,ui,mi,"∩","\\cap",!0),li(ci,ui,mi,"∪","\\cup",!0),li(ci,ui,mi,"∖","\\setminus",!0),li(ci,ui,mi,"∧","\\land"),li(ci,ui,mi,"∨","\\lor"),li(ci,ui,mi,"∧","\\wedge",!0),li(ci,ui,mi,"∨","\\vee",!0),li(ci,ui,yi,"√","\\surd"),li(ci,ui,bi,"⟨","\\langle",!0),li(ci,ui,bi,"∣","\\lvert"),li(ci,ui,bi,"∥","\\lVert"),li(ci,ui,gi,"?","?"),li(ci,ui,gi,"!","!"),li(ci,ui,gi,"⟩","\\rangle",!0),li(ci,ui,gi,"∣","\\rvert"),li(ci,ui,gi,"∥","\\rVert"),li(ci,ui,vi,"=","="),li(ci,ui,vi,":",":"),li(ci,ui,vi,"≈","\\approx",!0),li(ci,ui,vi,"≅","\\cong",!0),li(ci,ui,vi,"≥","\\ge"),li(ci,ui,vi,"≥","\\geq",!0),li(ci,ui,vi,"←","\\gets"),li(ci,ui,vi,">","\\gt",!0),li(ci,ui,vi,"∈","\\in",!0),li(ci,ui,vi,"","\\@not"),li(ci,ui,vi,"⊂","\\subset",!0),li(ci,ui,vi,"⊃","\\supset",!0),li(ci,ui,vi,"⊆","\\subseteq",!0),li(ci,ui,vi,"⊇","\\supseteq",!0),li(ci,pi,vi,"⊈","\\nsubseteq",!0),li(ci,pi,vi,"⊉","\\nsupseteq",!0),li(ci,ui,vi,"⊨","\\models"),li(ci,ui,vi,"←","\\leftarrow",!0),li(ci,ui,vi,"≤","\\le"),li(ci,ui,vi,"≤","\\leq",!0),li(ci,ui,vi,"<","\\lt",!0),li(ci,ui,vi,"→","\\rightarrow",!0),li(ci,ui,vi,"→","\\to"),li(ci,pi,vi,"≱","\\ngeq",!0),li(ci,pi,vi,"≰","\\nleq",!0),li(ci,ui,Ti," ","\\ "),li(ci,ui,Ti," ","\\space"),li(ci,ui,Ti," ","\\nobreakspace"),li(di,ui,Ti," ","\\ "),li(di,ui,Ti," "," "),li(di,ui,Ti," ","\\space"),li(di,ui,Ti," ","\\nobreakspace"),li(ci,ui,Ti,null,"\\nobreak"),li(ci,ui,Ti,null,"\\allowbreak"),li(ci,ui,Si,",",","),li(ci,ui,Si,";",";"),li(ci,pi,mi,"⊼","\\barwedge",!0),li(ci,pi,mi,"⊻","\\veebar",!0),li(ci,ui,mi,"⊙","\\odot",!0),li(ci,ui,mi,"⊕","\\oplus",!0),li(ci,ui,mi,"⊗","\\otimes",!0),li(ci,ui,yi,"∂","\\partial",!0),li(ci,ui,mi,"⊘","\\oslash",!0),li(ci,pi,mi,"⊚","\\circledcirc",!0),li(ci,pi,mi,"⊡","\\boxdot",!0),li(ci,ui,mi,"△","\\bigtriangleup"),li(ci,ui,mi,"▽","\\bigtriangledown"),li(ci,ui,mi,"†","\\dagger"),li(ci,ui,mi,"⋄","\\diamond"),li(ci,ui,mi,"⋆","\\star"),li(ci,ui,mi,"◃","\\triangleleft"),li(ci,ui,mi,"▹","\\triangleright"),li(ci,ui,bi,"{","\\{"),li(di,ui,yi,"{","\\{"),li(di,ui,yi,"{","\\textbraceleft"),li(ci,ui,gi,"}","\\}"),li(di,ui,yi,"}","\\}"),li(di,ui,yi,"}","\\textbraceright"),li(ci,ui,bi,"{","\\lbrace"),li(ci,ui,gi,"}","\\rbrace"),li(ci,ui,bi,"[","\\lbrack",!0),li(di,ui,yi,"[","\\lbrack",!0),li(ci,ui,gi,"]","\\rbrack",!0),li(di,ui,yi,"]","\\rbrack",!0),li(ci,ui,bi,"(","\\lparen",!0),li(ci,ui,gi,")","\\rparen",!0),li(di,ui,yi,"<","\\textless",!0),li(di,ui,yi,">","\\textgreater",!0),li(ci,ui,bi,"⌊","\\lfloor",!0),li(ci,ui,gi,"⌋","\\rfloor",!0),li(ci,ui,bi,"⌈","\\lceil",!0),li(ci,ui,gi,"⌉","\\rceil",!0),li(ci,ui,yi,"\\","\\backslash"),li(ci,ui,yi,"∣","|"),li(ci,ui,yi,"∣","\\vert"),li(di,ui,yi,"|","\\textbar",!0),li(ci,ui,yi,"∥","\\|"),li(ci,ui,yi,"∥","\\Vert"),li(di,ui,yi,"∥","\\textbardbl"),li(di,ui,yi,"~","\\textasciitilde"),li(di,ui,yi,"\\","\\textbackslash"),li(di,ui,yi,"^","\\textasciicircum"),li(ci,ui,vi,"↑","\\uparrow",!0),li(ci,ui,vi,"⇑","\\Uparrow",!0),li(ci,ui,vi,"↓","\\downarrow",!0),li(ci,ui,vi,"⇓","\\Downarrow",!0),li(ci,ui,vi,"↕","\\updownarrow",!0),li(ci,ui,vi,"⇕","\\Updownarrow",!0),li(ci,ui,Ei,"∐","\\coprod"),li(ci,ui,Ei,"⋁","\\bigvee"),li(ci,ui,Ei,"⋀","\\bigwedge"),li(ci,ui,Ei,"⨄","\\biguplus"),li(ci,ui,Ei,"⋂","\\bigcap"),li(ci,ui,Ei,"⋃","\\bigcup"),li(ci,ui,Ei,"∫","\\int"),li(ci,ui,Ei,"∫","\\intop"),li(ci,ui,Ei,"∬","\\iint"),li(ci,ui,Ei,"∭","\\iiint"),li(ci,ui,Ei,"∏","\\prod"),li(ci,ui,Ei,"∑","\\sum"),li(ci,ui,Ei,"⨂","\\bigotimes"),li(ci,ui,Ei,"⨁","\\bigoplus"),li(ci,ui,Ei,"⨀","\\bigodot"),li(ci,ui,Ei,"∮","\\oint"),li(ci,ui,Ei,"∯","\\oiint"),li(ci,ui,Ei,"∰","\\oiiint"),li(ci,ui,Ei,"⨆","\\bigsqcup"),li(ci,ui,Ei,"∫","\\smallint"),li(di,ui,hi,"…","\\textellipsis"),li(ci,ui,hi,"…","\\mathellipsis"),li(di,ui,hi,"…","\\ldots",!0),li(ci,ui,hi,"…","\\ldots",!0),li(ci,ui,hi,"⋯","\\@cdots",!0),li(ci,ui,hi,"⋱","\\ddots",!0),li(ci,ui,yi,"⋮","\\varvdots"),li(di,ui,yi,"⋮","\\varvdots"),li(ci,ui,_i,"ˊ","\\acute"),li(ci,ui,_i,"ˋ","\\grave"),li(ci,ui,_i,"¨","\\ddot"),li(ci,ui,_i,"~","\\tilde"),li(ci,ui,_i,"ˉ","\\bar"),li(ci,ui,_i,"˘","\\breve"),li(ci,ui,_i,"ˇ","\\check"),li(ci,ui,_i,"^","\\hat"),li(ci,ui,_i,"⃗","\\vec"),li(ci,ui,_i,"˙","\\dot"),li(ci,ui,_i,"˚","\\mathring"),li(ci,ui,fi,"","\\@imath"),li(ci,ui,fi,"","\\@jmath"),li(ci,ui,yi,"ı","ı"),li(ci,ui,yi,"ȷ","ȷ"),li(di,ui,yi,"ı","\\i",!0),li(di,ui,yi,"ȷ","\\j",!0),li(di,ui,yi,"ß","\\ss",!0),li(di,ui,yi,"æ","\\ae",!0),li(di,ui,yi,"œ","\\oe",!0),li(di,ui,yi,"ø","\\o",!0),li(di,ui,yi,"Æ","\\AE",!0),li(di,ui,yi,"Œ","\\OE",!0),li(di,ui,yi,"Ø","\\O",!0),li(di,ui,_i,"ˊ","\\'"),li(di,ui,_i,"ˋ","\\`"),li(di,ui,_i,"ˆ","\\^"),li(di,ui,_i,"˜","\\~"),li(di,ui,_i,"ˉ","\\="),li(di,ui,_i,"˘","\\u"),li(di,ui,_i,"˙","\\."),li(di,ui,_i,"¸","\\c"),li(di,ui,_i,"˚","\\r"),li(di,ui,_i,"ˇ","\\v"),li(di,ui,_i,"¨",'\\"'),li(di,ui,_i,"˝","\\H"),li(di,ui,_i,"◯","\\textcircled");var Ci={"--":!0,"---":!0,"``":!0,"''":!0};li(di,ui,yi,"–","--",!0),li(di,ui,yi,"–","\\textendash"),li(di,ui,yi,"—","---",!0),li(di,ui,yi,"—","\\textemdash"),li(di,ui,yi,"‘","`",!0),li(di,ui,yi,"‘","\\textquoteleft"),li(di,ui,yi,"’","'",!0),li(di,ui,yi,"’","\\textquoteright"),li(di,ui,yi,"“","``",!0),li(di,ui,yi,"“","\\textquotedblleft"),li(di,ui,yi,"”","''",!0),li(di,ui,yi,"”","\\textquotedblright"),li(ci,ui,yi,"°","\\degree",!0),li(di,ui,yi,"°","\\degree"),li(di,ui,yi,"°","\\textdegree",!0),li(ci,ui,yi,"£","\\pounds"),li(ci,ui,yi,"£","\\mathsterling",!0),li(di,ui,yi,"£","\\pounds"),li(di,ui,yi,"£","\\textsterling",!0),li(ci,pi,yi,"✠","\\maltese"),li(di,pi,yi,"✠","\\maltese");for(var Ni='0123456789/@."',Ri=0;Ri<14;Ri++){var Ai=Ni.charAt(Ri);li(ci,ui,yi,Ai,Ai)}for(var Oi='0123456789!@*()-=+";:?/.,',Ii=0;Ii<25;Ii++){var xi=Oi.charAt(Ii);li(di,ui,yi,xi,xi)}for(var wi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Di=0;Di<52;Di++){var Mi=wi.charAt(Di);li(ci,ui,fi,Mi,Mi),li(di,ui,yi,Mi,Mi)}li(ci,pi,yi,"C","ℂ"),li(di,pi,yi,"C","ℂ"),li(ci,pi,yi,"H","ℍ"),li(di,pi,yi,"H","ℍ"),li(ci,pi,yi,"N","ℕ"),li(di,pi,yi,"N","ℕ"),li(ci,pi,yi,"P","ℙ"),li(di,pi,yi,"P","ℙ"),li(ci,pi,yi,"Q","ℚ"),li(di,pi,yi,"Q","ℚ"),li(ci,pi,yi,"R","ℝ"),li(di,pi,yi,"R","ℝ"),li(ci,pi,yi,"Z","ℤ"),li(di,pi,yi,"Z","ℤ"),li(ci,ui,fi,"h","ℎ"),li(di,ui,fi,"h","ℎ");for(var ki="",Li=0;Li<52;Li++){var Pi=wi.charAt(Li);li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56320+Li)),li(di,ui,yi,Pi,ki),li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56372+Li)),li(di,ui,yi,Pi,ki),li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56424+Li)),li(di,ui,yi,Pi,ki),li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56580+Li)),li(di,ui,yi,Pi,ki),li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56684+Li)),li(di,ui,yi,Pi,ki),li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56736+Li)),li(di,ui,yi,Pi,ki),li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56788+Li)),li(di,ui,yi,Pi,ki),li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56840+Li)),li(di,ui,yi,Pi,ki),li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56944+Li)),li(di,ui,yi,Pi,ki),Li<26&&(li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56632+Li)),li(di,ui,yi,Pi,ki),li(ci,ui,fi,Pi,ki=String.fromCharCode(55349,56476+Li)),li(di,ui,yi,Pi,ki))}li(ci,ui,fi,"k",ki=String.fromCharCode(55349,56668)),li(di,ui,yi,"k",ki);for(var Fi=0;Fi<10;Fi++){var Bi=Fi.toString();li(ci,ui,fi,Bi,ki=String.fromCharCode(55349,57294+Fi)),li(di,ui,yi,Bi,ki),li(ci,ui,fi,Bi,ki=String.fromCharCode(55349,57314+Fi)),li(di,ui,yi,Bi,ki),li(ci,ui,fi,Bi,ki=String.fromCharCode(55349,57324+Fi)),li(di,ui,yi,Bi,ki),li(ci,ui,fi,Bi,ki=String.fromCharCode(55349,57334+Fi)),li(di,ui,yi,Bi,ki)}for(var Ui="ÐÞþ",Gi=0;Gi<3;Gi++){var zi=Ui.charAt(Gi);li(ci,ui,fi,zi,zi),li(di,ui,yi,zi,zi)}var Yi=[["mathbf","textbf","Main-Bold"],["mathbf","textbf","Main-Bold"],["mathnormal","textit","Math-Italic"],["mathnormal","textit","Math-Italic"],["boldsymbol","boldsymbol","Main-BoldItalic"],["boldsymbol","boldsymbol","Main-BoldItalic"],["mathscr","textscr","Script-Regular"],["","",""],["","",""],["","",""],["mathfrak","textfrak","Fraktur-Regular"],["mathfrak","textfrak","Fraktur-Regular"],["mathbb","textbb","AMS-Regular"],["mathbb","textbb","AMS-Regular"],["mathboldfrak","textboldfrak","Fraktur-Regular"],["mathboldfrak","textboldfrak","Fraktur-Regular"],["mathsf","textsf","SansSerif-Regular"],["mathsf","textsf","SansSerif-Regular"],["mathboldsf","textboldsf","SansSerif-Bold"],["mathboldsf","textboldsf","SansSerif-Bold"],["mathitsf","textitsf","SansSerif-Italic"],["mathitsf","textitsf","SansSerif-Italic"],["","",""],["","",""],["mathtt","texttt","Typewriter-Regular"],["mathtt","texttt","Typewriter-Regular"]],qi=[["mathbf","textbf","Main-Bold"],["","",""],["mathsf","textsf","SansSerif-Regular"],["mathboldsf","textboldsf","SansSerif-Bold"],["mathtt","texttt","Typewriter-Regular"]],Hi=function(e,t,r){return si[r][e]&&si[r][e].replace&&(e=si[r][e].replace),{value:e,metrics:ka(e,t,r)}},Vi=function(e,t,r,n,a){var i,o=Hi(e,t,r),s=o.metrics;if(e=o.value,s){var l=s.italic;("text"===r||n&&"mathit"===n.font)&&(l=0),i=new ei(e,s.height,s.depth,l,s.skew,s.width,a)}else"undefined"!=typeof console&&console.warn("No character metrics for '"+e+"' in style '"+t+"' and mode '"+r+"'"),i=new ei(e,0,0,0,0,0,a);if(n){i.maxFontSize=n.sizeMultiplier,n.style.isTight()&&i.classes.push("mtight");var c=n.getColor();c&&(i.style.color=c)}return i},$i=(e,t)=>{if(Va(e.classes)!==Va(t.classes)||e.skew!==t.skew||e.maxFontSize!==t.maxFontSize)return!1;if(1===e.classes.length){var r=e.classes[0];if("mbin"===r||"mord"===r)return!1}for(var n in e.style)if(e.style.hasOwnProperty(n)&&e.style[n]!==t.style[n])return!1;for(var a in t.style)if(t.style.hasOwnProperty(a)&&e.style[a]!==t.style[a])return!1;return!0},Wi=function(e){for(var t=0,r=0,n=0,a=0;a<e.children.length;a++){var i=e.children[a];i.height>t&&(t=i.height),i.depth>r&&(r=i.depth),i.maxFontSize>n&&(n=i.maxFontSize)}e.height=t,e.depth=r,e.maxFontSize=n},ji=function(e,t,r,n){var a=new Ka(e,t,r,n);return Wi(a),a},Qi=(e,t,r,n)=>new Ka(e,t,r,n),Ki=function(e){var t=new xa(e);return Wi(t),t},Xi=function(e,t,r){var n="";switch(e){case"amsrm":n="AMS";break;case"textrm":n="Main";break;case"textsf":n="SansSerif";break;case"texttt":n="Typewriter";break;default:n=e}return n+"-"+("textbf"===t&&"textit"===r?"BoldItalic":"textbf"===t?"Bold":"textit"===t?"Italic":"Regular")},Zi={mathbf:{variant:"bold",fontName:"Main-Bold"},mathrm:{variant:"normal",fontName:"Main-Regular"},textit:{variant:"italic",fontName:"Main-Italic"},mathit:{variant:"italic",fontName:"Main-Italic"},mathnormal:{variant:"italic",fontName:"Math-Italic"},mathsfit:{variant:"sans-serif-italic",fontName:"SansSerif-Italic"},mathbb:{variant:"double-struck",fontName:"AMS-Regular"},mathcal:{variant:"script",fontName:"Caligraphic-Regular"},mathfrak:{variant:"fraktur",fontName:"Fraktur-Regular"},mathscr:{variant:"script",fontName:"Script-Regular"},mathsf:{variant:"sans-serif",fontName:"SansSerif-Regular"},mathtt:{variant:"monospace",fontName:"Typewriter-Regular"}},Ji={vec:["vec",.471,.714],oiintSize1:["oiintSize1",.957,.499],oiintSize2:["oiintSize2",1.472,.659],oiiintSize1:["oiiintSize1",1.304,.499],oiiintSize2:["oiiintSize2",1.98,.659]},eo={fontMap:Zi,makeSymbol:Vi,mathsym:function(e,t,r,n){return void 0===n&&(n=[]),"boldsymbol"===r.font&&Hi(e,"Main-Bold",t).metrics?Vi(e,"Main-Bold",t,r,n.concat(["mathbf"])):"\\"===e||"main"===si[t][e].font?Vi(e,"Main-Regular",t,r,n):Vi(e,"AMS-Regular",t,r,n.concat(["amsrm"]))},makeSpan:ji,makeSvgSpan:Qi,makeLineSpan:function(e,t,r){var n=ji([e],[],t);return n.height=Math.max(r||t.fontMetrics().defaultRuleThickness,t.minRuleThickness),n.style.borderBottomWidth=Ha(n.height),n.maxFontSize=1,n},makeAnchor:function(e,t,r,n){var a=new Xa(e,t,r,n);return Wi(a),a},makeFragment:Ki,wrapFragment:function(e,t){return e instanceof xa?ji([],[e],t):e},makeVList:function(e,t){for(var{children:r,depth:n}=function(e){if("individualShift"===e.positionType){for(var t=e.children,r=[t[0]],n=-t[0].shift-t[0].elem.depth,a=n,i=1;i<t.length;i++){var o=-t[i].shift-a-t[i].elem.depth,s=o-(t[i-1].elem.height+t[i-1].elem.depth);a+=o,r.push({type:"kern",size:s}),r.push(t[i])}return{children:r,depth:n}}var l;if("top"===e.positionType){for(var c=e.positionData,d=0;d<e.children.length;d++){var u=e.children[d];c-="kern"===u.type?u.size:u.elem.height+u.elem.depth}l=c}else if("bottom"===e.positionType)l=-e.positionData;else{var p=e.children[0];if("elem"!==p.type)throw new Error('First child must have type "elem".');if("shift"===e.positionType)l=-p.elem.depth-e.positionData;else{if("firstBaseline"!==e.positionType)throw new Error("Invalid positionType "+e.positionType+".");l=-p.elem.depth}}return{children:e.children,depth:l}}(e),a=0,i=0;i<r.length;i++){var o=r[i];if("elem"===o.type){var s=o.elem;a=Math.max(a,s.maxFontSize,s.height)}}a+=2;var l=ji(["pstrut"],[]);l.style.height=Ha(a);for(var c=[],d=n,u=n,p=n,_=0;_<r.length;_++){var m=r[_];if("kern"===m.type)p+=m.size;else{var g=m.elem,h=m.wrapperClasses||[],f=m.wrapperStyle||{},E=ji(h,[l,g],void 0,f);E.style.top=Ha(-a-p-g.depth),m.marginLeft&&(E.style.marginLeft=m.marginLeft),m.marginRight&&(E.style.marginRight=m.marginRight),c.push(E),p+=g.height+g.depth}d=Math.min(d,p),u=Math.max(u,p)}var b,S=ji(["vlist"],c);if(S.style.height=Ha(u),d<0){var v=ji([],[]),T=ji(["vlist"],[v]);T.style.height=Ha(-d);var y=ji(["vlist-s"],[new ei("​")]);b=[ji(["vlist-r"],[S,y]),ji(["vlist-r"],[T])]}else b=[ji(["vlist-r"],[S])];var C=ji(["vlist-t"],b);return 2===b.length&&C.classes.push("vlist-t2"),C.height=u,C.depth=-d,C},makeOrd:function(e,t,r){var n=e.mode,a=e.text,i=["mord"],o="math"===n||"text"===n&&t.font,s=o?t.font:t.fontFamily,l="",c="";if(55349===a.charCodeAt(0)&&([l,c]=function(e,t){var r=1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320)+65536,n="math"===t?0:1;if(119808<=r&&r<120484){var a=Math.floor((r-119808)/26);return[Yi[a][2],Yi[a][n]]}if(120782<=r&&r<=120831){var i=Math.floor((r-120782)/10);return[qi[i][2],qi[i][n]]}if(120485===r||120486===r)return[Yi[0][2],Yi[0][n]];if(120486<r&&r<120782)return["",""];throw new sa("Unsupported character: "+e)}(a,n)),l.length>0)return Vi(a,l,n,t,i.concat(c));if(s){var d,u;if("boldsymbol"===s){var p=function(e,t,r,n,a){return"textord"!==a&&Hi(e,"Math-BoldItalic",t).metrics?{fontName:"Math-BoldItalic",fontClass:"boldsymbol"}:{fontName:"Main-Bold",fontClass:"mathbf"}}(a,n,0,0,r);d=p.fontName,u=[p.fontClass]}else o?(d=Zi[s].fontName,u=[s]):(d=Xi(s,t.fontWeight,t.fontShape),u=[s,t.fontWeight,t.fontShape]);if(Hi(a,d,n).metrics)return Vi(a,d,n,t,i.concat(u));if(Ci.hasOwnProperty(a)&&"Typewriter"===d.slice(0,10)){for(var _=[],m=0;m<a.length;m++)_.push(Vi(a[m],d,n,t,i.concat(u)));return Ki(_)}}if("mathord"===r)return Vi(a,"Math-Italic",n,t,i.concat(["mathnormal"]));if("textord"===r){var g=si[n][a]&&si[n][a].font;if("ams"===g){var h=Xi("amsrm",t.fontWeight,t.fontShape);return Vi(a,h,n,t,i.concat("amsrm",t.fontWeight,t.fontShape))}if("main"!==g&&g){var f=Xi(g,t.fontWeight,t.fontShape);return Vi(a,f,n,t,i.concat(f,t.fontWeight,t.fontShape))}var E=Xi("textrm",t.fontWeight,t.fontShape);return Vi(a,E,n,t,i.concat(t.fontWeight,t.fontShape))}throw new Error("unexpected type: "+r+" in makeOrd")},makeGlue:(e,t)=>{var r=ji(["mspace"],[],t),n=qa(e,t);return r.style.marginRight=Ha(n),r},staticSvg:function(e,t){var[r,n,a]=Ji[e],i=new ri(r),o=new ti([i],{width:Ha(n),height:Ha(a),style:"width:"+Ha(n),viewBox:"0 0 "+1e3*n+" "+1e3*a,preserveAspectRatio:"xMinYMin"}),s=Qi(["overlay"],[o],t);return s.height=a,s.style.height=Ha(a),s.style.width=Ha(n),s},svgData:Ji,tryCombineChars:e=>{for(var t=0;t<e.length-1;t++){var r=e[t],n=e[t+1];r instanceof ei&&n instanceof ei&&$i(r,n)&&(r.text+=n.text,r.height=Math.max(r.height,n.height),r.depth=Math.max(r.depth,n.depth),r.italic=n.italic,e.splice(t+1,1),t--)}return e}},to={number:3,unit:"mu"},ro={number:4,unit:"mu"},no={number:5,unit:"mu"},ao={mord:{mop:to,mbin:ro,mrel:no,minner:to},mop:{mord:to,mop:to,mrel:no,minner:to},mbin:{mord:ro,mop:ro,mopen:ro,minner:ro},mrel:{mord:no,mop:no,mopen:no,minner:no},mopen:{},mclose:{mop:to,mbin:ro,mrel:no,minner:to},mpunct:{mord:to,mop:to,mrel:no,mopen:to,mclose:to,mpunct:to,minner:to},minner:{mord:to,mop:to,mbin:ro,mrel:no,mopen:to,mpunct:to,minner:to}},io={mord:{mop:to},mop:{mord:to,mop:to},mbin:{},mrel:{},mopen:{},mclose:{mop:to},mpunct:{},minner:{mop:to}},oo={},so={},lo={};function co(e){for(var{type:t,names:r,props:n,handler:a,htmlBuilder:i,mathmlBuilder:o}=e,s={type:t,numArgs:n.numArgs,argTypes:n.argTypes,allowedInArgument:!!n.allowedInArgument,allowedInText:!!n.allowedInText,allowedInMath:void 0===n.allowedInMath||n.allowedInMath,numOptionalArgs:n.numOptionalArgs||0,infix:!!n.infix,primitive:!!n.primitive,handler:a},l=0;l<r.length;++l)oo[r[l]]=s;t&&(i&&(so[t]=i),o&&(lo[t]=o))}function uo(e){var{type:t,htmlBuilder:r,mathmlBuilder:n}=e;co({type:t,names:[],props:{numArgs:0},handler(){throw new Error("Should never be called.")},htmlBuilder:r,mathmlBuilder:n})}var po=function(e){return"ordgroup"===e.type&&1===e.body.length?e.body[0]:e},_o=function(e){return"ordgroup"===e.type?e.body:[e]},mo=eo.makeSpan,go=["leftmost","mbin","mopen","mrel","mop","mpunct"],ho=["rightmost","mrel","mclose","mpunct"],fo={display:Ca.DISPLAY,text:Ca.TEXT,script:Ca.SCRIPT,scriptscript:Ca.SCRIPTSCRIPT},Eo={mord:"mord",mop:"mop",mbin:"mbin",mrel:"mrel",mopen:"mopen",mclose:"mclose",mpunct:"mpunct",minner:"minner"},bo=function(e,t,r,n){void 0===n&&(n=[null,null]);for(var a=[],i=0;i<e.length;i++){var o=No(e[i],t);if(o instanceof xa){var s=o.children;a.push(...s)}else a.push(o)}if(eo.tryCombineChars(a),!r)return a;var l=t;if(1===e.length){var c=e[0];"sizing"===c.type?l=t.havingSize(c.size):"styling"===c.type&&(l=t.havingStyle(fo[c.style]))}var d=mo([n[0]||"leftmost"],[],t),u=mo([n[1]||"rightmost"],[],t),p="root"===r;return So(a,(e,t)=>{var r=t.classes[0],n=e.classes[0];"mbin"===r&&ho.includes(n)?t.classes[0]="mord":"mbin"===n&&go.includes(r)&&(e.classes[0]="mord")},{node:d},u,p),So(a,(e,t)=>{var r=yo(t),n=yo(e),a=r&&n?e.hasClass("mtight")?io[r][n]:ao[r][n]:null;if(a)return eo.makeGlue(a,l)},{node:d},u,p),a},So=function e(t,r,n,a,i){a&&t.push(a);for(var o=0;o<t.length;o++){var s=t[o],l=vo(s);if(l)e(l.children,r,n,null,i);else{var c=!s.hasClass("mspace");if(c){var d=r(s,n.node);d&&(n.insertAfter?n.insertAfter(d):(t.unshift(d),o++))}c?n.node=s:i&&s.hasClass("newline")&&(n.node=mo(["leftmost"])),n.insertAfter=(e=>r=>{t.splice(e+1,0,r),o++})(o)}}a&&t.pop()},vo=function(e){return e instanceof xa||e instanceof Xa||e instanceof Ka&&e.hasClass("enclosing")?e:null},To=function e(t,r){var n=vo(t);if(n){var a=n.children;if(a.length){if("right"===r)return e(a[a.length-1],"right");if("left"===r)return e(a[0],"left")}}return t},yo=function(e,t){return e?(t&&(e=To(e,t)),Eo[e.classes[0]]||null):null},Co=function(e,t){var r=["nulldelimiter"].concat(e.baseSizingClasses());return mo(t.concat(r))},No=function(e,t,r){if(!e)return mo();if(so[e.type]){var n=so[e.type](e,t);if(r&&t.size!==r.size){n=mo(t.sizingClasses(r),[n],t);var a=t.sizeMultiplier/r.sizeMultiplier;n.height*=a,n.depth*=a}return n}throw new sa("Got group of unknown type: '"+e.type+"'")};function Ro(e,t){var r=mo(["base"],e,t),n=mo(["strut"]);return n.style.height=Ha(r.height+r.depth),r.depth&&(n.style.verticalAlign=Ha(-r.depth)),r.children.unshift(n),r}function Ao(e,t){var r=null;1===e.length&&"tag"===e[0].type&&(r=e[0].tag,e=e[0].body);var n,a=bo(e,t,"root");2===a.length&&a[1].hasClass("tag")&&(n=a.pop());for(var i,o=[],s=[],l=0;l<a.length;l++)if(s.push(a[l]),a[l].hasClass("mbin")||a[l].hasClass("mrel")||a[l].hasClass("allowbreak")){for(var c=!1;l<a.length-1&&a[l+1].hasClass("mspace")&&!a[l+1].hasClass("newline");)l++,s.push(a[l]),a[l].hasClass("nobreak")&&(c=!0);c||(o.push(Ro(s,t)),s=[])}else a[l].hasClass("newline")&&(s.pop(),s.length>0&&(o.push(Ro(s,t)),s=[]),o.push(a[l]));s.length>0&&o.push(Ro(s,t)),r?((i=Ro(bo(r,t,!0))).classes=["tag"],o.push(i)):n&&o.push(n);var d=mo(["katex-html"],o);if(d.setAttribute("aria-hidden","true"),i){var u=i.children[0];u.style.height=Ha(d.height+d.depth),d.depth&&(u.style.verticalAlign=Ha(-d.depth))}return d}function Oo(e){return new xa(e)}class Io{constructor(e,t,r){this.type=void 0,this.attributes=void 0,this.children=void 0,this.classes=void 0,this.type=e,this.attributes={},this.children=t||[],this.classes=r||[]}setAttribute(e,t){this.attributes[e]=t}getAttribute(e){return this.attributes[e]}toNode(){var e=document.createElementNS("http://www.w3.org/1998/Math/MathML",this.type);for(var t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&e.setAttribute(t,this.attributes[t]);this.classes.length>0&&(e.className=Va(this.classes));for(var r=0;r<this.children.length;r++)if(this.children[r]instanceof xo&&this.children[r+1]instanceof xo){for(var n=this.children[r].toText()+this.children[++r].toText();this.children[r+1]instanceof xo;)n+=this.children[++r].toText();e.appendChild(new xo(n).toNode())}else e.appendChild(this.children[r].toNode());return e}toMarkup(){var e="<"+this.type;for(var t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&(e+=" "+t+'="',e+=pa.escape(this.attributes[t]),e+='"');this.classes.length>0&&(e+=' class ="'+pa.escape(Va(this.classes))+'"'),e+=">";for(var r=0;r<this.children.length;r++)e+=this.children[r].toMarkup();return e+="</"+this.type+">"}toText(){return this.children.map(e=>e.toText()).join("")}}class xo{constructor(e){this.text=void 0,this.text=e}toNode(){return document.createTextNode(this.text)}toMarkup(){return pa.escape(this.toText())}toText(){return this.text}}var wo={MathNode:Io,TextNode:xo,SpaceNode:class{constructor(e){this.width=void 0,this.character=void 0,this.width=e,this.character=e>=.05555&&e<=.05556?" ":e>=.1666&&e<=.1667?" ":e>=.2222&&e<=.2223?" ":e>=.2777&&e<=.2778?"  ":e>=-.05556&&e<=-.05555?" ⁣":e>=-.1667&&e<=-.1666?" ⁣":e>=-.2223&&e<=-.2222?" ⁣":e>=-.2778&&e<=-.2777?" ⁣":null}toNode(){if(this.character)return document.createTextNode(this.character);var e=document.createElementNS("http://www.w3.org/1998/Math/MathML","mspace");return e.setAttribute("width",Ha(this.width)),e}toMarkup(){return this.character?"<mtext>"+this.character+"</mtext>":'<mspace width="'+Ha(this.width)+'"/>'}toText(){return this.character?this.character:" "}},newDocumentFragment:Oo},Do=function(e,t,r){return!si[t][e]||!si[t][e].replace||55349===e.charCodeAt(0)||Ci.hasOwnProperty(e)&&r&&(r.fontFamily&&"tt"===r.fontFamily.slice(4,6)||r.font&&"tt"===r.font.slice(4,6))||(e=si[t][e].replace),new wo.TextNode(e)},Mo=function(e){return 1===e.length?e[0]:new wo.MathNode("mrow",e)},ko=function(e,t){if("texttt"===t.fontFamily)return"monospace";if("textsf"===t.fontFamily)return"textit"===t.fontShape&&"textbf"===t.fontWeight?"sans-serif-bold-italic":"textit"===t.fontShape?"sans-serif-italic":"textbf"===t.fontWeight?"bold-sans-serif":"sans-serif";if("textit"===t.fontShape&&"textbf"===t.fontWeight)return"bold-italic";if("textit"===t.fontShape)return"italic";if("textbf"===t.fontWeight)return"bold";var r=t.font;if(!r||"mathnormal"===r)return null;var n=e.mode;if("mathit"===r)return"italic";if("boldsymbol"===r)return"textord"===e.type?"bold":"bold-italic";if("mathbf"===r)return"bold";if("mathbb"===r)return"double-struck";if("mathsfit"===r)return"sans-serif-italic";if("mathfrak"===r)return"fraktur";if("mathscr"===r||"mathcal"===r)return"script";if("mathsf"===r)return"sans-serif";if("mathtt"===r)return"monospace";var a=e.text;return["\\imath","\\jmath"].includes(a)?null:(si[n][a]&&si[n][a].replace&&(a=si[n][a].replace),ka(a,eo.fontMap[r].fontName,n)?eo.fontMap[r].variant:null)};function Lo(e){if(!e)return!1;if("mi"===e.type&&1===e.children.length){var t=e.children[0];return t instanceof xo&&"."===t.text}if("mo"===e.type&&1===e.children.length&&"true"===e.getAttribute("separator")&&"0em"===e.getAttribute("lspace")&&"0em"===e.getAttribute("rspace")){var r=e.children[0];return r instanceof xo&&","===r.text}return!1}var Po=function(e,t,r){if(1===e.length){var n=Bo(e[0],t);return r&&n instanceof Io&&"mo"===n.type&&(n.setAttribute("lspace","0em"),n.setAttribute("rspace","0em")),[n]}for(var a,i=[],o=0;o<e.length;o++){var s=Bo(e[o],t);if(s instanceof Io&&a instanceof Io){if("mtext"===s.type&&"mtext"===a.type&&s.getAttribute("mathvariant")===a.getAttribute("mathvariant")){a.children.push(...s.children);continue}if("mn"===s.type&&"mn"===a.type){a.children.push(...s.children);continue}if(Lo(s)&&"mn"===a.type){a.children.push(...s.children);continue}if("mn"===s.type&&Lo(a))s.children=[...a.children,...s.children],i.pop();else if(("msup"===s.type||"msub"===s.type)&&s.children.length>=1&&("mn"===a.type||Lo(a))){var l=s.children[0];l instanceof Io&&"mn"===l.type&&(l.children=[...a.children,...l.children],i.pop())}else if("mi"===a.type&&1===a.children.length){var c=a.children[0];if(c instanceof xo&&"̸"===c.text&&("mo"===s.type||"mi"===s.type||"mn"===s.type)){var d=s.children[0];d instanceof xo&&d.text.length>0&&(d.text=d.text.slice(0,1)+"̸"+d.text.slice(1),i.pop())}}}i.push(s),a=s}return i},Fo=function(e,t,r){return Mo(Po(e,t,r))},Bo=function(e,t){if(!e)return new wo.MathNode("mrow");if(lo[e.type])return lo[e.type](e,t);throw new sa("Got group of unknown type: '"+e.type+"'")};function Uo(e,t,r,n,a){var i,o=Po(e,r);i=1===o.length&&o[0]instanceof Io&&["mrow","mtable"].includes(o[0].type)?o[0]:new wo.MathNode("mrow",o);var s=new wo.MathNode("annotation",[new wo.TextNode(t)]);s.setAttribute("encoding","application/x-tex");var l=new wo.MathNode("semantics",[i,s]),c=new wo.MathNode("math",[l]);c.setAttribute("xmlns","http://www.w3.org/1998/Math/MathML"),n&&c.setAttribute("display","block");var d=a?"katex":"katex-mathml";return eo.makeSpan([d],[c])}var Go=function(e){return new Ua({style:e.displayMode?Ca.DISPLAY:Ca.TEXT,maxSize:e.maxSize,minRuleThickness:e.minRuleThickness})},zo=function(e,t){if(t.displayMode){var r=["katex-display"];t.leqno&&r.push("leqno"),t.fleqn&&r.push("fleqn"),e=eo.makeSpan(r,[e])}return e},Yo={widehat:"^",widecheck:"ˇ",widetilde:"~",utilde:"~",overleftarrow:"←",underleftarrow:"←",xleftarrow:"←",overrightarrow:"→",underrightarrow:"→",xrightarrow:"→",underbrace:"⏟",overbrace:"⏞",overgroup:"⏠",undergroup:"⏡",overleftrightarrow:"↔",underleftrightarrow:"↔",xleftrightarrow:"↔",Overrightarrow:"⇒",xRightarrow:"⇒",overleftharpoon:"↼",xleftharpoonup:"↼",overrightharpoon:"⇀",xrightharpoonup:"⇀",xLeftarrow:"⇐",xLeftrightarrow:"⇔",xhookleftarrow:"↩",xhookrightarrow:"↪",xmapsto:"↦",xrightharpoondown:"⇁",xleftharpoondown:"↽",xrightleftharpoons:"⇌",xleftrightharpoons:"⇋",xtwoheadleftarrow:"↞",xtwoheadrightarrow:"↠",xlongequal:"=",xtofrom:"⇄",xrightleftarrows:"⇄",xrightequilibrium:"⇌",xleftequilibrium:"⇋","\\cdrightarrow":"→","\\cdleftarrow":"←","\\cdlongequal":"="},qo={overrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],overleftarrow:[["leftarrow"],.888,522,"xMinYMin"],underrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],underleftarrow:[["leftarrow"],.888,522,"xMinYMin"],xrightarrow:[["rightarrow"],1.469,522,"xMaxYMin"],"\\cdrightarrow":[["rightarrow"],3,522,"xMaxYMin"],xleftarrow:[["leftarrow"],1.469,522,"xMinYMin"],"\\cdleftarrow":[["leftarrow"],3,522,"xMinYMin"],Overrightarrow:[["doublerightarrow"],.888,560,"xMaxYMin"],xRightarrow:[["doublerightarrow"],1.526,560,"xMaxYMin"],xLeftarrow:[["doubleleftarrow"],1.526,560,"xMinYMin"],overleftharpoon:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoonup:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoondown:[["leftharpoondown"],.888,522,"xMinYMin"],overrightharpoon:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoonup:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoondown:[["rightharpoondown"],.888,522,"xMaxYMin"],xlongequal:[["longequal"],.888,334,"xMinYMin"],"\\cdlongequal":[["longequal"],3,334,"xMinYMin"],xtwoheadleftarrow:[["twoheadleftarrow"],.888,334,"xMinYMin"],xtwoheadrightarrow:[["twoheadrightarrow"],.888,334,"xMaxYMin"],overleftrightarrow:[["leftarrow","rightarrow"],.888,522],overbrace:[["leftbrace","midbrace","rightbrace"],1.6,548],underbrace:[["leftbraceunder","midbraceunder","rightbraceunder"],1.6,548],underleftrightarrow:[["leftarrow","rightarrow"],.888,522],xleftrightarrow:[["leftarrow","rightarrow"],1.75,522],xLeftrightarrow:[["doubleleftarrow","doublerightarrow"],1.75,560],xrightleftharpoons:[["leftharpoondownplus","rightharpoonplus"],1.75,716],xleftrightharpoons:[["leftharpoonplus","rightharpoondownplus"],1.75,716],xhookleftarrow:[["leftarrow","righthook"],1.08,522],xhookrightarrow:[["lefthook","rightarrow"],1.08,522],overlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],underlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],overgroup:[["leftgroup","rightgroup"],.888,342],undergroup:[["leftgroupunder","rightgroupunder"],.888,342],xmapsto:[["leftmapsto","rightarrow"],1.5,522],xtofrom:[["leftToFrom","rightToFrom"],1.75,528],xrightleftarrows:[["baraboveleftarrow","rightarrowabovebar"],1.75,901],xrightequilibrium:[["baraboveshortleftharpoon","rightharpoonaboveshortbar"],1.75,716],xleftequilibrium:[["shortbaraboveleftharpoon","shortrightharpoonabovebar"],1.75,716]},Ho=function(e,t,r,n,a){var i,o=e.height+e.depth+r+n;if(/fbox|color|angl/.test(t)){if(i=eo.makeSpan(["stretchy",t],[],a),"fbox"===t){var s=a.color&&a.getColor();s&&(i.style.borderColor=s)}}else{var l=[];/^[bx]cancel$/.test(t)&&l.push(new ni({x1:"0",y1:"0",x2:"100%",y2:"100%","stroke-width":"0.046em"})),/^x?cancel$/.test(t)&&l.push(new ni({x1:"0",y1:"100%",x2:"100%",y2:"0","stroke-width":"0.046em"}));var c=new ti(l,{width:"100%",height:Ha(o)});i=eo.makeSvgSpan([],[c],a)}return i.height=o,i.style.height=Ha(o),i},Vo=function(e){var t=new wo.MathNode("mo",[new wo.TextNode(Yo[e.replace(/^\\/,"")])]);return t.setAttribute("stretchy","true"),t},$o=function(e,t){var{span:r,minWidth:n,height:a}=function(){var r=4e5,n=e.label.slice(1);if(["widehat","widecheck","widetilde","utilde"].includes(n)){var a,i,o,s="ordgroup"===(_=e.base).type?_.body.length:1;if(s>5)"widehat"===n||"widecheck"===n?(a=420,r=2364,o=.42,i=n+"4"):(a=312,r=2340,o=.34,i="tilde4");else{var l=[1,1,2,2,3,3][s];"widehat"===n||"widecheck"===n?(r=[0,1062,2364,2364,2364][l],a=[0,239,300,360,420][l],o=[0,.24,.3,.3,.36,.42][l],i=n+l):(r=[0,600,1033,2339,2340][l],a=[0,260,286,306,312][l],o=[0,.26,.286,.3,.306,.34][l],i="tilde"+l)}var c=new ri(i),d=new ti([c],{width:"100%",height:Ha(o),viewBox:"0 0 "+r+" "+a,preserveAspectRatio:"none"});return{span:eo.makeSvgSpan([],[d],t),minWidth:0,height:o}}var u,p,_,m=[],g=qo[n],[h,f,E]=g,b=E/1e3,S=h.length;if(1===S)u=["hide-tail"],p=[g[3]];else if(2===S)u=["halfarrow-left","halfarrow-right"],p=["xMinYMin","xMaxYMin"];else{if(3!==S)throw new Error("Correct katexImagesData or update code here to support\n "+S+" children.");u=["brace-left","brace-center","brace-right"],p=["xMinYMin","xMidYMin","xMaxYMin"]}for(var v=0;v<S;v++){var T=new ri(h[v]),y=new ti([T],{width:"400em",height:Ha(b),viewBox:"0 0 "+r+" "+E,preserveAspectRatio:p[v]+" slice"}),C=eo.makeSvgSpan([u[v]],[y],t);if(1===S)return{span:C,minWidth:f,height:b};C.style.height=Ha(b),m.push(C)}return{span:eo.makeSpan(["stretchy"],m,t),minWidth:f,height:b}}();return r.height=a,r.style.height=Ha(a),n>0&&(r.style.minWidth=Ha(n)),r};function Wo(e,t){if(!e||e.type!==t)throw new Error("Expected node of type "+t+", but got "+(e?"node of type "+e.type:String(e)));return e}function jo(e){var t=Qo(e);if(!t)throw new Error("Expected node of symbol group type, but got "+(e?"node of type "+e.type:String(e)));return t}function Qo(e){return e&&("atom"===e.type||oi.hasOwnProperty(e.type))?e:null}var Ko=(e,t)=>{var r,n,a;e&&"supsub"===e.type?(r=(n=Wo(e.base,"accent")).base,e.base=r,a=function(e){if(e instanceof Ka)return e;throw new Error("Expected span<HtmlDomNode> but got "+String(e)+".")}(No(e,t)),e.base=n):r=(n=Wo(e,"accent")).base;var i=No(r,t.havingCrampedStyle()),o=0;if(n.isShifty&&pa.isCharacterBox(r)){var s=pa.getBaseElem(r);o=ai(No(s,t.havingCrampedStyle())).skew}var l,c="\\c"===n.label,d=c?i.height+i.depth:Math.min(i.height,t.fontMetrics().xHeight);if(n.isStretchy)l=$o(n,t),l=eo.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:i},{type:"elem",elem:l,wrapperClasses:["svg-align"],wrapperStyle:o>0?{width:"calc(100% - "+Ha(2*o)+")",marginLeft:Ha(2*o)}:void 0}]},t);else{var u,p;"\\vec"===n.label?(u=eo.staticSvg("vec",t),p=eo.svgData.vec[1]):((u=ai(u=eo.makeOrd({mode:n.mode,text:n.label},t,"textord"))).italic=0,p=u.width,c&&(d+=u.depth)),l=eo.makeSpan(["accent-body"],[u]);var _="\\textcircled"===n.label;_&&(l.classes.push("accent-full"),d=i.height);var m=o;_||(m-=p/2),l.style.left=Ha(m),"\\textcircled"===n.label&&(l.style.top=".2em"),l=eo.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:i},{type:"kern",size:-d},{type:"elem",elem:l}]},t)}var g=eo.makeSpan(["mord","accent"],[l],t);return a?(a.children[0]=g,a.height=Math.max(g.height,a.height),a.classes[0]="mord",a):g},Xo=(e,t)=>{var r=e.isStretchy?Vo(e.label):new wo.MathNode("mo",[Do(e.label,e.mode)]),n=new wo.MathNode("mover",[Bo(e.base,t),r]);return n.setAttribute("accent","true"),n},Zo=new RegExp(["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring"].map(e=>"\\"+e).join("|"));co({type:"accent",names:["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring","\\widecheck","\\widehat","\\widetilde","\\overrightarrow","\\overleftarrow","\\Overrightarrow","\\overleftrightarrow","\\overgroup","\\overlinesegment","\\overleftharpoon","\\overrightharpoon"],props:{numArgs:1},handler:(e,t)=>{var r=po(t[0]),n=!Zo.test(e.funcName),a=!n||"\\widehat"===e.funcName||"\\widetilde"===e.funcName||"\\widecheck"===e.funcName;return{type:"accent",mode:e.parser.mode,label:e.funcName,isStretchy:n,isShifty:a,base:r}},htmlBuilder:Ko,mathmlBuilder:Xo}),co({type:"accent",names:["\\'","\\`","\\^","\\~","\\=","\\u","\\.",'\\"',"\\c","\\r","\\H","\\v","\\textcircled"],props:{numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["primitive"]},handler:(e,t)=>{var r=t[0],n=e.parser.mode;return"math"===n&&(e.parser.settings.reportNonstrict("mathVsTextAccents","LaTeX's accent "+e.funcName+" works only in text mode"),n="text"),{type:"accent",mode:n,label:e.funcName,isStretchy:!1,isShifty:!0,base:r}},htmlBuilder:Ko,mathmlBuilder:Xo}),co({type:"accentUnder",names:["\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\undergroup","\\underlinesegment","\\utilde"],props:{numArgs:1},handler:(e,t)=>{var{parser:r,funcName:n}=e,a=t[0];return{type:"accentUnder",mode:r.mode,label:n,base:a}},htmlBuilder:(e,t)=>{var r=No(e.base,t),n=$o(e,t),a="\\utilde"===e.label?.12:0,i=eo.makeVList({positionType:"top",positionData:r.height,children:[{type:"elem",elem:n,wrapperClasses:["svg-align"]},{type:"kern",size:a},{type:"elem",elem:r}]},t);return eo.makeSpan(["mord","accentunder"],[i],t)},mathmlBuilder:(e,t)=>{var r=Vo(e.label),n=new wo.MathNode("munder",[Bo(e.base,t),r]);return n.setAttribute("accentunder","true"),n}});var Jo=e=>{var t=new wo.MathNode("mpadded",e?[e]:[]);return t.setAttribute("width","+0.6em"),t.setAttribute("lspace","0.3em"),t};co({type:"xArrow",names:["\\xleftarrow","\\xrightarrow","\\xLeftarrow","\\xRightarrow","\\xleftrightarrow","\\xLeftrightarrow","\\xhookleftarrow","\\xhookrightarrow","\\xmapsto","\\xrightharpoondown","\\xrightharpoonup","\\xleftharpoondown","\\xleftharpoonup","\\xrightleftharpoons","\\xleftrightharpoons","\\xlongequal","\\xtwoheadrightarrow","\\xtwoheadleftarrow","\\xtofrom","\\xrightleftarrows","\\xrightequilibrium","\\xleftequilibrium","\\\\cdrightarrow","\\\\cdleftarrow","\\\\cdlongequal"],props:{numArgs:1,numOptionalArgs:1},handler(e,t,r){var{parser:n,funcName:a}=e;return{type:"xArrow",mode:n.mode,label:a,body:t[0],below:r[0]}},htmlBuilder(e,t){var r,n=t.style,a=t.havingStyle(n.sup()),i=eo.wrapFragment(No(e.body,a,t),t),o="\\x"===e.label.slice(0,2)?"x":"cd";i.classes.push(o+"-arrow-pad"),e.below&&(a=t.havingStyle(n.sub()),(r=eo.wrapFragment(No(e.below,a,t),t)).classes.push(o+"-arrow-pad"));var s,l=$o(e,t),c=-t.fontMetrics().axisHeight+.5*l.height,d=-t.fontMetrics().axisHeight-.5*l.height-.111;if((i.depth>.25||"\\xleftequilibrium"===e.label)&&(d-=i.depth),r){var u=-t.fontMetrics().axisHeight+r.height+.5*l.height+.111;s=eo.makeVList({positionType:"individualShift",children:[{type:"elem",elem:i,shift:d},{type:"elem",elem:l,shift:c},{type:"elem",elem:r,shift:u}]},t)}else s=eo.makeVList({positionType:"individualShift",children:[{type:"elem",elem:i,shift:d},{type:"elem",elem:l,shift:c}]},t);return s.children[0].children[0].children[1].classes.push("svg-align"),eo.makeSpan(["mrel","x-arrow"],[s],t)},mathmlBuilder(e,t){var r,n=Vo(e.label);if(n.setAttribute("minsize","x"===e.label.charAt(0)?"1.75em":"3.0em"),e.body){var a=Jo(Bo(e.body,t));if(e.below){var i=Jo(Bo(e.below,t));r=new wo.MathNode("munderover",[n,i,a])}else r=new wo.MathNode("mover",[n,a])}else if(e.below){var o=Jo(Bo(e.below,t));r=new wo.MathNode("munder",[n,o])}else r=Jo(),r=new wo.MathNode("mover",[n,r]);return r}});var es=eo.makeSpan;function ts(e,t){var r=bo(e.body,t,!0);return es([e.mclass],r,t)}function rs(e,t){var r,n=Po(e.body,t);return"minner"===e.mclass?r=new wo.MathNode("mpadded",n):"mord"===e.mclass?e.isCharacterBox?(r=n[0]).type="mi":r=new wo.MathNode("mi",n):(e.isCharacterBox?(r=n[0]).type="mo":r=new wo.MathNode("mo",n),"mbin"===e.mclass?(r.attributes.lspace="0.22em",r.attributes.rspace="0.22em"):"mpunct"===e.mclass?(r.attributes.lspace="0em",r.attributes.rspace="0.17em"):"mopen"===e.mclass||"mclose"===e.mclass?(r.attributes.lspace="0em",r.attributes.rspace="0em"):"minner"===e.mclass&&(r.attributes.lspace="0.0556em",r.attributes.width="+0.1111em")),r}co({type:"mclass",names:["\\mathord","\\mathbin","\\mathrel","\\mathopen","\\mathclose","\\mathpunct","\\mathinner"],props:{numArgs:1,primitive:!0},handler(e,t){var{parser:r,funcName:n}=e,a=t[0];return{type:"mclass",mode:r.mode,mclass:"m"+n.slice(5),body:_o(a),isCharacterBox:pa.isCharacterBox(a)}},htmlBuilder:ts,mathmlBuilder:rs});var ns=e=>{var t="ordgroup"===e.type&&e.body.length?e.body[0]:e;return"atom"!==t.type||"bin"!==t.family&&"rel"!==t.family?"mord":"m"+t.family};co({type:"mclass",names:["\\@binrel"],props:{numArgs:2},handler(e,t){var{parser:r}=e;return{type:"mclass",mode:r.mode,mclass:ns(t[0]),body:_o(t[1]),isCharacterBox:pa.isCharacterBox(t[1])}}}),co({type:"mclass",names:["\\stackrel","\\overset","\\underset"],props:{numArgs:2},handler(e,t){var r,{parser:n,funcName:a}=e,i=t[1],o=t[0];r="\\stackrel"!==a?ns(i):"mrel";var s={type:"op",mode:i.mode,limits:!0,alwaysHandleSupSub:!0,parentIsSupSub:!1,symbol:!1,suppressBaseShift:"\\stackrel"!==a,body:_o(i)},l={type:"supsub",mode:o.mode,base:s,sup:"\\underset"===a?null:o,sub:"\\underset"===a?o:null};return{type:"mclass",mode:n.mode,mclass:r,body:[l],isCharacterBox:pa.isCharacterBox(l)}},htmlBuilder:ts,mathmlBuilder:rs}),co({type:"pmb",names:["\\pmb"],props:{numArgs:1,allowedInText:!0},handler(e,t){var{parser:r}=e;return{type:"pmb",mode:r.mode,mclass:ns(t[0]),body:_o(t[0])}},htmlBuilder(e,t){var r=bo(e.body,t,!0),n=eo.makeSpan([e.mclass],r,t);return n.style.textShadow="0.02em 0.01em 0.04px",n},mathmlBuilder(e,t){var r=Po(e.body,t),n=new wo.MathNode("mstyle",r);return n.setAttribute("style","text-shadow: 0.02em 0.01em 0.04px"),n}});var as={">":"\\\\cdrightarrow","<":"\\\\cdleftarrow","=":"\\\\cdlongequal",A:"\\uparrow",V:"\\downarrow","|":"\\Vert",".":"no arrow"},is=()=>({type:"styling",body:[],mode:"math",style:"display"}),os=e=>"textord"===e.type&&"@"===e.text,ss=(e,t)=>("mathord"===e.type||"atom"===e.type)&&e.text===t;function ls(e,t,r){var n=as[e];switch(n){case"\\\\cdrightarrow":case"\\\\cdleftarrow":return r.callFunction(n,[t[0]],[t[1]]);case"\\uparrow":case"\\downarrow":var a={type:"atom",text:n,mode:"math",family:"rel"},i={type:"ordgroup",mode:"math",body:[r.callFunction("\\\\cdleft",[t[0]],[]),r.callFunction("\\Big",[a],[]),r.callFunction("\\\\cdright",[t[1]],[])]};return r.callFunction("\\\\cdparent",[i],[]);case"\\\\cdlongequal":return r.callFunction("\\\\cdlongequal",[],[]);case"\\Vert":return r.callFunction("\\Big",[{type:"textord",text:"\\Vert",mode:"math"}],[]);default:return{type:"textord",text:" ",mode:"math"}}}co({type:"cdlabel",names:["\\\\cdleft","\\\\cdright"],props:{numArgs:1},handler(e,t){var{parser:r,funcName:n}=e;return{type:"cdlabel",mode:r.mode,side:n.slice(4),label:t[0]}},htmlBuilder(e,t){var r=t.havingStyle(t.style.sup()),n=eo.wrapFragment(No(e.label,r,t),t);return n.classes.push("cd-label-"+e.side),n.style.bottom=Ha(.8-n.depth),n.height=0,n.depth=0,n},mathmlBuilder(e,t){var r=new wo.MathNode("mrow",[Bo(e.label,t)]);return(r=new wo.MathNode("mpadded",[r])).setAttribute("width","0"),"left"===e.side&&r.setAttribute("lspace","-1width"),r.setAttribute("voffset","0.7em"),(r=new wo.MathNode("mstyle",[r])).setAttribute("displaystyle","false"),r.setAttribute("scriptlevel","1"),r}}),co({type:"cdlabelparent",names:["\\\\cdparent"],props:{numArgs:1},handler(e,t){var{parser:r}=e;return{type:"cdlabelparent",mode:r.mode,fragment:t[0]}},htmlBuilder(e,t){var r=eo.wrapFragment(No(e.fragment,t),t);return r.classes.push("cd-vert-arrow"),r},mathmlBuilder:(e,t)=>new wo.MathNode("mrow",[Bo(e.fragment,t)])}),co({type:"textord",names:["\\@char"],props:{numArgs:1,allowedInText:!0},handler(e,t){for(var{parser:r}=e,n=Wo(t[0],"ordgroup").body,a="",i=0;i<n.length;i++){a+=Wo(n[i],"textord").text}var o,s=parseInt(a);if(isNaN(s))throw new sa("\\@char has non-numeric argument "+a);if(s<0||s>=1114111)throw new sa("\\@char with invalid code point "+a);return s<=65535?o=String.fromCharCode(s):(s-=65536,o=String.fromCharCode(55296+(s>>10),56320+(1023&s))),{type:"textord",mode:r.mode,text:o}}});var cs=(e,t)=>{var r=bo(e.body,t.withColor(e.color),!1);return eo.makeFragment(r)},ds=(e,t)=>{var r=Po(e.body,t.withColor(e.color)),n=new wo.MathNode("mstyle",r);return n.setAttribute("mathcolor",e.color),n};co({type:"color",names:["\\textcolor"],props:{numArgs:2,allowedInText:!0,argTypes:["color","original"]},handler(e,t){var{parser:r}=e,n=Wo(t[0],"color-token").color,a=t[1];return{type:"color",mode:r.mode,color:n,body:_o(a)}},htmlBuilder:cs,mathmlBuilder:ds}),co({type:"color",names:["\\color"],props:{numArgs:1,allowedInText:!0,argTypes:["color"]},handler(e,t){var{parser:r,breakOnTokenText:n}=e,a=Wo(t[0],"color-token").color;r.gullet.macros.set("\\current@color",a);var i=r.parseExpression(!0,n);return{type:"color",mode:r.mode,color:a,body:i}},htmlBuilder:cs,mathmlBuilder:ds}),co({type:"cr",names:["\\\\"],props:{numArgs:0,numOptionalArgs:0,allowedInText:!0},handler(e,t,r){var{parser:n}=e,a="["===n.gullet.future().text?n.parseSizeGroup(!0):null,i=!n.settings.displayMode||!n.settings.useStrictBehavior("newLineInDisplayMode","In LaTeX, \\\\ or \\newline does nothing in display mode");return{type:"cr",mode:n.mode,newLine:i,size:a&&Wo(a,"size").value}},htmlBuilder(e,t){var r=eo.makeSpan(["mspace"],[],t);return e.newLine&&(r.classes.push("newline"),e.size&&(r.style.marginTop=Ha(qa(e.size,t)))),r},mathmlBuilder(e,t){var r=new wo.MathNode("mspace");return e.newLine&&(r.setAttribute("linebreak","newline"),e.size&&r.setAttribute("height",Ha(qa(e.size,t)))),r}});var us={"\\global":"\\global","\\long":"\\\\globallong","\\\\globallong":"\\\\globallong","\\def":"\\gdef","\\gdef":"\\gdef","\\edef":"\\xdef","\\xdef":"\\xdef","\\let":"\\\\globallet","\\futurelet":"\\\\globalfuture"},ps=e=>{var t=e.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(t))throw new sa("Expected a control sequence",e);return t},_s=(e,t,r,n)=>{var a=e.gullet.macros.get(r.text);null==a&&(r.noexpand=!0,a={tokens:[r],numArgs:0,unexpandable:!e.gullet.isExpandable(r.text)}),e.gullet.macros.set(t,a,n)};co({type:"internal",names:["\\global","\\long","\\\\globallong"],props:{numArgs:0,allowedInText:!0},handler(e){var{parser:t,funcName:r}=e;t.consumeSpaces();var n=t.fetch();if(us[n.text])return"\\global"!==r&&"\\\\globallong"!==r||(n.text=us[n.text]),Wo(t.parseFunction(),"internal");throw new sa("Invalid token after macro prefix",n)}}),co({type:"internal",names:["\\def","\\gdef","\\edef","\\xdef"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e){var{parser:t,funcName:r}=e,n=t.gullet.popToken(),a=n.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(a))throw new sa("Expected a control sequence",n);for(var i,o=0,s=[[]];"{"!==t.gullet.future().text;)if("#"===(n=t.gullet.popToken()).text){if("{"===t.gullet.future().text){i=t.gullet.future(),s[o].push("{");break}if(n=t.gullet.popToken(),!/^[1-9]$/.test(n.text))throw new sa('Invalid argument number "'+n.text+'"');if(parseInt(n.text)!==o+1)throw new sa('Argument number "'+n.text+'" out of order');o++,s.push([])}else{if("EOF"===n.text)throw new sa("Expected a macro definition");s[o].push(n.text)}var{tokens:l}=t.gullet.consumeArg();return i&&l.unshift(i),"\\edef"!==r&&"\\xdef"!==r||(l=t.gullet.expandTokens(l)).reverse(),t.gullet.macros.set(a,{tokens:l,numArgs:o,delimiters:s},r===us[r]),{type:"internal",mode:t.mode}}}),co({type:"internal",names:["\\let","\\\\globallet"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e){var{parser:t,funcName:r}=e,n=ps(t.gullet.popToken());t.gullet.consumeSpaces();var a=(e=>{var t=e.gullet.popToken();return"="===t.text&&" "===(t=e.gullet.popToken()).text&&(t=e.gullet.popToken()),t})(t);return _s(t,n,a,"\\\\globallet"===r),{type:"internal",mode:t.mode}}}),co({type:"internal",names:["\\futurelet","\\\\globalfuture"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e){var{parser:t,funcName:r}=e,n=ps(t.gullet.popToken()),a=t.gullet.popToken(),i=t.gullet.popToken();return _s(t,n,i,"\\\\globalfuture"===r),t.gullet.pushToken(i),t.gullet.pushToken(a),{type:"internal",mode:t.mode}}});var ms=function(e,t,r){var n=ka(si.math[e]&&si.math[e].replace||e,t,r);if(!n)throw new Error("Unsupported symbol "+e+" and font size "+t+".");return n},gs=function(e,t,r,n){var a=r.havingBaseStyle(t),i=eo.makeSpan(n.concat(a.sizingClasses(r)),[e],r),o=a.sizeMultiplier/r.sizeMultiplier;return i.height*=o,i.depth*=o,i.maxFontSize=a.sizeMultiplier,i},hs=function(e,t,r){var n=t.havingBaseStyle(r),a=(1-t.sizeMultiplier/n.sizeMultiplier)*t.fontMetrics().axisHeight;e.classes.push("delimcenter"),e.style.top=Ha(a),e.height-=a,e.depth+=a},fs=function(e,t,r,n,a,i){var o=function(e,t,r,n){return eo.makeSymbol(e,"Size"+t+"-Regular",r,n)}(e,t,a,n),s=gs(eo.makeSpan(["delimsizing","size"+t],[o],n),Ca.TEXT,n,i);return r&&hs(s,n,Ca.TEXT),s},Es=function(e,t,r){var n;return n="Size1-Regular"===t?"delim-size1":"delim-size4",{type:"elem",elem:eo.makeSpan(["delimsizinginner",n],[eo.makeSpan([],[eo.makeSymbol(e,t,r)])])}},bs=function(e,t,r){var n=wa["Size4-Regular"][e.charCodeAt(0)]?wa["Size4-Regular"][e.charCodeAt(0)][4]:wa["Size1-Regular"][e.charCodeAt(0)][4],a=new ri("inner",function(e,t){switch(e){case"⎜":return"M291 0 H417 V"+t+" H291z M291 0 H417 V"+t+" H291z";case"∣":return"M145 0 H188 V"+t+" H145z M145 0 H188 V"+t+" H145z";case"∥":return"M145 0 H188 V"+t+" H145z M145 0 H188 V"+t+" H145zM367 0 H410 V"+t+" H367z M367 0 H410 V"+t+" H367z";case"⎟":return"M457 0 H583 V"+t+" H457z M457 0 H583 V"+t+" H457z";case"⎢":return"M319 0 H403 V"+t+" H319z M319 0 H403 V"+t+" H319z";case"⎥":return"M263 0 H347 V"+t+" H263z M263 0 H347 V"+t+" H263z";case"⎪":return"M384 0 H504 V"+t+" H384z M384 0 H504 V"+t+" H384z";case"⏐":return"M312 0 H355 V"+t+" H312z M312 0 H355 V"+t+" H312z";case"‖":return"M257 0 H300 V"+t+" H257z M257 0 H300 V"+t+" H257zM478 0 H521 V"+t+" H478z M478 0 H521 V"+t+" H478z";default:return""}}(e,Math.round(1e3*t))),i=new ti([a],{width:Ha(n),height:Ha(t),style:"width:"+Ha(n),viewBox:"0 0 "+1e3*n+" "+Math.round(1e3*t),preserveAspectRatio:"xMinYMin"}),o=eo.makeSvgSpan([],[i],r);return o.height=t,o.style.height=Ha(t),o.style.width=Ha(n),{type:"elem",elem:o}},Ss={type:"kern",size:-.008},vs=["|","\\lvert","\\rvert","\\vert"],Ts=["\\|","\\lVert","\\rVert","\\Vert"],ys=function(e,t,r,n,a,i){var o,s,l,c,d="",u=0;o=l=c=e,s=null;var p="Size1-Regular";"\\uparrow"===e?l=c="⏐":"\\Uparrow"===e?l=c="‖":"\\downarrow"===e?o=l="⏐":"\\Downarrow"===e?o=l="‖":"\\updownarrow"===e?(o="\\uparrow",l="⏐",c="\\downarrow"):"\\Updownarrow"===e?(o="\\Uparrow",l="‖",c="\\Downarrow"):vs.includes(e)?(l="∣",d="vert",u=333):Ts.includes(e)?(l="∥",d="doublevert",u=556):"["===e||"\\lbrack"===e?(o="⎡",l="⎢",c="⎣",p="Size4-Regular",d="lbrack",u=667):"]"===e||"\\rbrack"===e?(o="⎤",l="⎥",c="⎦",p="Size4-Regular",d="rbrack",u=667):"\\lfloor"===e||"⌊"===e?(l=o="⎢",c="⎣",p="Size4-Regular",d="lfloor",u=667):"\\lceil"===e||"⌈"===e?(o="⎡",l=c="⎢",p="Size4-Regular",d="lceil",u=667):"\\rfloor"===e||"⌋"===e?(l=o="⎥",c="⎦",p="Size4-Regular",d="rfloor",u=667):"\\rceil"===e||"⌉"===e?(o="⎤",l=c="⎥",p="Size4-Regular",d="rceil",u=667):"("===e||"\\lparen"===e?(o="⎛",l="⎜",c="⎝",p="Size4-Regular",d="lparen",u=875):")"===e||"\\rparen"===e?(o="⎞",l="⎟",c="⎠",p="Size4-Regular",d="rparen",u=875):"\\{"===e||"\\lbrace"===e?(o="⎧",s="⎨",c="⎩",l="⎪",p="Size4-Regular"):"\\}"===e||"\\rbrace"===e?(o="⎫",s="⎬",c="⎭",l="⎪",p="Size4-Regular"):"\\lgroup"===e||"⟮"===e?(o="⎧",c="⎩",l="⎪",p="Size4-Regular"):"\\rgroup"===e||"⟯"===e?(o="⎫",c="⎭",l="⎪",p="Size4-Regular"):"\\lmoustache"===e||"⎰"===e?(o="⎧",c="⎭",l="⎪",p="Size4-Regular"):"\\rmoustache"!==e&&"⎱"!==e||(o="⎫",c="⎩",l="⎪",p="Size4-Regular");var _=ms(o,p,a),m=_.height+_.depth,g=ms(l,p,a),h=g.height+g.depth,f=ms(c,p,a),E=f.height+f.depth,b=0,S=1;if(null!==s){var v=ms(s,p,a);b=v.height+v.depth,S=2}var T=m+E+b,y=T+Math.max(0,Math.ceil((t-T)/(S*h)))*S*h,C=n.fontMetrics().axisHeight;r&&(C*=n.sizeMultiplier);var N=y/2-C,R=[];if(d.length>0){var A=y-m-E,O=Math.round(1e3*y),I=function(e,t){switch(e){case"lbrack":return"M403 1759 V84 H666 V0 H319 V1759 v"+t+" v1759 h347 v-84\nH403z M403 1759 V0 H319 V1759 v"+t+" v1759 h84z";case"rbrack":return"M347 1759 V0 H0 V84 H263 V1759 v"+t+" v1759 H0 v84 H347z\nM347 1759 V0 H263 V1759 v"+t+" v1759 h84z";case"vert":return"M145 15 v585 v"+t+" v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v"+-t+" v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v"+t+" v585 h43z";case"doublevert":return"M145 15 v585 v"+t+" v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v"+-t+" v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v"+t+" v585 h43z\nM367 15 v585 v"+t+" v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v"+-t+" v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M410 15 H367 v585 v"+t+" v585 h43z";case"lfloor":return"M319 602 V0 H403 V602 v"+t+" v1715 h263 v84 H319z\nMM319 602 V0 H403 V602 v"+t+" v1715 H319z";case"rfloor":return"M319 602 V0 H403 V602 v"+t+" v1799 H0 v-84 H319z\nMM319 602 V0 H403 V602 v"+t+" v1715 H319z";case"lceil":return"M403 1759 V84 H666 V0 H319 V1759 v"+t+" v602 h84z\nM403 1759 V0 H319 V1759 v"+t+" v602 h84z";case"rceil":return"M347 1759 V0 H0 V84 H263 V1759 v"+t+" v602 h84z\nM347 1759 V0 h-84 V1759 v"+t+" v602 h84z";case"lparen":return"M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1\nc-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349,\n-36,557 l0,"+(t+84)+"c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210,\n949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9\nc0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5,\n-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189\nl0,-"+(t+92)+"c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3,\n-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z";case"rparen":return"M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3,\n63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5\nc11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0,"+(t+9)+"\nc-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664\nc-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11\nc0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17\nc242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558\nl0,-"+(t+144)+"c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,\n-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z";default:throw new Error("Unknown stretchy delimiter.")}}(d,Math.round(1e3*A)),x=new ri(d,I),w=(u/1e3).toFixed(3)+"em",D=(O/1e3).toFixed(3)+"em",M=new ti([x],{width:w,height:D,viewBox:"0 0 "+u+" "+O}),k=eo.makeSvgSpan([],[M],n);k.height=O/1e3,k.style.width=w,k.style.height=D,R.push({type:"elem",elem:k})}else{if(R.push(Es(c,p,a)),R.push(Ss),null===s){var L=y-m-E+.016;R.push(bs(l,L,n))}else{var P=(y-m-E-b)/2+.016;R.push(bs(l,P,n)),R.push(Ss),R.push(Es(s,p,a)),R.push(Ss),R.push(bs(l,P,n))}R.push(Ss),R.push(Es(o,p,a))}var F=n.havingBaseStyle(Ca.TEXT),B=eo.makeVList({positionType:"bottom",positionData:N,children:R},F);return gs(eo.makeSpan(["delimsizing","mult"],[B],F),Ca.TEXT,n,i)},Cs=.08,Ns=function(e,t,r,n,a){var i=function(e,t,r){t*=1e3;var n="";switch(e){case"sqrtMain":n=function(e,t){return"M95,"+(622+e+t)+"\nc-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14\nc0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54\nc44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10\ns173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429\nc69,-144,104.5,-217.7,106.5,-221\nl"+e/2.075+" -"+e+"\nc5.3,-9.3,12,-14,20,-14\nH400000v"+(40+e)+"H845.2724\ns-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7\nc-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z\nM"+(834+e)+" "+t+"h400000v"+(40+e)+"h-400000z"}(t,Oa);break;case"sqrtSize1":n=function(e,t){return"M263,"+(601+e+t)+"c0.7,0,18,39.7,52,119\nc34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120\nc340,-704.7,510.7,-1060.3,512,-1067\nl"+e/2.084+" -"+e+"\nc4.7,-7.3,11,-11,19,-11\nH40000v"+(40+e)+"H1012.3\ns-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232\nc-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1\ns-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26\nc-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z\nM"+(1001+e)+" "+t+"h400000v"+(40+e)+"h-400000z"}(t,Oa);break;case"sqrtSize2":n=function(e,t){return"M983 "+(10+e+t)+"\nl"+e/3.13+" -"+e+"\nc4,-6.7,10,-10,18,-10 H400000v"+(40+e)+"\nH1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7\ns-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744\nc-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30\nc26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722\nc56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5\nc53.7,-170.3,84.5,-266.8,92.5,-289.5z\nM"+(1001+e)+" "+t+"h400000v"+(40+e)+"h-400000z"}(t,Oa);break;case"sqrtSize3":n=function(e,t){return"M424,"+(2398+e+t)+"\nc-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514\nc0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20\ns-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121\ns209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081\nl"+e/4.223+" -"+e+"c4,-6.7,10,-10,18,-10 H400000\nv"+(40+e)+"H1014.6\ns-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185\nc-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2z M"+(1001+e)+" "+t+"\nh400000v"+(40+e)+"h-400000z"}(t,Oa);break;case"sqrtSize4":n=function(e,t){return"M473,"+(2713+e+t)+"\nc339.3,-1799.3,509.3,-2700,510,-2702 l"+e/5.298+" -"+e+"\nc3.3,-7.3,9.3,-11,18,-11 H400000v"+(40+e)+"H1017.7\ns-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200\nc0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26\ns76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,\n606zM"+(1001+e)+" "+t+"h400000v"+(40+e)+"H1017.7z"}(t,Oa);break;case"sqrtTall":n=function(e,t,r){return"M702 "+(e+t)+"H400000"+(40+e)+"\nH742v"+(r-54-t-e)+"l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1\nh-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170\nc-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667\n219 661 l218 661zM702 "+t+"H400000v"+(40+e)+"H742z"}(t,Oa,r)}return n}(e,n,r),o=new ri(e,i),s=new ti([o],{width:"400em",height:Ha(t),viewBox:"0 0 400000 "+r,preserveAspectRatio:"xMinYMin slice"});return eo.makeSvgSpan(["hide-tail"],[s],a)},Rs=["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","⌊","⌋","\\lceil","\\rceil","⌈","⌉","\\surd"],As=["\\uparrow","\\downarrow","\\updownarrow","\\Uparrow","\\Downarrow","\\Updownarrow","|","\\|","\\vert","\\Vert","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","⟮","⟯","\\lmoustache","\\rmoustache","⎰","⎱"],Os=["<",">","\\langle","\\rangle","/","\\backslash","\\lt","\\gt"],Is=[0,1.2,1.8,2.4,3],xs=[{type:"small",style:Ca.SCRIPTSCRIPT},{type:"small",style:Ca.SCRIPT},{type:"small",style:Ca.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4}],ws=[{type:"small",style:Ca.SCRIPTSCRIPT},{type:"small",style:Ca.SCRIPT},{type:"small",style:Ca.TEXT},{type:"stack"}],Ds=[{type:"small",style:Ca.SCRIPTSCRIPT},{type:"small",style:Ca.SCRIPT},{type:"small",style:Ca.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4},{type:"stack"}],Ms=function(e){if("small"===e.type)return"Main-Regular";if("large"===e.type)return"Size"+e.size+"-Regular";if("stack"===e.type)return"Size4-Regular";throw new Error("Add support for delim type '"+e.type+"' here.")},ks=function(e,t,r,n){for(var a=Math.min(2,3-n.style.size);a<r.length&&"stack"!==r[a].type;a++){var i=ms(e,Ms(r[a]),"math"),o=i.height+i.depth;if("small"===r[a].type&&(o*=n.havingBaseStyle(r[a].style).sizeMultiplier),o>t)return r[a]}return r[r.length-1]},Ls=function(e,t,r,n,a,i){var o;"<"===e||"\\lt"===e||"⟨"===e?e="\\langle":">"!==e&&"\\gt"!==e&&"⟩"!==e||(e="\\rangle"),o=Os.includes(e)?xs:Rs.includes(e)?Ds:ws;var s=ks(e,t,o,n);return"small"===s.type?function(e,t,r,n,a,i){var o=eo.makeSymbol(e,"Main-Regular",a,n),s=gs(o,t,n,i);return r&&hs(s,n,t),s}(e,s.style,r,n,a,i):"large"===s.type?fs(e,s.size,r,n,a,i):ys(e,t,r,n,a,i)},Ps={sqrtImage:function(e,t){var r,n,a=t.havingBaseSizing(),i=ks("\\surd",e*a.sizeMultiplier,Ds,a),o=a.sizeMultiplier,s=Math.max(0,t.minRuleThickness-t.fontMetrics().sqrtRuleThickness),l=0,c=0,d=0;return"small"===i.type?(e<1?o=1:e<1.4&&(o=.7),c=(1+s)/o,(r=Ns("sqrtMain",l=(1+s+Cs)/o,d=1e3+1e3*s+80,s,t)).style.minWidth="0.853em",n=.833/o):"large"===i.type?(d=1080*Is[i.size],c=(Is[i.size]+s)/o,l=(Is[i.size]+s+Cs)/o,(r=Ns("sqrtSize"+i.size,l,d,s,t)).style.minWidth="1.02em",n=1/o):(l=e+s+Cs,c=e+s,d=Math.floor(1e3*e+s)+80,(r=Ns("sqrtTall",l,d,s,t)).style.minWidth="0.742em",n=1.056),r.height=c,r.style.height=Ha(l),{span:r,advanceWidth:n,ruleWidth:(t.fontMetrics().sqrtRuleThickness+s)*o}},sizedDelim:function(e,t,r,n,a){if("<"===e||"\\lt"===e||"⟨"===e?e="\\langle":">"!==e&&"\\gt"!==e&&"⟩"!==e||(e="\\rangle"),Rs.includes(e)||Os.includes(e))return fs(e,t,!1,r,n,a);if(As.includes(e))return ys(e,Is[t],!1,r,n,a);throw new sa("Illegal delimiter: '"+e+"'")},sizeToMaxHeight:Is,customSizedDelim:Ls,leftRightDelim:function(e,t,r,n,a,i){var o=n.fontMetrics().axisHeight*n.sizeMultiplier,s=5/n.fontMetrics().ptPerEm,l=Math.max(t-o,r+o),c=Math.max(l/500*901,2*l-s);return Ls(e,c,!0,n,a,i)}},Fs={"\\bigl":{mclass:"mopen",size:1},"\\Bigl":{mclass:"mopen",size:2},"\\biggl":{mclass:"mopen",size:3},"\\Biggl":{mclass:"mopen",size:4},"\\bigr":{mclass:"mclose",size:1},"\\Bigr":{mclass:"mclose",size:2},"\\biggr":{mclass:"mclose",size:3},"\\Biggr":{mclass:"mclose",size:4},"\\bigm":{mclass:"mrel",size:1},"\\Bigm":{mclass:"mrel",size:2},"\\biggm":{mclass:"mrel",size:3},"\\Biggm":{mclass:"mrel",size:4},"\\big":{mclass:"mord",size:1},"\\Big":{mclass:"mord",size:2},"\\bigg":{mclass:"mord",size:3},"\\Bigg":{mclass:"mord",size:4}},Bs=["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","⌊","⌋","\\lceil","\\rceil","⌈","⌉","<",">","\\langle","⟨","\\rangle","⟩","\\lt","\\gt","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","⟮","⟯","\\lmoustache","\\rmoustache","⎰","⎱","/","\\backslash","|","\\vert","\\|","\\Vert","\\uparrow","\\Uparrow","\\downarrow","\\Downarrow","\\updownarrow","\\Updownarrow","."];function Us(e,t){var r=Qo(e);if(r&&Bs.includes(r.text))return r;throw new sa(r?"Invalid delimiter '"+r.text+"' after '"+t.funcName+"'":"Invalid delimiter type '"+e.type+"'",e)}function Gs(e){if(!e.body)throw new Error("Bug: The leftright ParseNode wasn't fully parsed.")}co({type:"delimsizing",names:["\\bigl","\\Bigl","\\biggl","\\Biggl","\\bigr","\\Bigr","\\biggr","\\Biggr","\\bigm","\\Bigm","\\biggm","\\Biggm","\\big","\\Big","\\bigg","\\Bigg"],props:{numArgs:1,argTypes:["primitive"]},handler:(e,t)=>{var r=Us(t[0],e);return{type:"delimsizing",mode:e.parser.mode,size:Fs[e.funcName].size,mclass:Fs[e.funcName].mclass,delim:r.text}},htmlBuilder:(e,t)=>"."===e.delim?eo.makeSpan([e.mclass]):Ps.sizedDelim(e.delim,e.size,t,e.mode,[e.mclass]),mathmlBuilder:e=>{var t=[];"."!==e.delim&&t.push(Do(e.delim,e.mode));var r=new wo.MathNode("mo",t);"mopen"===e.mclass||"mclose"===e.mclass?r.setAttribute("fence","true"):r.setAttribute("fence","false"),r.setAttribute("stretchy","true");var n=Ha(Ps.sizeToMaxHeight[e.size]);return r.setAttribute("minsize",n),r.setAttribute("maxsize",n),r}}),co({type:"leftright-right",names:["\\right"],props:{numArgs:1,primitive:!0},handler:(e,t)=>{var r=e.parser.gullet.macros.get("\\current@color");if(r&&"string"!=typeof r)throw new sa("\\current@color set to non-string in \\right");return{type:"leftright-right",mode:e.parser.mode,delim:Us(t[0],e).text,color:r}}}),co({type:"leftright",names:["\\left"],props:{numArgs:1,primitive:!0},handler:(e,t)=>{var r=Us(t[0],e),n=e.parser;++n.leftrightDepth;var a=n.parseExpression(!1);--n.leftrightDepth,n.expect("\\right",!1);var i=Wo(n.parseFunction(),"leftright-right");return{type:"leftright",mode:n.mode,body:a,left:r.text,right:i.delim,rightColor:i.color}},htmlBuilder:(e,t)=>{Gs(e);for(var r,n,a=bo(e.body,t,!0,["mopen","mclose"]),i=0,o=0,s=!1,l=0;l<a.length;l++)a[l].isMiddle?s=!0:(i=Math.max(a[l].height,i),o=Math.max(a[l].depth,o));if(i*=t.sizeMultiplier,o*=t.sizeMultiplier,r="."===e.left?Co(t,["mopen"]):Ps.leftRightDelim(e.left,i,o,t,e.mode,["mopen"]),a.unshift(r),s)for(var c=1;c<a.length;c++){var d=a[c].isMiddle;d&&(a[c]=Ps.leftRightDelim(d.delim,i,o,d.options,e.mode,[]))}if("."===e.right)n=Co(t,["mclose"]);else{var u=e.rightColor?t.withColor(e.rightColor):t;n=Ps.leftRightDelim(e.right,i,o,u,e.mode,["mclose"])}return a.push(n),eo.makeSpan(["minner"],a,t)},mathmlBuilder:(e,t)=>{Gs(e);var r=Po(e.body,t);if("."!==e.left){var n=new wo.MathNode("mo",[Do(e.left,e.mode)]);n.setAttribute("fence","true"),r.unshift(n)}if("."!==e.right){var a=new wo.MathNode("mo",[Do(e.right,e.mode)]);a.setAttribute("fence","true"),e.rightColor&&a.setAttribute("mathcolor",e.rightColor),r.push(a)}return Mo(r)}}),co({type:"middle",names:["\\middle"],props:{numArgs:1,primitive:!0},handler:(e,t)=>{var r=Us(t[0],e);if(!e.parser.leftrightDepth)throw new sa("\\middle without preceding \\left",r);return{type:"middle",mode:e.parser.mode,delim:r.text}},htmlBuilder:(e,t)=>{var r;if("."===e.delim)r=Co(t,[]);else{r=Ps.sizedDelim(e.delim,1,t,e.mode,[]);var n={delim:e.delim,options:t};r.isMiddle=n}return r},mathmlBuilder:(e,t)=>{var r="\\vert"===e.delim||"|"===e.delim?Do("|","text"):Do(e.delim,e.mode),n=new wo.MathNode("mo",[r]);return n.setAttribute("fence","true"),n.setAttribute("lspace","0.05em"),n.setAttribute("rspace","0.05em"),n}});var zs=(e,t)=>{var r,n,a,i=eo.wrapFragment(No(e.body,t),t),o=e.label.slice(1),s=t.sizeMultiplier,l=0,c=pa.isCharacterBox(e.body);if("sout"===o)(r=eo.makeSpan(["stretchy","sout"])).height=t.fontMetrics().defaultRuleThickness/s,l=-.5*t.fontMetrics().xHeight;else if("phase"===o){var d=qa({number:.6,unit:"pt"},t),u=qa({number:.35,unit:"ex"},t);s/=t.havingBaseSizing().sizeMultiplier;var p=i.height+i.depth+d+u;i.style.paddingLeft=Ha(p/2+d);var _=Math.floor(1e3*p*s),m="M400000 "+(n=_)+" H0 L"+n/2+" 0 l65 45 L145 "+(n-80)+" H400000z",g=new ti([new ri("phase",m)],{width:"400em",height:Ha(_/1e3),viewBox:"0 0 400000 "+_,preserveAspectRatio:"xMinYMin slice"});(r=eo.makeSvgSpan(["hide-tail"],[g],t)).style.height=Ha(p),l=i.depth+d+u}else{/cancel/.test(o)?c||i.classes.push("cancel-pad"):"angl"===o?i.classes.push("anglpad"):i.classes.push("boxpad");var h=0,f=0,E=0;/box/.test(o)?(E=Math.max(t.fontMetrics().fboxrule,t.minRuleThickness),f=h=t.fontMetrics().fboxsep+("colorbox"===o?0:E)):"angl"===o?(h=4*(E=Math.max(t.fontMetrics().defaultRuleThickness,t.minRuleThickness)),f=Math.max(0,.25-i.depth)):f=h=c?.2:0,r=Ho(i,o,h,f,t),/fbox|boxed|fcolorbox/.test(o)?(r.style.borderStyle="solid",r.style.borderWidth=Ha(E)):"angl"===o&&.049!==E&&(r.style.borderTopWidth=Ha(E),r.style.borderRightWidth=Ha(E)),l=i.depth+f,e.backgroundColor&&(r.style.backgroundColor=e.backgroundColor,e.borderColor&&(r.style.borderColor=e.borderColor))}if(e.backgroundColor)a=eo.makeVList({positionType:"individualShift",children:[{type:"elem",elem:r,shift:l},{type:"elem",elem:i,shift:0}]},t);else{var b=/cancel|phase/.test(o)?["svg-align"]:[];a=eo.makeVList({positionType:"individualShift",children:[{type:"elem",elem:i,shift:0},{type:"elem",elem:r,shift:l,wrapperClasses:b}]},t)}return/cancel/.test(o)&&(a.height=i.height,a.depth=i.depth),/cancel/.test(o)&&!c?eo.makeSpan(["mord","cancel-lap"],[a],t):eo.makeSpan(["mord"],[a],t)},Ys=(e,t)=>{var r=0,n=new wo.MathNode(e.label.indexOf("colorbox")>-1?"mpadded":"menclose",[Bo(e.body,t)]);switch(e.label){case"\\cancel":n.setAttribute("notation","updiagonalstrike");break;case"\\bcancel":n.setAttribute("notation","downdiagonalstrike");break;case"\\phase":n.setAttribute("notation","phasorangle");break;case"\\sout":n.setAttribute("notation","horizontalstrike");break;case"\\fbox":n.setAttribute("notation","box");break;case"\\angl":n.setAttribute("notation","actuarial");break;case"\\fcolorbox":case"\\colorbox":if(r=t.fontMetrics().fboxsep*t.fontMetrics().ptPerEm,n.setAttribute("width","+"+2*r+"pt"),n.setAttribute("height","+"+2*r+"pt"),n.setAttribute("lspace",r+"pt"),n.setAttribute("voffset",r+"pt"),"\\fcolorbox"===e.label){var a=Math.max(t.fontMetrics().fboxrule,t.minRuleThickness);n.setAttribute("style","border: "+a+"em solid "+String(e.borderColor))}break;case"\\xcancel":n.setAttribute("notation","updiagonalstrike downdiagonalstrike")}return e.backgroundColor&&n.setAttribute("mathbackground",e.backgroundColor),n};co({type:"enclose",names:["\\colorbox"],props:{numArgs:2,allowedInText:!0,argTypes:["color","text"]},handler(e,t,r){var{parser:n,funcName:a}=e,i=Wo(t[0],"color-token").color,o=t[1];return{type:"enclose",mode:n.mode,label:a,backgroundColor:i,body:o}},htmlBuilder:zs,mathmlBuilder:Ys}),co({type:"enclose",names:["\\fcolorbox"],props:{numArgs:3,allowedInText:!0,argTypes:["color","color","text"]},handler(e,t,r){var{parser:n,funcName:a}=e,i=Wo(t[0],"color-token").color,o=Wo(t[1],"color-token").color,s=t[2];return{type:"enclose",mode:n.mode,label:a,backgroundColor:o,borderColor:i,body:s}},htmlBuilder:zs,mathmlBuilder:Ys}),co({type:"enclose",names:["\\fbox"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!0},handler(e,t){var{parser:r}=e;return{type:"enclose",mode:r.mode,label:"\\fbox",body:t[0]}}}),co({type:"enclose",names:["\\cancel","\\bcancel","\\xcancel","\\sout","\\phase"],props:{numArgs:1},handler(e,t){var{parser:r,funcName:n}=e,a=t[0];return{type:"enclose",mode:r.mode,label:n,body:a}},htmlBuilder:zs,mathmlBuilder:Ys}),co({type:"enclose",names:["\\angl"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!1},handler(e,t){var{parser:r}=e;return{type:"enclose",mode:r.mode,label:"\\angl",body:t[0]}}});var qs={};function Hs(e){for(var{type:t,names:r,props:n,handler:a,htmlBuilder:i,mathmlBuilder:o}=e,s={type:t,numArgs:n.numArgs||0,allowedInText:!1,numOptionalArgs:0,handler:a},l=0;l<r.length;++l)qs[r[l]]=s;i&&(so[t]=i),o&&(lo[t]=o)}var Vs={};function $s(e,t){Vs[e]=t}function Ws(e){var t=[];e.consumeSpaces();var r=e.fetch().text;for("\\relax"===r&&(e.consume(),e.consumeSpaces(),r=e.fetch().text);"\\hline"===r||"\\hdashline"===r;)e.consume(),t.push("\\hdashline"===r),e.consumeSpaces(),r=e.fetch().text;return t}var js=e=>{if(!e.parser.settings.displayMode)throw new sa("{"+e.envName+"} can be used only in display mode.")};function Qs(e){if(-1===e.indexOf("ed"))return-1===e.indexOf("*")}function Ks(e,t,r){var{hskipBeforeAndAfter:n,addJot:a,cols:i,arraystretch:o,colSeparationType:s,autoTag:l,singleRow:c,emptySingleRow:d,maxNumCols:u,leqno:p}=t;if(e.gullet.beginGroup(),c||e.gullet.macros.set("\\cr","\\\\\\relax"),!o){var _=e.gullet.expandMacroAsText("\\arraystretch");if(null==_)o=1;else if(!(o=parseFloat(_))||o<0)throw new sa("Invalid \\arraystretch: "+_)}e.gullet.beginGroup();var m=[],g=[m],h=[],f=[],E=null!=l?[]:void 0;function b(){l&&e.gullet.macros.set("\\@eqnsw","1",!0)}function S(){E&&(e.gullet.macros.get("\\df@tag")?(E.push(e.subparse([new oa("\\df@tag")])),e.gullet.macros.set("\\df@tag",void 0,!0)):E.push(Boolean(l)&&"1"===e.gullet.macros.get("\\@eqnsw")))}for(b(),f.push(Ws(e));;){var v=e.parseExpression(!1,c?"\\end":"\\\\");e.gullet.endGroup(),e.gullet.beginGroup(),v={type:"ordgroup",mode:e.mode,body:v},r&&(v={type:"styling",mode:e.mode,style:r,body:[v]}),m.push(v);var T=e.fetch().text;if("&"===T){if(u&&m.length===u){if(c||s)throw new sa("Too many tab characters: &",e.nextToken);e.settings.reportNonstrict("textEnv","Too few columns specified in the {array} column argument.")}e.consume()}else{if("\\end"===T){S(),1===m.length&&"styling"===v.type&&0===v.body[0].body.length&&(g.length>1||!d)&&g.pop(),f.length<g.length+1&&f.push([]);break}if("\\\\"!==T)throw new sa("Expected & or \\\\ or \\cr or \\end",e.nextToken);e.consume();var y=void 0;" "!==e.gullet.future().text&&(y=e.parseSizeGroup(!0)),h.push(y?y.value:null),S(),f.push(Ws(e)),m=[],g.push(m),b()}}return e.gullet.endGroup(),e.gullet.endGroup(),{type:"array",mode:e.mode,addJot:a,arraystretch:o,body:g,cols:i,rowGaps:h,hskipBeforeAndAfter:n,hLinesBeforeRow:f,colSeparationType:s,tags:E,leqno:p}}function Xs(e){return"d"===e.slice(0,1)?"display":"text"}var Zs=function(e,t){var r,n,a=e.body.length,i=e.hLinesBeforeRow,o=0,s=new Array(a),l=[],c=Math.max(t.fontMetrics().arrayRuleWidth,t.minRuleThickness),d=1/t.fontMetrics().ptPerEm,u=5*d;e.colSeparationType&&"small"===e.colSeparationType&&(u=t.havingStyle(Ca.SCRIPT).sizeMultiplier/t.sizeMultiplier*.2778);var p="CD"===e.colSeparationType?qa({number:3,unit:"ex"},t):12*d,_=3*d,m=e.arraystretch*p,g=.7*m,h=.3*m,f=0;function E(e){for(var t=0;t<e.length;++t)t>0&&(f+=.25),l.push({pos:f,isDashed:e[t]})}for(E(i[0]),r=0;r<e.body.length;++r){var b=e.body[r],S=g,v=h;o<b.length&&(o=b.length);var T=new Array(b.length);for(n=0;n<b.length;++n){var y=No(b[n],t);v<y.depth&&(v=y.depth),S<y.height&&(S=y.height),T[n]=y}var C=e.rowGaps[r],N=0;C&&(N=qa(C,t))>0&&(v<(N+=h)&&(v=N),N=0),e.addJot&&(v+=_),T.height=S,T.depth=v,f+=S,T.pos=f,f+=v+N,s[r]=T,E(i[r+1])}var R,A,O=f/2+t.fontMetrics().axisHeight,I=e.cols||[],x=[],w=[];if(e.tags&&e.tags.some(e=>e))for(r=0;r<a;++r){var D=s[r],M=D.pos-O,k=e.tags[r],L=void 0;(L=!0===k?eo.makeSpan(["eqn-num"],[],t):!1===k?eo.makeSpan([],[],t):eo.makeSpan([],bo(k,t,!0),t)).depth=D.depth,L.height=D.height,w.push({type:"elem",elem:L,shift:M})}for(n=0,A=0;n<o||A<I.length;++n,++A){for(var P=I[A]||{},F=!0;"separator"===P.type;){if(F||((R=eo.makeSpan(["arraycolsep"],[])).style.width=Ha(t.fontMetrics().doubleRuleSep),x.push(R)),"|"!==P.separator&&":"!==P.separator)throw new sa("Invalid separator type: "+P.separator);var B="|"===P.separator?"solid":"dashed",U=eo.makeSpan(["vertical-separator"],[],t);U.style.height=Ha(f),U.style.borderRightWidth=Ha(c),U.style.borderRightStyle=B,U.style.margin="0 "+Ha(-c/2);var G=f-O;G&&(U.style.verticalAlign=Ha(-G)),x.push(U),P=I[++A]||{},F=!1}if(!(n>=o)){var z=void 0;(n>0||e.hskipBeforeAndAfter)&&0!==(z=pa.deflt(P.pregap,u))&&((R=eo.makeSpan(["arraycolsep"],[])).style.width=Ha(z),x.push(R));var Y=[];for(r=0;r<a;++r){var q=s[r],H=q[n];if(H){var V=q.pos-O;H.depth=q.depth,H.height=q.height,Y.push({type:"elem",elem:H,shift:V})}}Y=eo.makeVList({positionType:"individualShift",children:Y},t),Y=eo.makeSpan(["col-align-"+(P.align||"c")],[Y]),x.push(Y),(n<o-1||e.hskipBeforeAndAfter)&&0!==(z=pa.deflt(P.postgap,u))&&((R=eo.makeSpan(["arraycolsep"],[])).style.width=Ha(z),x.push(R))}}if(s=eo.makeSpan(["mtable"],x),l.length>0){for(var $=eo.makeLineSpan("hline",t,c),W=eo.makeLineSpan("hdashline",t,c),j=[{type:"elem",elem:s,shift:0}];l.length>0;){var Q=l.pop(),K=Q.pos-O;Q.isDashed?j.push({type:"elem",elem:W,shift:K}):j.push({type:"elem",elem:$,shift:K})}s=eo.makeVList({positionType:"individualShift",children:j},t)}if(0===w.length)return eo.makeSpan(["mord"],[s],t);var X=eo.makeVList({positionType:"individualShift",children:w},t);return X=eo.makeSpan(["tag"],[X],t),eo.makeFragment([s,X])},Js={c:"center ",l:"left ",r:"right "},el=function(e,t){for(var r=[],n=new wo.MathNode("mtd",[],["mtr-glue"]),a=new wo.MathNode("mtd",[],["mml-eqn-num"]),i=0;i<e.body.length;i++){for(var o=e.body[i],s=[],l=0;l<o.length;l++)s.push(new wo.MathNode("mtd",[Bo(o[l],t)]));e.tags&&e.tags[i]&&(s.unshift(n),s.push(n),e.leqno?s.unshift(a):s.push(a)),r.push(new wo.MathNode("mtr",s))}var c=new wo.MathNode("mtable",r),d=.5===e.arraystretch?.1:.16+e.arraystretch-1+(e.addJot?.09:0);c.setAttribute("rowspacing",Ha(d));var u="",p="";if(e.cols&&e.cols.length>0){var _=e.cols,m="",g=!1,h=0,f=_.length;"separator"===_[0].type&&(u+="top ",h=1),"separator"===_[_.length-1].type&&(u+="bottom ",f-=1);for(var E=h;E<f;E++)"align"===_[E].type?(p+=Js[_[E].align],g&&(m+="none "),g=!0):"separator"===_[E].type&&g&&(m+="|"===_[E].separator?"solid ":"dashed ",g=!1);c.setAttribute("columnalign",p.trim()),/[sd]/.test(m)&&c.setAttribute("columnlines",m.trim())}if("align"===e.colSeparationType){for(var b=e.cols||[],S="",v=1;v<b.length;v++)S+=v%2?"0em ":"1em ";c.setAttribute("columnspacing",S.trim())}else"alignat"===e.colSeparationType||"gather"===e.colSeparationType?c.setAttribute("columnspacing","0em"):"small"===e.colSeparationType?c.setAttribute("columnspacing","0.2778em"):"CD"===e.colSeparationType?c.setAttribute("columnspacing","0.5em"):c.setAttribute("columnspacing","1em");var T="",y=e.hLinesBeforeRow;u+=y[0].length>0?"left ":"",u+=y[y.length-1].length>0?"right ":"";for(var C=1;C<y.length-1;C++)T+=0===y[C].length?"none ":y[C][0]?"dashed ":"solid ";return/[sd]/.test(T)&&c.setAttribute("rowlines",T.trim()),""!==u&&(c=new wo.MathNode("menclose",[c])).setAttribute("notation",u.trim()),e.arraystretch&&e.arraystretch<1&&(c=new wo.MathNode("mstyle",[c])).setAttribute("scriptlevel","1"),c},tl=function(e,t){-1===e.envName.indexOf("ed")&&js(e);var r,n=[],a=e.envName.indexOf("at")>-1?"alignat":"align",i="split"===e.envName,o=Ks(e.parser,{cols:n,addJot:!0,autoTag:i?void 0:Qs(e.envName),emptySingleRow:!0,colSeparationType:a,maxNumCols:i?2:void 0,leqno:e.parser.settings.leqno},"display"),s=0,l={type:"ordgroup",mode:e.mode,body:[]};if(t[0]&&"ordgroup"===t[0].type){for(var c="",d=0;d<t[0].body.length;d++){c+=Wo(t[0].body[d],"textord").text}r=Number(c),s=2*r}var u=!s;o.body.forEach(function(e){for(var t=1;t<e.length;t+=2){var n=Wo(e[t],"styling");Wo(n.body[0],"ordgroup").body.unshift(l)}if(u)s<e.length&&(s=e.length);else{var a=e.length/2;if(r<a)throw new sa("Too many math in a row: expected "+r+", but got "+a,e[0])}});for(var p=0;p<s;++p){var _="r",m=0;p%2==1?_="l":p>0&&u&&(m=1),n[p]={type:"align",align:_,pregap:m,postgap:0}}return o.colSeparationType=u?"align":"alignat",o};Hs({type:"array",names:["array","darray"],props:{numArgs:1},handler(e,t){var r=(Qo(t[0])?[t[0]]:Wo(t[0],"ordgroup").body).map(function(e){var t=jo(e).text;if(-1!=="lcr".indexOf(t))return{type:"align",align:t};if("|"===t)return{type:"separator",separator:"|"};if(":"===t)return{type:"separator",separator:":"};throw new sa("Unknown column alignment: "+t,e)}),n={cols:r,hskipBeforeAndAfter:!0,maxNumCols:r.length};return Ks(e.parser,n,Xs(e.envName))},htmlBuilder:Zs,mathmlBuilder:el}),Hs({type:"array",names:["matrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix","matrix*","pmatrix*","bmatrix*","Bmatrix*","vmatrix*","Vmatrix*"],props:{numArgs:0},handler(e){var t={matrix:null,pmatrix:["(",")"],bmatrix:["[","]"],Bmatrix:["\\{","\\}"],vmatrix:["|","|"],Vmatrix:["\\Vert","\\Vert"]}[e.envName.replace("*","")],r="c",n={hskipBeforeAndAfter:!1,cols:[{type:"align",align:r}]};if("*"===e.envName.charAt(e.envName.length-1)){var a=e.parser;if(a.consumeSpaces(),"["===a.fetch().text){if(a.consume(),a.consumeSpaces(),r=a.fetch().text,-1==="lcr".indexOf(r))throw new sa("Expected l or c or r",a.nextToken);a.consume(),a.consumeSpaces(),a.expect("]"),a.consume(),n.cols=[{type:"align",align:r}]}}var i=Ks(e.parser,n,Xs(e.envName)),o=Math.max(0,...i.body.map(e=>e.length));return i.cols=new Array(o).fill({type:"align",align:r}),t?{type:"leftright",mode:e.mode,body:[i],left:t[0],right:t[1],rightColor:void 0}:i},htmlBuilder:Zs,mathmlBuilder:el}),Hs({type:"array",names:["smallmatrix"],props:{numArgs:0},handler(e){var t=Ks(e.parser,{arraystretch:.5},"script");return t.colSeparationType="small",t},htmlBuilder:Zs,mathmlBuilder:el}),Hs({type:"array",names:["subarray"],props:{numArgs:1},handler(e,t){var r=(Qo(t[0])?[t[0]]:Wo(t[0],"ordgroup").body).map(function(e){var t=jo(e).text;if(-1!=="lc".indexOf(t))return{type:"align",align:t};throw new sa("Unknown column alignment: "+t,e)});if(r.length>1)throw new sa("{subarray} can contain only one column");var n={cols:r,hskipBeforeAndAfter:!1,arraystretch:.5};if((n=Ks(e.parser,n,"script")).body.length>0&&n.body[0].length>1)throw new sa("{subarray} can contain only one column");return n},htmlBuilder:Zs,mathmlBuilder:el}),Hs({type:"array",names:["cases","dcases","rcases","drcases"],props:{numArgs:0},handler(e){var t=Ks(e.parser,{arraystretch:1.2,cols:[{type:"align",align:"l",pregap:0,postgap:1},{type:"align",align:"l",pregap:0,postgap:0}]},Xs(e.envName));return{type:"leftright",mode:e.mode,body:[t],left:e.envName.indexOf("r")>-1?".":"\\{",right:e.envName.indexOf("r")>-1?"\\}":".",rightColor:void 0}},htmlBuilder:Zs,mathmlBuilder:el}),Hs({type:"array",names:["align","align*","aligned","split"],props:{numArgs:0},handler:tl,htmlBuilder:Zs,mathmlBuilder:el}),Hs({type:"array",names:["gathered","gather","gather*"],props:{numArgs:0},handler(e){["gather","gather*"].includes(e.envName)&&js(e);var t={cols:[{type:"align",align:"c"}],addJot:!0,colSeparationType:"gather",autoTag:Qs(e.envName),emptySingleRow:!0,leqno:e.parser.settings.leqno};return Ks(e.parser,t,"display")},htmlBuilder:Zs,mathmlBuilder:el}),Hs({type:"array",names:["alignat","alignat*","alignedat"],props:{numArgs:1},handler:tl,htmlBuilder:Zs,mathmlBuilder:el}),Hs({type:"array",names:["equation","equation*"],props:{numArgs:0},handler(e){js(e);var t={autoTag:Qs(e.envName),emptySingleRow:!0,singleRow:!0,maxNumCols:1,leqno:e.parser.settings.leqno};return Ks(e.parser,t,"display")},htmlBuilder:Zs,mathmlBuilder:el}),Hs({type:"array",names:["CD"],props:{numArgs:0},handler:e=>(js(e),function(e){var t=[];for(e.gullet.beginGroup(),e.gullet.macros.set("\\cr","\\\\\\relax"),e.gullet.beginGroup();;){t.push(e.parseExpression(!1,"\\\\")),e.gullet.endGroup(),e.gullet.beginGroup();var r=e.fetch().text;if("&"!==r&&"\\\\"!==r){if("\\end"===r){0===t[t.length-1].length&&t.pop();break}throw new sa("Expected \\\\ or \\cr or \\end",e.nextToken)}e.consume()}for(var n=[],a=[n],i=0;i<t.length;i++){for(var o=t[i],s=is(),l=0;l<o.length;l++)if(os(o[l])){n.push(s);var c=jo(o[l+=1]).text,d=new Array(2);if(d[0]={type:"ordgroup",mode:"math",body:[]},d[1]={type:"ordgroup",mode:"math",body:[]},"=|.".indexOf(c)>-1);else{if(!("<>AV".indexOf(c)>-1))throw new sa('Expected one of "<>AV=|." after @',o[l]);for(var u=0;u<2;u++){for(var p=!0,_=l+1;_<o.length;_++){if(ss(o[_],c)){p=!1,l=_;break}if(os(o[_]))throw new sa("Missing a "+c+" character to complete a CD arrow.",o[_]);d[u].body.push(o[_])}if(p)throw new sa("Missing a "+c+" character to complete a CD arrow.",o[l])}}var m={type:"styling",body:[ls(c,d,e)],mode:"math",style:"display"};n.push(m),s=is()}else s.body.push(o[l]);i%2==0?n.push(s):n.shift(),n=[],a.push(n)}return e.gullet.endGroup(),e.gullet.endGroup(),{type:"array",mode:"math",body:a,arraystretch:1,addJot:!0,rowGaps:[null],cols:new Array(a[0].length).fill({type:"align",align:"c",pregap:.25,postgap:.25}),colSeparationType:"CD",hLinesBeforeRow:new Array(a.length+1).fill([])}}(e.parser)),htmlBuilder:Zs,mathmlBuilder:el}),$s("\\nonumber","\\gdef\\@eqnsw{0}"),$s("\\notag","\\nonumber"),co({type:"text",names:["\\hline","\\hdashline"],props:{numArgs:0,allowedInText:!0,allowedInMath:!0},handler(e,t){throw new sa(e.funcName+" valid only within array environment")}});var rl=qs;co({type:"environment",names:["\\begin","\\end"],props:{numArgs:1,argTypes:["text"]},handler(e,t){var{parser:r,funcName:n}=e,a=t[0];if("ordgroup"!==a.type)throw new sa("Invalid environment name",a);for(var i="",o=0;o<a.body.length;++o)i+=Wo(a.body[o],"textord").text;if("\\begin"===n){if(!rl.hasOwnProperty(i))throw new sa("No such environment: "+i,a);var s=rl[i],{args:l,optArgs:c}=r.parseArguments("\\begin{"+i+"}",s),d={mode:r.mode,envName:i,parser:r},u=s.handler(d,l,c);r.expect("\\end",!1);var p=r.nextToken,_=Wo(r.parseFunction(),"environment");if(_.name!==i)throw new sa("Mismatch: \\begin{"+i+"} matched by \\end{"+_.name+"}",p);return u}return{type:"environment",mode:r.mode,name:i,nameGroup:a}}});var nl=(e,t)=>{var r=e.font,n=t.withFont(r);return No(e.body,n)},al=(e,t)=>{var r=e.font,n=t.withFont(r);return Bo(e.body,n)},il={"\\Bbb":"\\mathbb","\\bold":"\\mathbf","\\frak":"\\mathfrak","\\bm":"\\boldsymbol"};co({type:"font",names:["\\mathrm","\\mathit","\\mathbf","\\mathnormal","\\mathsfit","\\mathbb","\\mathcal","\\mathfrak","\\mathscr","\\mathsf","\\mathtt","\\Bbb","\\bold","\\frak"],props:{numArgs:1,allowedInArgument:!0},handler:(e,t)=>{var{parser:r,funcName:n}=e,a=po(t[0]),i=n;return i in il&&(i=il[i]),{type:"font",mode:r.mode,font:i.slice(1),body:a}},htmlBuilder:nl,mathmlBuilder:al}),co({type:"mclass",names:["\\boldsymbol","\\bm"],props:{numArgs:1},handler:(e,t)=>{var{parser:r}=e,n=t[0],a=pa.isCharacterBox(n);return{type:"mclass",mode:r.mode,mclass:ns(n),body:[{type:"font",mode:r.mode,font:"boldsymbol",body:n}],isCharacterBox:a}}}),co({type:"font",names:["\\rm","\\sf","\\tt","\\bf","\\it","\\cal"],props:{numArgs:0,allowedInText:!0},handler:(e,t)=>{var{parser:r,funcName:n,breakOnTokenText:a}=e,{mode:i}=r,o=r.parseExpression(!0,a);return{type:"font",mode:i,font:"math"+n.slice(1),body:{type:"ordgroup",mode:r.mode,body:o}}},htmlBuilder:nl,mathmlBuilder:al});var ol=(e,t)=>{var r=t;return"display"===e?r=r.id>=Ca.SCRIPT.id?r.text():Ca.DISPLAY:"text"===e&&r.size===Ca.DISPLAY.size?r=Ca.TEXT:"script"===e?r=Ca.SCRIPT:"scriptscript"===e&&(r=Ca.SCRIPTSCRIPT),r},sl=(e,t)=>{var r,n=ol(e.size,t.style),a=n.fracNum(),i=n.fracDen();r=t.havingStyle(a);var o=No(e.numer,r,t);if(e.continued){var s=8.5/t.fontMetrics().ptPerEm,l=3.5/t.fontMetrics().ptPerEm;o.height=o.height<s?s:o.height,o.depth=o.depth<l?l:o.depth}r=t.havingStyle(i);var c,d,u,p,_,m,g,h,f,E,b=No(e.denom,r,t);if(e.hasBarLine?(e.barSize?(d=qa(e.barSize,t),c=eo.makeLineSpan("frac-line",t,d)):c=eo.makeLineSpan("frac-line",t),d=c.height,u=c.height):(c=null,d=0,u=t.fontMetrics().defaultRuleThickness),n.size===Ca.DISPLAY.size||"display"===e.size?(p=t.fontMetrics().num1,_=d>0?3*u:7*u,m=t.fontMetrics().denom1):(d>0?(p=t.fontMetrics().num2,_=u):(p=t.fontMetrics().num3,_=3*u),m=t.fontMetrics().denom2),c){var S=t.fontMetrics().axisHeight;p-o.depth-(S+.5*d)<_&&(p+=_-(p-o.depth-(S+.5*d))),S-.5*d-(b.height-m)<_&&(m+=_-(S-.5*d-(b.height-m)));var v=-(S-.5*d);g=eo.makeVList({positionType:"individualShift",children:[{type:"elem",elem:b,shift:m},{type:"elem",elem:c,shift:v},{type:"elem",elem:o,shift:-p}]},t)}else{var T=p-o.depth-(b.height-m);T<_&&(p+=.5*(_-T),m+=.5*(_-T)),g=eo.makeVList({positionType:"individualShift",children:[{type:"elem",elem:b,shift:m},{type:"elem",elem:o,shift:-p}]},t)}return r=t.havingStyle(n),g.height*=r.sizeMultiplier/t.sizeMultiplier,g.depth*=r.sizeMultiplier/t.sizeMultiplier,h=n.size===Ca.DISPLAY.size?t.fontMetrics().delim1:n.size===Ca.SCRIPTSCRIPT.size?t.havingStyle(Ca.SCRIPT).fontMetrics().delim2:t.fontMetrics().delim2,f=null==e.leftDelim?Co(t,["mopen"]):Ps.customSizedDelim(e.leftDelim,h,!0,t.havingStyle(n),e.mode,["mopen"]),E=e.continued?eo.makeSpan([]):null==e.rightDelim?Co(t,["mclose"]):Ps.customSizedDelim(e.rightDelim,h,!0,t.havingStyle(n),e.mode,["mclose"]),eo.makeSpan(["mord"].concat(r.sizingClasses(t)),[f,eo.makeSpan(["mfrac"],[g]),E],t)},ll=(e,t)=>{var r=new wo.MathNode("mfrac",[Bo(e.numer,t),Bo(e.denom,t)]);if(e.hasBarLine){if(e.barSize){var n=qa(e.barSize,t);r.setAttribute("linethickness",Ha(n))}}else r.setAttribute("linethickness","0px");var a=ol(e.size,t.style);if(a.size!==t.style.size){r=new wo.MathNode("mstyle",[r]);var i=a.size===Ca.DISPLAY.size?"true":"false";r.setAttribute("displaystyle",i),r.setAttribute("scriptlevel","0")}if(null!=e.leftDelim||null!=e.rightDelim){var o=[];if(null!=e.leftDelim){var s=new wo.MathNode("mo",[new wo.TextNode(e.leftDelim.replace("\\",""))]);s.setAttribute("fence","true"),o.push(s)}if(o.push(r),null!=e.rightDelim){var l=new wo.MathNode("mo",[new wo.TextNode(e.rightDelim.replace("\\",""))]);l.setAttribute("fence","true"),o.push(l)}return Mo(o)}return r};co({type:"genfrac",names:["\\dfrac","\\frac","\\tfrac","\\dbinom","\\binom","\\tbinom","\\\\atopfrac","\\\\bracefrac","\\\\brackfrac"],props:{numArgs:2,allowedInArgument:!0},handler:(e,t)=>{var r,{parser:n,funcName:a}=e,i=t[0],o=t[1],s=null,l=null,c="auto";switch(a){case"\\dfrac":case"\\frac":case"\\tfrac":r=!0;break;case"\\\\atopfrac":r=!1;break;case"\\dbinom":case"\\binom":case"\\tbinom":r=!1,s="(",l=")";break;case"\\\\bracefrac":r=!1,s="\\{",l="\\}";break;case"\\\\brackfrac":r=!1,s="[",l="]";break;default:throw new Error("Unrecognized genfrac command")}switch(a){case"\\dfrac":case"\\dbinom":c="display";break;case"\\tfrac":case"\\tbinom":c="text"}return{type:"genfrac",mode:n.mode,continued:!1,numer:i,denom:o,hasBarLine:r,leftDelim:s,rightDelim:l,size:c,barSize:null}},htmlBuilder:sl,mathmlBuilder:ll}),co({type:"genfrac",names:["\\cfrac"],props:{numArgs:2},handler:(e,t)=>{var{parser:r,funcName:n}=e,a=t[0],i=t[1];return{type:"genfrac",mode:r.mode,continued:!0,numer:a,denom:i,hasBarLine:!0,leftDelim:null,rightDelim:null,size:"display",barSize:null}}}),co({type:"infix",names:["\\over","\\choose","\\atop","\\brace","\\brack"],props:{numArgs:0,infix:!0},handler(e){var t,{parser:r,funcName:n,token:a}=e;switch(n){case"\\over":t="\\frac";break;case"\\choose":t="\\binom";break;case"\\atop":t="\\\\atopfrac";break;case"\\brace":t="\\\\bracefrac";break;case"\\brack":t="\\\\brackfrac";break;default:throw new Error("Unrecognized infix genfrac command")}return{type:"infix",mode:r.mode,replaceWith:t,token:a}}});var cl=["display","text","script","scriptscript"],dl=function(e){var t=null;return e.length>0&&(t="."===(t=e)?null:t),t};co({type:"genfrac",names:["\\genfrac"],props:{numArgs:6,allowedInArgument:!0,argTypes:["math","math","size","text","math","math"]},handler(e,t){var r,{parser:n}=e,a=t[4],i=t[5],o=po(t[0]),s="atom"===o.type&&"open"===o.family?dl(o.text):null,l=po(t[1]),c="atom"===l.type&&"close"===l.family?dl(l.text):null,d=Wo(t[2],"size"),u=null;r=!!d.isBlank||(u=d.value).number>0;var p="auto",_=t[3];if("ordgroup"===_.type){if(_.body.length>0){var m=Wo(_.body[0],"textord");p=cl[Number(m.text)]}}else _=Wo(_,"textord"),p=cl[Number(_.text)];return{type:"genfrac",mode:n.mode,numer:a,denom:i,continued:!1,hasBarLine:r,barSize:u,leftDelim:s,rightDelim:c,size:p}},htmlBuilder:sl,mathmlBuilder:ll}),co({type:"infix",names:["\\above"],props:{numArgs:1,argTypes:["size"],infix:!0},handler(e,t){var{parser:r,funcName:n,token:a}=e;return{type:"infix",mode:r.mode,replaceWith:"\\\\abovefrac",size:Wo(t[0],"size").value,token:a}}}),co({type:"genfrac",names:["\\\\abovefrac"],props:{numArgs:3,argTypes:["math","size","math"]},handler:(e,t)=>{var{parser:r,funcName:n}=e,a=t[0],i=function(e){if(!e)throw new Error("Expected non-null, but got "+String(e));return e}(Wo(t[1],"infix").size),o=t[2],s=i.number>0;return{type:"genfrac",mode:r.mode,numer:a,denom:o,continued:!1,hasBarLine:s,barSize:i,leftDelim:null,rightDelim:null,size:"auto"}},htmlBuilder:sl,mathmlBuilder:ll});var ul=(e,t)=>{var r,n,a=t.style;"supsub"===e.type?(r=e.sup?No(e.sup,t.havingStyle(a.sup()),t):No(e.sub,t.havingStyle(a.sub()),t),n=Wo(e.base,"horizBrace")):n=Wo(e,"horizBrace");var i,o=No(n.base,t.havingBaseStyle(Ca.DISPLAY)),s=$o(n,t);if(n.isOver?(i=eo.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:o},{type:"kern",size:.1},{type:"elem",elem:s}]},t)).children[0].children[0].children[1].classes.push("svg-align"):(i=eo.makeVList({positionType:"bottom",positionData:o.depth+.1+s.height,children:[{type:"elem",elem:s},{type:"kern",size:.1},{type:"elem",elem:o}]},t)).children[0].children[0].children[0].classes.push("svg-align"),r){var l=eo.makeSpan(["mord",n.isOver?"mover":"munder"],[i],t);i=n.isOver?eo.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:l},{type:"kern",size:.2},{type:"elem",elem:r}]},t):eo.makeVList({positionType:"bottom",positionData:l.depth+.2+r.height+r.depth,children:[{type:"elem",elem:r},{type:"kern",size:.2},{type:"elem",elem:l}]},t)}return eo.makeSpan(["mord",n.isOver?"mover":"munder"],[i],t)};co({type:"horizBrace",names:["\\overbrace","\\underbrace"],props:{numArgs:1},handler(e,t){var{parser:r,funcName:n}=e;return{type:"horizBrace",mode:r.mode,label:n,isOver:/^\\over/.test(n),base:t[0]}},htmlBuilder:ul,mathmlBuilder:(e,t)=>{var r=Vo(e.label);return new wo.MathNode(e.isOver?"mover":"munder",[Bo(e.base,t),r])}}),co({type:"href",names:["\\href"],props:{numArgs:2,argTypes:["url","original"],allowedInText:!0},handler:(e,t)=>{var{parser:r}=e,n=t[1],a=Wo(t[0],"url").url;return r.settings.isTrusted({command:"\\href",url:a})?{type:"href",mode:r.mode,href:a,body:_o(n)}:r.formatUnsupportedCmd("\\href")},htmlBuilder:(e,t)=>{var r=bo(e.body,t,!1);return eo.makeAnchor(e.href,[],r,t)},mathmlBuilder:(e,t)=>{var r=Fo(e.body,t);return r instanceof Io||(r=new Io("mrow",[r])),r.setAttribute("href",e.href),r}}),co({type:"href",names:["\\url"],props:{numArgs:1,argTypes:["url"],allowedInText:!0},handler:(e,t)=>{var{parser:r}=e,n=Wo(t[0],"url").url;if(!r.settings.isTrusted({command:"\\url",url:n}))return r.formatUnsupportedCmd("\\url");for(var a=[],i=0;i<n.length;i++){var o=n[i];"~"===o&&(o="\\textasciitilde"),a.push({type:"textord",mode:"text",text:o})}var s={type:"text",mode:r.mode,font:"\\texttt",body:a};return{type:"href",mode:r.mode,href:n,body:_o(s)}}}),co({type:"hbox",names:["\\hbox"],props:{numArgs:1,argTypes:["text"],allowedInText:!0,primitive:!0},handler(e,t){var{parser:r}=e;return{type:"hbox",mode:r.mode,body:_o(t[0])}},htmlBuilder(e,t){var r=bo(e.body,t,!1);return eo.makeFragment(r)},mathmlBuilder:(e,t)=>new wo.MathNode("mrow",Po(e.body,t))}),co({type:"html",names:["\\htmlClass","\\htmlId","\\htmlStyle","\\htmlData"],props:{numArgs:2,argTypes:["raw","original"],allowedInText:!0},handler:(e,t)=>{var r,{parser:n,funcName:a,token:i}=e,o=Wo(t[0],"raw").string,s=t[1];n.settings.strict&&n.settings.reportNonstrict("htmlExtension","HTML extension is disabled on strict mode");var l={};switch(a){case"\\htmlClass":l.class=o,r={command:"\\htmlClass",class:o};break;case"\\htmlId":l.id=o,r={command:"\\htmlId",id:o};break;case"\\htmlStyle":l.style=o,r={command:"\\htmlStyle",style:o};break;case"\\htmlData":for(var c=o.split(","),d=0;d<c.length;d++){var u=c[d],p=u.indexOf("=");if(p<0)throw new sa("\\htmlData key/value '"+u+"' missing equals sign");var _=u.slice(0,p),m=u.slice(p+1);l["data-"+_.trim()]=m}r={command:"\\htmlData",attributes:l};break;default:throw new Error("Unrecognized html command")}return n.settings.isTrusted(r)?{type:"html",mode:n.mode,attributes:l,body:_o(s)}:n.formatUnsupportedCmd(a)},htmlBuilder:(e,t)=>{var r=bo(e.body,t,!1),n=["enclosing"];e.attributes.class&&n.push(...e.attributes.class.trim().split(/\s+/));var a=eo.makeSpan(n,r,t);for(var i in e.attributes)"class"!==i&&e.attributes.hasOwnProperty(i)&&a.setAttribute(i,e.attributes[i]);return a},mathmlBuilder:(e,t)=>Fo(e.body,t)}),co({type:"htmlmathml",names:["\\html@mathml"],props:{numArgs:2,allowedInText:!0},handler:(e,t)=>{var{parser:r}=e;return{type:"htmlmathml",mode:r.mode,html:_o(t[0]),mathml:_o(t[1])}},htmlBuilder:(e,t)=>{var r=bo(e.html,t,!1);return eo.makeFragment(r)},mathmlBuilder:(e,t)=>Fo(e.mathml,t)});var pl=function(e){if(/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(e))return{number:+e,unit:"bp"};var t=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(e);if(!t)throw new sa("Invalid size: '"+e+"' in \\includegraphics");var r={number:+(t[1]+t[2]),unit:t[3]};if(!Ya(r))throw new sa("Invalid unit: '"+r.unit+"' in \\includegraphics.");return r};co({type:"includegraphics",names:["\\includegraphics"],props:{numArgs:1,numOptionalArgs:1,argTypes:["raw","url"],allowedInText:!1},handler:(e,t,r)=>{var{parser:n}=e,a={number:0,unit:"em"},i={number:.9,unit:"em"},o={number:0,unit:"em"},s="";if(r[0])for(var l=Wo(r[0],"raw").string.split(","),c=0;c<l.length;c++){var d=l[c].split("=");if(2===d.length){var u=d[1].trim();switch(d[0].trim()){case"alt":s=u;break;case"width":a=pl(u);break;case"height":i=pl(u);break;case"totalheight":o=pl(u);break;default:throw new sa("Invalid key: '"+d[0]+"' in \\includegraphics.")}}}var p=Wo(t[0],"url").url;return""===s&&(s=(s=(s=p).replace(/^.*[\\/]/,"")).substring(0,s.lastIndexOf("."))),n.settings.isTrusted({command:"\\includegraphics",url:p})?{type:"includegraphics",mode:n.mode,alt:s,width:a,height:i,totalheight:o,src:p}:n.formatUnsupportedCmd("\\includegraphics")},htmlBuilder:(e,t)=>{var r=qa(e.height,t),n=0;e.totalheight.number>0&&(n=qa(e.totalheight,t)-r);var a=0;e.width.number>0&&(a=qa(e.width,t));var i={height:Ha(r+n)};a>0&&(i.width=Ha(a)),n>0&&(i.verticalAlign=Ha(-n));var o=new Za(e.src,e.alt,i);return o.height=r,o.depth=n,o},mathmlBuilder:(e,t)=>{var r=new wo.MathNode("mglyph",[]);r.setAttribute("alt",e.alt);var n=qa(e.height,t),a=0;if(e.totalheight.number>0&&(a=qa(e.totalheight,t)-n,r.setAttribute("valign",Ha(-a))),r.setAttribute("height",Ha(n+a)),e.width.number>0){var i=qa(e.width,t);r.setAttribute("width",Ha(i))}return r.setAttribute("src",e.src),r}}),co({type:"kern",names:["\\kern","\\mkern","\\hskip","\\mskip"],props:{numArgs:1,argTypes:["size"],primitive:!0,allowedInText:!0},handler(e,t){var{parser:r,funcName:n}=e,a=Wo(t[0],"size");if(r.settings.strict){var i="m"===n[1],o="mu"===a.value.unit;i?(o||r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+n+" supports only mu units, not "+a.value.unit+" units"),"math"!==r.mode&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+n+" works only in math mode")):o&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+n+" doesn't support mu units")}return{type:"kern",mode:r.mode,dimension:a.value}},htmlBuilder:(e,t)=>eo.makeGlue(e.dimension,t),mathmlBuilder(e,t){var r=qa(e.dimension,t);return new wo.SpaceNode(r)}}),co({type:"lap",names:["\\mathllap","\\mathrlap","\\mathclap"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{var{parser:r,funcName:n}=e,a=t[0];return{type:"lap",mode:r.mode,alignment:n.slice(5),body:a}},htmlBuilder:(e,t)=>{var r;"clap"===e.alignment?(r=eo.makeSpan([],[No(e.body,t)]),r=eo.makeSpan(["inner"],[r],t)):r=eo.makeSpan(["inner"],[No(e.body,t)]);var n=eo.makeSpan(["fix"],[]),a=eo.makeSpan([e.alignment],[r,n],t),i=eo.makeSpan(["strut"]);return i.style.height=Ha(a.height+a.depth),a.depth&&(i.style.verticalAlign=Ha(-a.depth)),a.children.unshift(i),a=eo.makeSpan(["thinbox"],[a],t),eo.makeSpan(["mord","vbox"],[a],t)},mathmlBuilder:(e,t)=>{var r=new wo.MathNode("mpadded",[Bo(e.body,t)]);if("rlap"!==e.alignment){var n="llap"===e.alignment?"-1":"-0.5";r.setAttribute("lspace",n+"width")}return r.setAttribute("width","0px"),r}}),co({type:"styling",names:["\\(","$"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(e,t){var{funcName:r,parser:n}=e,a=n.mode;n.switchMode("math");var i="\\("===r?"\\)":"$",o=n.parseExpression(!1,i);return n.expect(i),n.switchMode(a),{type:"styling",mode:n.mode,style:"text",body:o}}}),co({type:"text",names:["\\)","\\]"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(e,t){throw new sa("Mismatched "+e.funcName)}});var _l=(e,t)=>{switch(t.style.size){case Ca.DISPLAY.size:return e.display;case Ca.TEXT.size:return e.text;case Ca.SCRIPT.size:return e.script;case Ca.SCRIPTSCRIPT.size:return e.scriptscript;default:return e.text}};co({type:"mathchoice",names:["\\mathchoice"],props:{numArgs:4,primitive:!0},handler:(e,t)=>{var{parser:r}=e;return{type:"mathchoice",mode:r.mode,display:_o(t[0]),text:_o(t[1]),script:_o(t[2]),scriptscript:_o(t[3])}},htmlBuilder:(e,t)=>{var r=_l(e,t),n=bo(r,t,!1);return eo.makeFragment(n)},mathmlBuilder:(e,t)=>{var r=_l(e,t);return Fo(r,t)}});var ml=(e,t,r,n,a,i,o)=>{e=eo.makeSpan([],[e]);var s,l,c,d=r&&pa.isCharacterBox(r);if(t){var u=No(t,n.havingStyle(a.sup()),n);l={elem:u,kern:Math.max(n.fontMetrics().bigOpSpacing1,n.fontMetrics().bigOpSpacing3-u.depth)}}if(r){var p=No(r,n.havingStyle(a.sub()),n);s={elem:p,kern:Math.max(n.fontMetrics().bigOpSpacing2,n.fontMetrics().bigOpSpacing4-p.height)}}if(l&&s){var _=n.fontMetrics().bigOpSpacing5+s.elem.height+s.elem.depth+s.kern+e.depth+o;c=eo.makeVList({positionType:"bottom",positionData:_,children:[{type:"kern",size:n.fontMetrics().bigOpSpacing5},{type:"elem",elem:s.elem,marginLeft:Ha(-i)},{type:"kern",size:s.kern},{type:"elem",elem:e},{type:"kern",size:l.kern},{type:"elem",elem:l.elem,marginLeft:Ha(i)},{type:"kern",size:n.fontMetrics().bigOpSpacing5}]},n)}else if(s){var m=e.height-o;c=eo.makeVList({positionType:"top",positionData:m,children:[{type:"kern",size:n.fontMetrics().bigOpSpacing5},{type:"elem",elem:s.elem,marginLeft:Ha(-i)},{type:"kern",size:s.kern},{type:"elem",elem:e}]},n)}else{if(!l)return e;var g=e.depth+o;c=eo.makeVList({positionType:"bottom",positionData:g,children:[{type:"elem",elem:e},{type:"kern",size:l.kern},{type:"elem",elem:l.elem,marginLeft:Ha(i)},{type:"kern",size:n.fontMetrics().bigOpSpacing5}]},n)}var h=[c];if(s&&0!==i&&!d){var f=eo.makeSpan(["mspace"],[],n);f.style.marginRight=Ha(i),h.unshift(f)}return eo.makeSpan(["mop","op-limits"],h,n)},gl=["\\smallint"],hl=(e,t)=>{var r,n,a,i=!1;"supsub"===e.type?(r=e.sup,n=e.sub,a=Wo(e.base,"op"),i=!0):a=Wo(e,"op");var o,s=t.style,l=!1;if(s.size===Ca.DISPLAY.size&&a.symbol&&!gl.includes(a.name)&&(l=!0),a.symbol){var c=l?"Size2-Regular":"Size1-Regular",d="";if("\\oiint"!==a.name&&"\\oiiint"!==a.name||(d=a.name.slice(1),a.name="oiint"===d?"\\iint":"\\iiint"),o=eo.makeSymbol(a.name,c,"math",t,["mop","op-symbol",l?"large-op":"small-op"]),d.length>0){var u=o.italic,p=eo.staticSvg(d+"Size"+(l?"2":"1"),t);o=eo.makeVList({positionType:"individualShift",children:[{type:"elem",elem:o,shift:0},{type:"elem",elem:p,shift:l?.08:0}]},t),a.name="\\"+d,o.classes.unshift("mop"),o.italic=u}}else if(a.body){var _=bo(a.body,t,!0);1===_.length&&_[0]instanceof ei?(o=_[0]).classes[0]="mop":o=eo.makeSpan(["mop"],_,t)}else{for(var m=[],g=1;g<a.name.length;g++)m.push(eo.mathsym(a.name[g],a.mode,t));o=eo.makeSpan(["mop"],m,t)}var h=0,f=0;return(o instanceof ei||"\\oiint"===a.name||"\\oiiint"===a.name)&&!a.suppressBaseShift&&(h=(o.height-o.depth)/2-t.fontMetrics().axisHeight,f=o.italic),i?ml(o,r,n,t,s,f,h):(h&&(o.style.position="relative",o.style.top=Ha(h)),o)},fl=(e,t)=>{var r;if(e.symbol)r=new Io("mo",[Do(e.name,e.mode)]),gl.includes(e.name)&&r.setAttribute("largeop","false");else if(e.body)r=new Io("mo",Po(e.body,t));else{r=new Io("mi",[new xo(e.name.slice(1))]);var n=new Io("mo",[Do("⁡","text")]);r=e.parentIsSupSub?new Io("mrow",[r,n]):Oo([r,n])}return r},El={"∏":"\\prod","∐":"\\coprod","∑":"\\sum","⋀":"\\bigwedge","⋁":"\\bigvee","⋂":"\\bigcap","⋃":"\\bigcup","⨀":"\\bigodot","⨁":"\\bigoplus","⨂":"\\bigotimes","⨄":"\\biguplus","⨆":"\\bigsqcup"};co({type:"op",names:["\\coprod","\\bigvee","\\bigwedge","\\biguplus","\\bigcap","\\bigcup","\\intop","\\prod","\\sum","\\bigotimes","\\bigoplus","\\bigodot","\\bigsqcup","\\smallint","∏","∐","∑","⋀","⋁","⋂","⋃","⨀","⨁","⨂","⨄","⨆"],props:{numArgs:0},handler:(e,t)=>{var{parser:r,funcName:n}=e,a=n;return 1===a.length&&(a=El[a]),{type:"op",mode:r.mode,limits:!0,parentIsSupSub:!1,symbol:!0,name:a}},htmlBuilder:hl,mathmlBuilder:fl}),co({type:"op",names:["\\mathop"],props:{numArgs:1,primitive:!0},handler:(e,t)=>{var{parser:r}=e,n=t[0];return{type:"op",mode:r.mode,limits:!1,parentIsSupSub:!1,symbol:!1,body:_o(n)}},htmlBuilder:hl,mathmlBuilder:fl});var bl={"∫":"\\int","∬":"\\iint","∭":"\\iiint","∮":"\\oint","∯":"\\oiint","∰":"\\oiiint"};co({type:"op",names:["\\arcsin","\\arccos","\\arctan","\\arctg","\\arcctg","\\arg","\\ch","\\cos","\\cosec","\\cosh","\\cot","\\cotg","\\coth","\\csc","\\ctg","\\cth","\\deg","\\dim","\\exp","\\hom","\\ker","\\lg","\\ln","\\log","\\sec","\\sin","\\sinh","\\sh","\\tan","\\tanh","\\tg","\\th"],props:{numArgs:0},handler(e){var{parser:t,funcName:r}=e;return{type:"op",mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!1,name:r}},htmlBuilder:hl,mathmlBuilder:fl}),co({type:"op",names:["\\det","\\gcd","\\inf","\\lim","\\max","\\min","\\Pr","\\sup"],props:{numArgs:0},handler(e){var{parser:t,funcName:r}=e;return{type:"op",mode:t.mode,limits:!0,parentIsSupSub:!1,symbol:!1,name:r}},htmlBuilder:hl,mathmlBuilder:fl}),co({type:"op",names:["\\int","\\iint","\\iiint","\\oint","\\oiint","\\oiiint","∫","∬","∭","∮","∯","∰"],props:{numArgs:0,allowedInArgument:!0},handler(e){var{parser:t,funcName:r}=e,n=r;return 1===n.length&&(n=bl[n]),{type:"op",mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!0,name:n}},htmlBuilder:hl,mathmlBuilder:fl});var Sl=(e,t)=>{var r,n,a,i,o=!1;if("supsub"===e.type?(r=e.sup,n=e.sub,a=Wo(e.base,"operatorname"),o=!0):a=Wo(e,"operatorname"),a.body.length>0){for(var s=a.body.map(e=>{var t=e.text;return"string"==typeof t?{type:"textord",mode:e.mode,text:t}:e}),l=bo(s,t.withFont("mathrm"),!0),c=0;c<l.length;c++){var d=l[c];d instanceof ei&&(d.text=d.text.replace(/\u2212/,"-").replace(/\u2217/,"*"))}i=eo.makeSpan(["mop"],l,t)}else i=eo.makeSpan(["mop"],[],t);return o?ml(i,r,n,t,t.style,0,0):i};function vl(e,t,r){for(var n=bo(e,t,!1),a=t.sizeMultiplier/r.sizeMultiplier,i=0;i<n.length;i++){var o=n[i].classes.indexOf("sizing");o<0?Array.prototype.push.apply(n[i].classes,t.sizingClasses(r)):n[i].classes[o+1]==="reset-size"+t.size&&(n[i].classes[o+1]="reset-size"+r.size),n[i].height*=a,n[i].depth*=a}return eo.makeFragment(n)}co({type:"operatorname",names:["\\operatorname@","\\operatornamewithlimits"],props:{numArgs:1},handler:(e,t)=>{var{parser:r,funcName:n}=e,a=t[0];return{type:"operatorname",mode:r.mode,body:_o(a),alwaysHandleSupSub:"\\operatornamewithlimits"===n,limits:!1,parentIsSupSub:!1}},htmlBuilder:Sl,mathmlBuilder:(e,t)=>{for(var r=Po(e.body,t.withFont("mathrm")),n=!0,a=0;a<r.length;a++){var i=r[a];if(i instanceof wo.SpaceNode);else if(i instanceof wo.MathNode)switch(i.type){case"mi":case"mn":case"ms":case"mspace":case"mtext":break;case"mo":var o=i.children[0];1===i.children.length&&o instanceof wo.TextNode?o.text=o.text.replace(/\u2212/,"-").replace(/\u2217/,"*"):n=!1;break;default:n=!1}else n=!1}if(n){var s=r.map(e=>e.toText()).join("");r=[new wo.TextNode(s)]}var l=new wo.MathNode("mi",r);l.setAttribute("mathvariant","normal");var c=new wo.MathNode("mo",[Do("⁡","text")]);return e.parentIsSupSub?new wo.MathNode("mrow",[l,c]):wo.newDocumentFragment([l,c])}}),$s("\\operatorname","\\@ifstar\\operatornamewithlimits\\operatorname@"),uo({type:"ordgroup",htmlBuilder:(e,t)=>e.semisimple?eo.makeFragment(bo(e.body,t,!1)):eo.makeSpan(["mord"],bo(e.body,t,!0),t),mathmlBuilder:(e,t)=>Fo(e.body,t,!0)}),co({type:"overline",names:["\\overline"],props:{numArgs:1},handler(e,t){var{parser:r}=e,n=t[0];return{type:"overline",mode:r.mode,body:n}},htmlBuilder(e,t){var r=No(e.body,t.havingCrampedStyle()),n=eo.makeLineSpan("overline-line",t),a=t.fontMetrics().defaultRuleThickness,i=eo.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r},{type:"kern",size:3*a},{type:"elem",elem:n},{type:"kern",size:a}]},t);return eo.makeSpan(["mord","overline"],[i],t)},mathmlBuilder(e,t){var r=new wo.MathNode("mo",[new wo.TextNode("‾")]);r.setAttribute("stretchy","true");var n=new wo.MathNode("mover",[Bo(e.body,t),r]);return n.setAttribute("accent","true"),n}}),co({type:"phantom",names:["\\phantom"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{var{parser:r}=e,n=t[0];return{type:"phantom",mode:r.mode,body:_o(n)}},htmlBuilder:(e,t)=>{var r=bo(e.body,t.withPhantom(),!1);return eo.makeFragment(r)},mathmlBuilder:(e,t)=>{var r=Po(e.body,t);return new wo.MathNode("mphantom",r)}}),co({type:"hphantom",names:["\\hphantom"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{var{parser:r}=e,n=t[0];return{type:"hphantom",mode:r.mode,body:n}},htmlBuilder:(e,t)=>{var r=eo.makeSpan([],[No(e.body,t.withPhantom())]);if(r.height=0,r.depth=0,r.children)for(var n=0;n<r.children.length;n++)r.children[n].height=0,r.children[n].depth=0;return r=eo.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r}]},t),eo.makeSpan(["mord"],[r],t)},mathmlBuilder:(e,t)=>{var r=Po(_o(e.body),t),n=new wo.MathNode("mphantom",r),a=new wo.MathNode("mpadded",[n]);return a.setAttribute("height","0px"),a.setAttribute("depth","0px"),a}}),co({type:"vphantom",names:["\\vphantom"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{var{parser:r}=e,n=t[0];return{type:"vphantom",mode:r.mode,body:n}},htmlBuilder:(e,t)=>{var r=eo.makeSpan(["inner"],[No(e.body,t.withPhantom())]),n=eo.makeSpan(["fix"],[]);return eo.makeSpan(["mord","rlap"],[r,n],t)},mathmlBuilder:(e,t)=>{var r=Po(_o(e.body),t),n=new wo.MathNode("mphantom",r),a=new wo.MathNode("mpadded",[n]);return a.setAttribute("width","0px"),a}}),co({type:"raisebox",names:["\\raisebox"],props:{numArgs:2,argTypes:["size","hbox"],allowedInText:!0},handler(e,t){var{parser:r}=e,n=Wo(t[0],"size").value,a=t[1];return{type:"raisebox",mode:r.mode,dy:n,body:a}},htmlBuilder(e,t){var r=No(e.body,t),n=qa(e.dy,t);return eo.makeVList({positionType:"shift",positionData:-n,children:[{type:"elem",elem:r}]},t)},mathmlBuilder(e,t){var r=new wo.MathNode("mpadded",[Bo(e.body,t)]),n=e.dy.number+e.dy.unit;return r.setAttribute("voffset",n),r}}),co({type:"internal",names:["\\relax"],props:{numArgs:0,allowedInText:!0,allowedInArgument:!0},handler(e){var{parser:t}=e;return{type:"internal",mode:t.mode}}}),co({type:"rule",names:["\\rule"],props:{numArgs:2,numOptionalArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["size","size","size"]},handler(e,t,r){var{parser:n}=e,a=r[0],i=Wo(t[0],"size"),o=Wo(t[1],"size");return{type:"rule",mode:n.mode,shift:a&&Wo(a,"size").value,width:i.value,height:o.value}},htmlBuilder(e,t){var r=eo.makeSpan(["mord","rule"],[],t),n=qa(e.width,t),a=qa(e.height,t),i=e.shift?qa(e.shift,t):0;return r.style.borderRightWidth=Ha(n),r.style.borderTopWidth=Ha(a),r.style.bottom=Ha(i),r.width=n,r.height=a+i,r.depth=-i,r.maxFontSize=1.125*a*t.sizeMultiplier,r},mathmlBuilder(e,t){var r=qa(e.width,t),n=qa(e.height,t),a=e.shift?qa(e.shift,t):0,i=t.color&&t.getColor()||"black",o=new wo.MathNode("mspace");o.setAttribute("mathbackground",i),o.setAttribute("width",Ha(r)),o.setAttribute("height",Ha(n));var s=new wo.MathNode("mpadded",[o]);return a>=0?s.setAttribute("height",Ha(a)):(s.setAttribute("height",Ha(a)),s.setAttribute("depth",Ha(-a))),s.setAttribute("voffset",Ha(a)),s}});var Tl=["\\tiny","\\sixptsize","\\scriptsize","\\footnotesize","\\small","\\normalsize","\\large","\\Large","\\LARGE","\\huge","\\Huge"];co({type:"sizing",names:Tl,props:{numArgs:0,allowedInText:!0},handler:(e,t)=>{var{breakOnTokenText:r,funcName:n,parser:a}=e,i=a.parseExpression(!1,r);return{type:"sizing",mode:a.mode,size:Tl.indexOf(n)+1,body:i}},htmlBuilder:(e,t)=>{var r=t.havingSize(e.size);return vl(e.body,r,t)},mathmlBuilder:(e,t)=>{var r=t.havingSize(e.size),n=Po(e.body,r),a=new wo.MathNode("mstyle",n);return a.setAttribute("mathsize",Ha(r.sizeMultiplier)),a}}),co({type:"smash",names:["\\smash"],props:{numArgs:1,numOptionalArgs:1,allowedInText:!0},handler:(e,t,r)=>{var{parser:n}=e,a=!1,i=!1,o=r[0]&&Wo(r[0],"ordgroup");if(o)for(var s="",l=0;l<o.body.length;++l){if("t"===(s=o.body[l].text))a=!0;else{if("b"!==s){a=!1,i=!1;break}i=!0}}else a=!0,i=!0;var c=t[0];return{type:"smash",mode:n.mode,body:c,smashHeight:a,smashDepth:i}},htmlBuilder:(e,t)=>{var r=eo.makeSpan([],[No(e.body,t)]);if(!e.smashHeight&&!e.smashDepth)return r;if(e.smashHeight&&(r.height=0,r.children))for(var n=0;n<r.children.length;n++)r.children[n].height=0;if(e.smashDepth&&(r.depth=0,r.children))for(var a=0;a<r.children.length;a++)r.children[a].depth=0;var i=eo.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r}]},t);return eo.makeSpan(["mord"],[i],t)},mathmlBuilder:(e,t)=>{var r=new wo.MathNode("mpadded",[Bo(e.body,t)]);return e.smashHeight&&r.setAttribute("height","0px"),e.smashDepth&&r.setAttribute("depth","0px"),r}}),co({type:"sqrt",names:["\\sqrt"],props:{numArgs:1,numOptionalArgs:1},handler(e,t,r){var{parser:n}=e,a=r[0],i=t[0];return{type:"sqrt",mode:n.mode,body:i,index:a}},htmlBuilder(e,t){var r=No(e.body,t.havingCrampedStyle());0===r.height&&(r.height=t.fontMetrics().xHeight),r=eo.wrapFragment(r,t);var n=t.fontMetrics().defaultRuleThickness,a=n;t.style.id<Ca.TEXT.id&&(a=t.fontMetrics().xHeight);var i=n+a/4,o=r.height+r.depth+i+n,{span:s,ruleWidth:l,advanceWidth:c}=Ps.sqrtImage(o,t),d=s.height-l;d>r.height+r.depth+i&&(i=(i+d-r.height-r.depth)/2);var u=s.height-r.height-i-l;r.style.paddingLeft=Ha(c);var p=eo.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r,wrapperClasses:["svg-align"]},{type:"kern",size:-(r.height+u)},{type:"elem",elem:s},{type:"kern",size:l}]},t);if(e.index){var _=t.havingStyle(Ca.SCRIPTSCRIPT),m=No(e.index,_,t),g=.6*(p.height-p.depth),h=eo.makeVList({positionType:"shift",positionData:-g,children:[{type:"elem",elem:m}]},t),f=eo.makeSpan(["root"],[h]);return eo.makeSpan(["mord","sqrt"],[f,p],t)}return eo.makeSpan(["mord","sqrt"],[p],t)},mathmlBuilder(e,t){var{body:r,index:n}=e;return n?new wo.MathNode("mroot",[Bo(r,t),Bo(n,t)]):new wo.MathNode("msqrt",[Bo(r,t)])}});var yl={display:Ca.DISPLAY,text:Ca.TEXT,script:Ca.SCRIPT,scriptscript:Ca.SCRIPTSCRIPT};co({type:"styling",names:["\\displaystyle","\\textstyle","\\scriptstyle","\\scriptscriptstyle"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e,t){var{breakOnTokenText:r,funcName:n,parser:a}=e,i=a.parseExpression(!0,r),o=n.slice(1,n.length-5);return{type:"styling",mode:a.mode,style:o,body:i}},htmlBuilder(e,t){var r=yl[e.style],n=t.havingStyle(r).withFont("");return vl(e.body,n,t)},mathmlBuilder(e,t){var r=yl[e.style],n=t.havingStyle(r),a=Po(e.body,n),i=new wo.MathNode("mstyle",a),o={display:["0","true"],text:["0","false"],script:["1","false"],scriptscript:["2","false"]}[e.style];return i.setAttribute("scriptlevel",o[0]),i.setAttribute("displaystyle",o[1]),i}});uo({type:"supsub",htmlBuilder(e,t){var r=function(e,t){var r=e.base;return r?"op"===r.type?r.limits&&(t.style.size===Ca.DISPLAY.size||r.alwaysHandleSupSub)?hl:null:"operatorname"===r.type?r.alwaysHandleSupSub&&(t.style.size===Ca.DISPLAY.size||r.limits)?Sl:null:"accent"===r.type?pa.isCharacterBox(r.base)?Ko:null:"horizBrace"===r.type&&!e.sub===r.isOver?ul:null:null}(e,t);if(r)return r(e,t);var n,a,i,{base:o,sup:s,sub:l}=e,c=No(o,t),d=t.fontMetrics(),u=0,p=0,_=o&&pa.isCharacterBox(o);if(s){var m=t.havingStyle(t.style.sup());n=No(s,m,t),_||(u=c.height-m.fontMetrics().supDrop*m.sizeMultiplier/t.sizeMultiplier)}if(l){var g=t.havingStyle(t.style.sub());a=No(l,g,t),_||(p=c.depth+g.fontMetrics().subDrop*g.sizeMultiplier/t.sizeMultiplier)}i=t.style===Ca.DISPLAY?d.sup1:t.style.cramped?d.sup3:d.sup2;var h,f=t.sizeMultiplier,E=Ha(.5/d.ptPerEm/f),b=null;if(a){var S=e.base&&"op"===e.base.type&&e.base.name&&("\\oiint"===e.base.name||"\\oiiint"===e.base.name);(c instanceof ei||S)&&(b=Ha(-c.italic))}if(n&&a){u=Math.max(u,i,n.depth+.25*d.xHeight),p=Math.max(p,d.sub2);var v=4*d.defaultRuleThickness;if(u-n.depth-(a.height-p)<v){p=v-(u-n.depth)+a.height;var T=.8*d.xHeight-(u-n.depth);T>0&&(u+=T,p-=T)}var y=[{type:"elem",elem:a,shift:p,marginRight:E,marginLeft:b},{type:"elem",elem:n,shift:-u,marginRight:E}];h=eo.makeVList({positionType:"individualShift",children:y},t)}else if(a){p=Math.max(p,d.sub1,a.height-.8*d.xHeight);var C=[{type:"elem",elem:a,marginLeft:b,marginRight:E}];h=eo.makeVList({positionType:"shift",positionData:p,children:C},t)}else{if(!n)throw new Error("supsub must have either sup or sub.");u=Math.max(u,i,n.depth+.25*d.xHeight),h=eo.makeVList({positionType:"shift",positionData:-u,children:[{type:"elem",elem:n,marginRight:E}]},t)}var N=yo(c,"right")||"mord";return eo.makeSpan([N],[c,eo.makeSpan(["msupsub"],[h])],t)},mathmlBuilder(e,t){var r,n=!1;e.base&&"horizBrace"===e.base.type&&!!e.sup===e.base.isOver&&(n=!0,r=e.base.isOver),!e.base||"op"!==e.base.type&&"operatorname"!==e.base.type||(e.base.parentIsSupSub=!0);var a,i=[Bo(e.base,t)];if(e.sub&&i.push(Bo(e.sub,t)),e.sup&&i.push(Bo(e.sup,t)),n)a=r?"mover":"munder";else if(e.sub)if(e.sup){var o=e.base;a=o&&"op"===o.type&&o.limits&&t.style===Ca.DISPLAY||o&&"operatorname"===o.type&&o.alwaysHandleSupSub&&(t.style===Ca.DISPLAY||o.limits)?"munderover":"msubsup"}else{var s=e.base;a=s&&"op"===s.type&&s.limits&&(t.style===Ca.DISPLAY||s.alwaysHandleSupSub)||s&&"operatorname"===s.type&&s.alwaysHandleSupSub&&(s.limits||t.style===Ca.DISPLAY)?"munder":"msub"}else{var l=e.base;a=l&&"op"===l.type&&l.limits&&(t.style===Ca.DISPLAY||l.alwaysHandleSupSub)||l&&"operatorname"===l.type&&l.alwaysHandleSupSub&&(l.limits||t.style===Ca.DISPLAY)?"mover":"msup"}return new wo.MathNode(a,i)}}),uo({type:"atom",htmlBuilder:(e,t)=>eo.mathsym(e.text,e.mode,t,["m"+e.family]),mathmlBuilder(e,t){var r=new wo.MathNode("mo",[Do(e.text,e.mode)]);if("bin"===e.family){var n=ko(e,t);"bold-italic"===n&&r.setAttribute("mathvariant",n)}else"punct"===e.family?r.setAttribute("separator","true"):"open"!==e.family&&"close"!==e.family||r.setAttribute("stretchy","false");return r}});var Cl={mi:"italic",mn:"normal",mtext:"normal"};uo({type:"mathord",htmlBuilder:(e,t)=>eo.makeOrd(e,t,"mathord"),mathmlBuilder(e,t){var r=new wo.MathNode("mi",[Do(e.text,e.mode,t)]),n=ko(e,t)||"italic";return n!==Cl[r.type]&&r.setAttribute("mathvariant",n),r}}),uo({type:"textord",htmlBuilder:(e,t)=>eo.makeOrd(e,t,"textord"),mathmlBuilder(e,t){var r,n=Do(e.text,e.mode,t),a=ko(e,t)||"normal";return r="text"===e.mode?new wo.MathNode("mtext",[n]):/[0-9]/.test(e.text)?new wo.MathNode("mn",[n]):"\\prime"===e.text?new wo.MathNode("mo",[n]):new wo.MathNode("mi",[n]),a!==Cl[r.type]&&r.setAttribute("mathvariant",a),r}});var Nl={"\\nobreak":"nobreak","\\allowbreak":"allowbreak"},Rl={" ":{},"\\ ":{},"~":{className:"nobreak"},"\\space":{},"\\nobreakspace":{className:"nobreak"}};uo({type:"spacing",htmlBuilder(e,t){if(Rl.hasOwnProperty(e.text)){var r=Rl[e.text].className||"";if("text"===e.mode){var n=eo.makeOrd(e,t,"textord");return n.classes.push(r),n}return eo.makeSpan(["mspace",r],[eo.mathsym(e.text,e.mode,t)],t)}if(Nl.hasOwnProperty(e.text))return eo.makeSpan(["mspace",Nl[e.text]],[],t);throw new sa('Unknown type of space "'+e.text+'"')},mathmlBuilder(e,t){if(!Rl.hasOwnProperty(e.text)){if(Nl.hasOwnProperty(e.text))return new wo.MathNode("mspace");throw new sa('Unknown type of space "'+e.text+'"')}return new wo.MathNode("mtext",[new wo.TextNode(" ")])}});var Al=()=>{var e=new wo.MathNode("mtd",[]);return e.setAttribute("width","50%"),e};uo({type:"tag",mathmlBuilder(e,t){var r=new wo.MathNode("mtable",[new wo.MathNode("mtr",[Al(),new wo.MathNode("mtd",[Fo(e.body,t)]),Al(),new wo.MathNode("mtd",[Fo(e.tag,t)])])]);return r.setAttribute("width","100%"),r}});var Ol={"\\text":void 0,"\\textrm":"textrm","\\textsf":"textsf","\\texttt":"texttt","\\textnormal":"textrm"},Il={"\\textbf":"textbf","\\textmd":"textmd"},xl={"\\textit":"textit","\\textup":"textup"},wl=(e,t)=>{var r=e.font;return r?Ol[r]?t.withTextFontFamily(Ol[r]):Il[r]?t.withTextFontWeight(Il[r]):"\\emph"===r?"textit"===t.fontShape?t.withTextFontShape("textup"):t.withTextFontShape("textit"):t.withTextFontShape(xl[r]):t};co({type:"text",names:["\\text","\\textrm","\\textsf","\\texttt","\\textnormal","\\textbf","\\textmd","\\textit","\\textup","\\emph"],props:{numArgs:1,argTypes:["text"],allowedInArgument:!0,allowedInText:!0},handler(e,t){var{parser:r,funcName:n}=e,a=t[0];return{type:"text",mode:r.mode,body:_o(a),font:n}},htmlBuilder(e,t){var r=wl(e,t),n=bo(e.body,r,!0);return eo.makeSpan(["mord","text"],n,r)},mathmlBuilder(e,t){var r=wl(e,t);return Fo(e.body,r)}}),co({type:"underline",names:["\\underline"],props:{numArgs:1,allowedInText:!0},handler(e,t){var{parser:r}=e;return{type:"underline",mode:r.mode,body:t[0]}},htmlBuilder(e,t){var r=No(e.body,t),n=eo.makeLineSpan("underline-line",t),a=t.fontMetrics().defaultRuleThickness,i=eo.makeVList({positionType:"top",positionData:r.height,children:[{type:"kern",size:a},{type:"elem",elem:n},{type:"kern",size:3*a},{type:"elem",elem:r}]},t);return eo.makeSpan(["mord","underline"],[i],t)},mathmlBuilder(e,t){var r=new wo.MathNode("mo",[new wo.TextNode("‾")]);r.setAttribute("stretchy","true");var n=new wo.MathNode("munder",[Bo(e.body,t),r]);return n.setAttribute("accentunder","true"),n}}),co({type:"vcenter",names:["\\vcenter"],props:{numArgs:1,argTypes:["original"],allowedInText:!1},handler(e,t){var{parser:r}=e;return{type:"vcenter",mode:r.mode,body:t[0]}},htmlBuilder(e,t){var r=No(e.body,t),n=t.fontMetrics().axisHeight,a=.5*(r.height-n-(r.depth+n));return eo.makeVList({positionType:"shift",positionData:a,children:[{type:"elem",elem:r}]},t)},mathmlBuilder:(e,t)=>new wo.MathNode("mpadded",[Bo(e.body,t)],["vcenter"])}),co({type:"verb",names:["\\verb"],props:{numArgs:0,allowedInText:!0},handler(e,t,r){throw new sa("\\verb ended by end of line instead of matching delimiter")},htmlBuilder(e,t){for(var r=Dl(e),n=[],a=t.havingStyle(t.style.text()),i=0;i<r.length;i++){var o=r[i];"~"===o&&(o="\\textasciitilde"),n.push(eo.makeSymbol(o,"Typewriter-Regular",e.mode,a,["mord","texttt"]))}return eo.makeSpan(["mord","text"].concat(a.sizingClasses(t)),eo.tryCombineChars(n),a)},mathmlBuilder(e,t){var r=new wo.TextNode(Dl(e)),n=new wo.MathNode("mtext",[r]);return n.setAttribute("mathvariant","monospace"),n}});var Dl=e=>e.body.replace(/ /g,e.star?"␣":" "),Ml=oo,kl="[ \r\n\t]",Ll="(\\\\[a-zA-Z@]+)"+kl+"*",Pl="[̀-ͯ]",Fl=new RegExp(Pl+"+$"),Bl="("+kl+"+)|\\\\(\n|[ \r\t]+\n?)[ \r\t]*|([!-\\[\\]-‧‪-퟿豈-￿]"+Pl+"*|[\ud800-\udbff][\udc00-\udfff]"+Pl+"*|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5|"+Ll+"|\\\\[^\ud800-\udfff])";class Ul{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(Bl,"g"),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new oa("EOF",new ia(this,t,t));var r=this.tokenRegex.exec(e);if(null===r||r.index!==t)throw new sa("Unexpected character: '"+e[t]+"'",new oa(e[t],new ia(this,t,t+1)));var n=r[6]||r[3]||(r[2]?"\\ ":" ");if(14===this.catcodes[n]){var a=e.indexOf("\n",this.tokenRegex.lastIndex);return-1===a?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict("commentAtEnd","% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)")):this.tokenRegex.lastIndex=a+1,this.lex()}return new oa(n,new ia(this,t,this.tokenRegex.lastIndex))}}class Gl{constructor(e,t){void 0===e&&(e={}),void 0===t&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(0===this.undefStack.length)throw new sa("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");var e=this.undefStack.pop();for(var t in e)e.hasOwnProperty(t)&&(null==e[t]?delete this.current[t]:this.current[t]=e[t])}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return this.current.hasOwnProperty(e)||this.builtins.hasOwnProperty(e)}get(e){return this.current.hasOwnProperty(e)?this.current[e]:this.builtins[e]}set(e,t,r){if(void 0===r&&(r=!1),r){for(var n=0;n<this.undefStack.length;n++)delete this.undefStack[n][e];this.undefStack.length>0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var a=this.undefStack[this.undefStack.length-1];a&&!a.hasOwnProperty(e)&&(a[e]=this.current[e])}null==t?delete this.current[e]:this.current[e]=t}}var zl=Vs;$s("\\noexpand",function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),$s("\\expandafter",function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),$s("\\@firstoftwo",function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),$s("\\@secondoftwo",function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),$s("\\@ifnextchar",function(e){var t=e.consumeArgs(3);e.consumeSpaces();var r=e.future();return 1===t[0].length&&t[0][0].text===r.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),$s("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}"),$s("\\TextOrMath",function(e){var t=e.consumeArgs(2);return"text"===e.mode?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var Yl={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};$s("\\char",function(e){var t,r=e.popToken(),n="";if("'"===r.text)t=8,r=e.popToken();else if('"'===r.text)t=16,r=e.popToken();else if("`"===r.text)if("\\"===(r=e.popToken()).text[0])n=r.text.charCodeAt(1);else{if("EOF"===r.text)throw new sa("\\char` missing argument");n=r.text.charCodeAt(0)}else t=10;if(t){if(null==(n=Yl[r.text])||n>=t)throw new sa("Invalid base-"+t+" digit "+r.text);for(var a;null!=(a=Yl[e.future().text])&&a<t;)n*=t,n+=a,e.popToken()}return"\\@char{"+n+"}"});var ql=(e,t,r,n)=>{var a=e.consumeArg().tokens;if(1!==a.length)throw new sa("\\newcommand's first argument must be a macro name");var i=a[0].text,o=e.isDefined(i);if(o&&!t)throw new sa("\\newcommand{"+i+"} attempting to redefine "+i+"; use \\renewcommand");if(!o&&!r)throw new sa("\\renewcommand{"+i+"} when command "+i+" does not yet exist; use \\newcommand");var s=0;if(1===(a=e.consumeArg().tokens).length&&"["===a[0].text){for(var l="",c=e.expandNextToken();"]"!==c.text&&"EOF"!==c.text;)l+=c.text,c=e.expandNextToken();if(!l.match(/^\s*[0-9]+\s*$/))throw new sa("Invalid number of arguments: "+l);s=parseInt(l),a=e.consumeArg().tokens}return o&&n||e.macros.set(i,{tokens:a,numArgs:s}),""};$s("\\newcommand",e=>ql(e,!1,!0,!1)),$s("\\renewcommand",e=>ql(e,!0,!1,!1)),$s("\\providecommand",e=>ql(e,!0,!0,!0)),$s("\\message",e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join("")),""}),$s("\\errmessage",e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join("")),""}),$s("\\show",e=>{var t=e.popToken(),r=t.text;return console.log(t,e.macros.get(r),Ml[r],si.math[r],si.text[r]),""}),$s("\\bgroup","{"),$s("\\egroup","}"),$s("~","\\nobreakspace"),$s("\\lq","`"),$s("\\rq","'"),$s("\\aa","\\r a"),$s("\\AA","\\r A"),$s("\\textcopyright","\\html@mathml{\\textcircled{c}}{\\char`©}"),$s("\\copyright","\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}"),$s("\\textregistered","\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),$s("ℬ","\\mathscr{B}"),$s("ℰ","\\mathscr{E}"),$s("ℱ","\\mathscr{F}"),$s("ℋ","\\mathscr{H}"),$s("ℐ","\\mathscr{I}"),$s("ℒ","\\mathscr{L}"),$s("ℳ","\\mathscr{M}"),$s("ℛ","\\mathscr{R}"),$s("ℭ","\\mathfrak{C}"),$s("ℌ","\\mathfrak{H}"),$s("ℨ","\\mathfrak{Z}"),$s("\\Bbbk","\\Bbb{k}"),$s("·","\\cdotp"),$s("\\llap","\\mathllap{\\textrm{#1}}"),$s("\\rlap","\\mathrlap{\\textrm{#1}}"),$s("\\clap","\\mathclap{\\textrm{#1}}"),$s("\\mathstrut","\\vphantom{(}"),$s("\\underbar","\\underline{\\text{#1}}"),$s("\\not",'\\html@mathml{\\mathrel{\\mathrlap\\@not}}{\\char"338}'),$s("\\neq","\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`≠}}"),$s("\\ne","\\neq"),$s("≠","\\neq"),$s("\\notin","\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`∉}}"),$s("∉","\\notin"),$s("≘","\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`≘}}"),$s("≙","\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`≘}}"),$s("≚","\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`≚}}"),$s("≛","\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`≛}}"),$s("≝","\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`≝}}"),$s("≞","\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`≞}}"),$s("≟","\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`≟}}"),$s("⟂","\\perp"),$s("‼","\\mathclose{!\\mkern-0.8mu!}"),$s("∌","\\notni"),$s("⌜","\\ulcorner"),$s("⌝","\\urcorner"),$s("⌞","\\llcorner"),$s("⌟","\\lrcorner"),$s("©","\\copyright"),$s("®","\\textregistered"),$s("️","\\textregistered"),$s("\\ulcorner",'\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}'),$s("\\urcorner",'\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}'),$s("\\llcorner",'\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}'),$s("\\lrcorner",'\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}'),$s("\\vdots","{\\varvdots\\rule{0pt}{15pt}}"),$s("⋮","\\vdots"),$s("\\varGamma","\\mathit{\\Gamma}"),$s("\\varDelta","\\mathit{\\Delta}"),$s("\\varTheta","\\mathit{\\Theta}"),$s("\\varLambda","\\mathit{\\Lambda}"),$s("\\varXi","\\mathit{\\Xi}"),$s("\\varPi","\\mathit{\\Pi}"),$s("\\varSigma","\\mathit{\\Sigma}"),$s("\\varUpsilon","\\mathit{\\Upsilon}"),$s("\\varPhi","\\mathit{\\Phi}"),$s("\\varPsi","\\mathit{\\Psi}"),$s("\\varOmega","\\mathit{\\Omega}"),$s("\\substack","\\begin{subarray}{c}#1\\end{subarray}"),$s("\\colon","\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax"),$s("\\boxed","\\fbox{$\\displaystyle{#1}$}"),$s("\\iff","\\DOTSB\\;\\Longleftrightarrow\\;"),$s("\\implies","\\DOTSB\\;\\Longrightarrow\\;"),$s("\\impliedby","\\DOTSB\\;\\Longleftarrow\\;"),$s("\\dddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}"),$s("\\ddddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}");var Hl={",":"\\dotsc","\\not":"\\dotsb","+":"\\dotsb","=":"\\dotsb","<":"\\dotsb",">":"\\dotsb","-":"\\dotsb","*":"\\dotsb",":":"\\dotsb","\\DOTSB":"\\dotsb","\\coprod":"\\dotsb","\\bigvee":"\\dotsb","\\bigwedge":"\\dotsb","\\biguplus":"\\dotsb","\\bigcap":"\\dotsb","\\bigcup":"\\dotsb","\\prod":"\\dotsb","\\sum":"\\dotsb","\\bigotimes":"\\dotsb","\\bigoplus":"\\dotsb","\\bigodot":"\\dotsb","\\bigsqcup":"\\dotsb","\\And":"\\dotsb","\\longrightarrow":"\\dotsb","\\Longrightarrow":"\\dotsb","\\longleftarrow":"\\dotsb","\\Longleftarrow":"\\dotsb","\\longleftrightarrow":"\\dotsb","\\Longleftrightarrow":"\\dotsb","\\mapsto":"\\dotsb","\\longmapsto":"\\dotsb","\\hookrightarrow":"\\dotsb","\\doteq":"\\dotsb","\\mathbin":"\\dotsb","\\mathrel":"\\dotsb","\\relbar":"\\dotsb","\\Relbar":"\\dotsb","\\xrightarrow":"\\dotsb","\\xleftarrow":"\\dotsb","\\DOTSI":"\\dotsi","\\int":"\\dotsi","\\oint":"\\dotsi","\\iint":"\\dotsi","\\iiint":"\\dotsi","\\iiiint":"\\dotsi","\\idotsint":"\\dotsi","\\DOTSX":"\\dotsx"};$s("\\dots",function(e){var t="\\dotso",r=e.expandAfterFuture().text;return r in Hl?t=Hl[r]:("\\not"===r.slice(0,4)||r in si.math&&["bin","rel"].includes(si.math[r].group))&&(t="\\dotsb"),t});var Vl={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};$s("\\dotso",function(e){return e.future().text in Vl?"\\ldots\\,":"\\ldots"}),$s("\\dotsc",function(e){var t=e.future().text;return t in Vl&&","!==t?"\\ldots\\,":"\\ldots"}),$s("\\cdots",function(e){return e.future().text in Vl?"\\@cdots\\,":"\\@cdots"}),$s("\\dotsb","\\cdots"),$s("\\dotsm","\\cdots"),$s("\\dotsi","\\!\\cdots"),$s("\\dotsx","\\ldots\\,"),$s("\\DOTSI","\\relax"),$s("\\DOTSB","\\relax"),$s("\\DOTSX","\\relax"),$s("\\tmspace","\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax"),$s("\\,","\\tmspace+{3mu}{.1667em}"),$s("\\thinspace","\\,"),$s("\\>","\\mskip{4mu}"),$s("\\:","\\tmspace+{4mu}{.2222em}"),$s("\\medspace","\\:"),$s("\\;","\\tmspace+{5mu}{.2777em}"),$s("\\thickspace","\\;"),$s("\\!","\\tmspace-{3mu}{.1667em}"),$s("\\negthinspace","\\!"),$s("\\negmedspace","\\tmspace-{4mu}{.2222em}"),$s("\\negthickspace","\\tmspace-{5mu}{.277em}"),$s("\\enspace","\\kern.5em "),$s("\\enskip","\\hskip.5em\\relax"),$s("\\quad","\\hskip1em\\relax"),$s("\\qquad","\\hskip2em\\relax"),$s("\\tag","\\@ifstar\\tag@literal\\tag@paren"),$s("\\tag@paren","\\tag@literal{({#1})}"),$s("\\tag@literal",e=>{if(e.macros.get("\\df@tag"))throw new sa("Multiple \\tag");return"\\gdef\\df@tag{\\text{#1}}"}),$s("\\bmod","\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}"),$s("\\pod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)"),$s("\\pmod","\\pod{{\\rm mod}\\mkern6mu#1}"),$s("\\mod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1"),$s("\\newline","\\\\\\relax"),$s("\\TeX","\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");var $l=Ha(wa["Main-Regular"]["T".charCodeAt(0)][1]-.7*wa["Main-Regular"]["A".charCodeAt(0)][1]);$s("\\LaTeX","\\textrm{\\html@mathml{L\\kern-.36em\\raisebox{"+$l+"}{\\scriptstyle A}\\kern-.15em\\TeX}{LaTeX}}"),$s("\\KaTeX","\\textrm{\\html@mathml{K\\kern-.17em\\raisebox{"+$l+"}{\\scriptstyle A}\\kern-.15em\\TeX}{KaTeX}}"),$s("\\hspace","\\@ifstar\\@hspacer\\@hspace"),$s("\\@hspace","\\hskip #1\\relax"),$s("\\@hspacer","\\rule{0pt}{0pt}\\hskip #1\\relax"),$s("\\ordinarycolon",":"),$s("\\vcentcolon","\\mathrel{\\mathop\\ordinarycolon}"),$s("\\dblcolon",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}'),$s("\\coloneqq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}'),$s("\\Coloneqq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}'),$s("\\coloneq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}'),$s("\\Coloneq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}'),$s("\\eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}'),$s("\\Eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}'),$s("\\eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}'),$s("\\Eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}'),$s("\\colonapprox",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}'),$s("\\Colonapprox",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}'),$s("\\colonsim",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}'),$s("\\Colonsim",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}'),$s("∷","\\dblcolon"),$s("∹","\\eqcolon"),$s("≔","\\coloneqq"),$s("≕","\\eqqcolon"),$s("⩴","\\Coloneqq"),$s("\\ratio","\\vcentcolon"),$s("\\coloncolon","\\dblcolon"),$s("\\colonequals","\\coloneqq"),$s("\\coloncolonequals","\\Coloneqq"),$s("\\equalscolon","\\eqqcolon"),$s("\\equalscoloncolon","\\Eqqcolon"),$s("\\colonminus","\\coloneq"),$s("\\coloncolonminus","\\Coloneq"),$s("\\minuscolon","\\eqcolon"),$s("\\minuscoloncolon","\\Eqcolon"),$s("\\coloncolonapprox","\\Colonapprox"),$s("\\coloncolonsim","\\Colonsim"),$s("\\simcolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),$s("\\simcoloncolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}"),$s("\\approxcolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),$s("\\approxcoloncolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}"),$s("\\notni","\\html@mathml{\\not\\ni}{\\mathrel{\\char`∌}}"),$s("\\limsup","\\DOTSB\\operatorname*{lim\\,sup}"),$s("\\liminf","\\DOTSB\\operatorname*{lim\\,inf}"),$s("\\injlim","\\DOTSB\\operatorname*{inj\\,lim}"),$s("\\projlim","\\DOTSB\\operatorname*{proj\\,lim}"),$s("\\varlimsup","\\DOTSB\\operatorname*{\\overline{lim}}"),$s("\\varliminf","\\DOTSB\\operatorname*{\\underline{lim}}"),$s("\\varinjlim","\\DOTSB\\operatorname*{\\underrightarrow{lim}}"),$s("\\varprojlim","\\DOTSB\\operatorname*{\\underleftarrow{lim}}"),$s("\\gvertneqq","\\html@mathml{\\@gvertneqq}{≩}"),$s("\\lvertneqq","\\html@mathml{\\@lvertneqq}{≨}"),$s("\\ngeqq","\\html@mathml{\\@ngeqq}{≱}"),$s("\\ngeqslant","\\html@mathml{\\@ngeqslant}{≱}"),$s("\\nleqq","\\html@mathml{\\@nleqq}{≰}"),$s("\\nleqslant","\\html@mathml{\\@nleqslant}{≰}"),$s("\\nshortmid","\\html@mathml{\\@nshortmid}{∤}"),$s("\\nshortparallel","\\html@mathml{\\@nshortparallel}{∦}"),$s("\\nsubseteqq","\\html@mathml{\\@nsubseteqq}{⊈}"),$s("\\nsupseteqq","\\html@mathml{\\@nsupseteqq}{⊉}"),$s("\\varsubsetneq","\\html@mathml{\\@varsubsetneq}{⊊}"),$s("\\varsubsetneqq","\\html@mathml{\\@varsubsetneqq}{⫋}"),$s("\\varsupsetneq","\\html@mathml{\\@varsupsetneq}{⊋}"),$s("\\varsupsetneqq","\\html@mathml{\\@varsupsetneqq}{⫌}"),$s("\\imath","\\html@mathml{\\@imath}{ı}"),$s("\\jmath","\\html@mathml{\\@jmath}{ȷ}"),$s("\\llbracket","\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`⟦}}"),$s("\\rrbracket","\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`⟧}}"),$s("⟦","\\llbracket"),$s("⟧","\\rrbracket"),$s("\\lBrace","\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`⦃}}"),$s("\\rBrace","\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`⦄}}"),$s("⦃","\\lBrace"),$s("⦄","\\rBrace"),$s("\\minuso","\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`⦵}}"),$s("⦵","\\minuso"),$s("\\darr","\\downarrow"),$s("\\dArr","\\Downarrow"),$s("\\Darr","\\Downarrow"),$s("\\lang","\\langle"),$s("\\rang","\\rangle"),$s("\\uarr","\\uparrow"),$s("\\uArr","\\Uparrow"),$s("\\Uarr","\\Uparrow"),$s("\\N","\\mathbb{N}"),$s("\\R","\\mathbb{R}"),$s("\\Z","\\mathbb{Z}"),$s("\\alef","\\aleph"),$s("\\alefsym","\\aleph"),$s("\\Alpha","\\mathrm{A}"),$s("\\Beta","\\mathrm{B}"),$s("\\bull","\\bullet"),$s("\\Chi","\\mathrm{X}"),$s("\\clubs","\\clubsuit"),$s("\\cnums","\\mathbb{C}"),$s("\\Complex","\\mathbb{C}"),$s("\\Dagger","\\ddagger"),$s("\\diamonds","\\diamondsuit"),$s("\\empty","\\emptyset"),$s("\\Epsilon","\\mathrm{E}"),$s("\\Eta","\\mathrm{H}"),$s("\\exist","\\exists"),$s("\\harr","\\leftrightarrow"),$s("\\hArr","\\Leftrightarrow"),$s("\\Harr","\\Leftrightarrow"),$s("\\hearts","\\heartsuit"),$s("\\image","\\Im"),$s("\\infin","\\infty"),$s("\\Iota","\\mathrm{I}"),$s("\\isin","\\in"),$s("\\Kappa","\\mathrm{K}"),$s("\\larr","\\leftarrow"),$s("\\lArr","\\Leftarrow"),$s("\\Larr","\\Leftarrow"),$s("\\lrarr","\\leftrightarrow"),$s("\\lrArr","\\Leftrightarrow"),$s("\\Lrarr","\\Leftrightarrow"),$s("\\Mu","\\mathrm{M}"),$s("\\natnums","\\mathbb{N}"),$s("\\Nu","\\mathrm{N}"),$s("\\Omicron","\\mathrm{O}"),$s("\\plusmn","\\pm"),$s("\\rarr","\\rightarrow"),$s("\\rArr","\\Rightarrow"),$s("\\Rarr","\\Rightarrow"),$s("\\real","\\Re"),$s("\\reals","\\mathbb{R}"),$s("\\Reals","\\mathbb{R}"),$s("\\Rho","\\mathrm{P}"),$s("\\sdot","\\cdot"),$s("\\sect","\\S"),$s("\\spades","\\spadesuit"),$s("\\sub","\\subset"),$s("\\sube","\\subseteq"),$s("\\supe","\\supseteq"),$s("\\Tau","\\mathrm{T}"),$s("\\thetasym","\\vartheta"),$s("\\weierp","\\wp"),$s("\\Zeta","\\mathrm{Z}"),$s("\\argmin","\\DOTSB\\operatorname*{arg\\,min}"),$s("\\argmax","\\DOTSB\\operatorname*{arg\\,max}"),$s("\\plim","\\DOTSB\\mathop{\\operatorname{plim}}\\limits"),$s("\\bra","\\mathinner{\\langle{#1}|}"),$s("\\ket","\\mathinner{|{#1}\\rangle}"),$s("\\braket","\\mathinner{\\langle{#1}\\rangle}"),$s("\\Bra","\\left\\langle#1\\right|"),$s("\\Ket","\\left|#1\\right\\rangle");var Wl=e=>t=>{var r=t.consumeArg().tokens,n=t.consumeArg().tokens,a=t.consumeArg().tokens,i=t.consumeArg().tokens,o=t.macros.get("|"),s=t.macros.get("\\|");t.macros.beginGroup();var l=t=>r=>{e&&(r.macros.set("|",o),a.length&&r.macros.set("\\|",s));var i=t;!t&&a.length&&("|"===r.future().text&&(r.popToken(),i=!0));return{tokens:i?a:n,numArgs:0}};t.macros.set("|",l(!1)),a.length&&t.macros.set("\\|",l(!0));var c=t.consumeArg().tokens,d=t.expandTokens([...i,...c,...r]);return t.macros.endGroup(),{tokens:d.reverse(),numArgs:0}};$s("\\bra@ket",Wl(!1)),$s("\\bra@set",Wl(!0)),$s("\\Braket","\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}"),$s("\\Set","\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}"),$s("\\set","\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}"),$s("\\angln","{\\angl n}"),$s("\\blue","\\textcolor{##6495ed}{#1}"),$s("\\orange","\\textcolor{##ffa500}{#1}"),$s("\\pink","\\textcolor{##ff00af}{#1}"),$s("\\red","\\textcolor{##df0030}{#1}"),$s("\\green","\\textcolor{##28ae7b}{#1}"),$s("\\gray","\\textcolor{gray}{#1}"),$s("\\purple","\\textcolor{##9d38bd}{#1}"),$s("\\blueA","\\textcolor{##ccfaff}{#1}"),$s("\\blueB","\\textcolor{##80f6ff}{#1}"),$s("\\blueC","\\textcolor{##63d9ea}{#1}"),$s("\\blueD","\\textcolor{##11accd}{#1}"),$s("\\blueE","\\textcolor{##0c7f99}{#1}"),$s("\\tealA","\\textcolor{##94fff5}{#1}"),$s("\\tealB","\\textcolor{##26edd5}{#1}"),$s("\\tealC","\\textcolor{##01d1c1}{#1}"),$s("\\tealD","\\textcolor{##01a995}{#1}"),$s("\\tealE","\\textcolor{##208170}{#1}"),$s("\\greenA","\\textcolor{##b6ffb0}{#1}"),$s("\\greenB","\\textcolor{##8af281}{#1}"),$s("\\greenC","\\textcolor{##74cf70}{#1}"),$s("\\greenD","\\textcolor{##1fab54}{#1}"),$s("\\greenE","\\textcolor{##0d923f}{#1}"),$s("\\goldA","\\textcolor{##ffd0a9}{#1}"),$s("\\goldB","\\textcolor{##ffbb71}{#1}"),$s("\\goldC","\\textcolor{##ff9c39}{#1}"),$s("\\goldD","\\textcolor{##e07d10}{#1}"),$s("\\goldE","\\textcolor{##a75a05}{#1}"),$s("\\redA","\\textcolor{##fca9a9}{#1}"),$s("\\redB","\\textcolor{##ff8482}{#1}"),$s("\\redC","\\textcolor{##f9685d}{#1}"),$s("\\redD","\\textcolor{##e84d39}{#1}"),$s("\\redE","\\textcolor{##bc2612}{#1}"),$s("\\maroonA","\\textcolor{##ffbde0}{#1}"),$s("\\maroonB","\\textcolor{##ff92c6}{#1}"),$s("\\maroonC","\\textcolor{##ed5fa6}{#1}"),$s("\\maroonD","\\textcolor{##ca337c}{#1}"),$s("\\maroonE","\\textcolor{##9e034e}{#1}"),$s("\\purpleA","\\textcolor{##ddd7ff}{#1}"),$s("\\purpleB","\\textcolor{##c6b9fc}{#1}"),$s("\\purpleC","\\textcolor{##aa87ff}{#1}"),$s("\\purpleD","\\textcolor{##7854ab}{#1}"),$s("\\purpleE","\\textcolor{##543b78}{#1}"),$s("\\mintA","\\textcolor{##f5f9e8}{#1}"),$s("\\mintB","\\textcolor{##edf2df}{#1}"),$s("\\mintC","\\textcolor{##e0e5cc}{#1}"),$s("\\grayA","\\textcolor{##f6f7f7}{#1}"),$s("\\grayB","\\textcolor{##f0f1f2}{#1}"),$s("\\grayC","\\textcolor{##e3e5e6}{#1}"),$s("\\grayD","\\textcolor{##d6d8da}{#1}"),$s("\\grayE","\\textcolor{##babec2}{#1}"),$s("\\grayF","\\textcolor{##888d93}{#1}"),$s("\\grayG","\\textcolor{##626569}{#1}"),$s("\\grayH","\\textcolor{##3b3e40}{#1}"),$s("\\grayI","\\textcolor{##21242c}{#1}"),$s("\\kaBlue","\\textcolor{##314453}{#1}"),$s("\\kaGreen","\\textcolor{##71B307}{#1}");var jl={"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0};class Ql{constructor(e,t,r){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=t,this.expansionCount=0,this.feed(e),this.macros=new Gl(zl,t.macros),this.mode=r,this.stack=[]}feed(e){this.lexer=new Ul(e,this.settings)}switchMode(e){this.mode=e}beginGroup(){this.macros.beginGroup()}endGroup(){this.macros.endGroup()}endGroups(){this.macros.endGroups()}future(){return 0===this.stack.length&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]}popToken(){return this.future(),this.stack.pop()}pushToken(e){this.stack.push(e)}pushTokens(e){this.stack.push(...e)}scanArgument(e){var t,r,n;if(e){if(this.consumeSpaces(),"["!==this.future().text)return null;t=this.popToken(),({tokens:n,end:r}=this.consumeArg(["]"]))}else({tokens:n,start:t,end:r}=this.consumeArg());return this.pushToken(new oa("EOF",r.loc)),this.pushTokens(n),new oa("",ia.range(t,r))}consumeSpaces(){for(;;){if(" "!==this.future().text)break;this.stack.pop()}}consumeArg(e){var t=[],r=e&&e.length>0;r||this.consumeSpaces();var n,a=this.future(),i=0,o=0;do{if(n=this.popToken(),t.push(n),"{"===n.text)++i;else if("}"===n.text){if(-1===--i)throw new sa("Extra }",n)}else if("EOF"===n.text)throw new sa("Unexpected end of input in a macro argument, expected '"+(e&&r?e[o]:"}")+"'",n);if(e&&r)if((0===i||1===i&&"{"===e[o])&&n.text===e[o]){if(++o===e.length){t.splice(-o,o);break}}else o=0}while(0!==i||r);return"{"===a.text&&"}"===t[t.length-1].text&&(t.pop(),t.shift()),t.reverse(),{tokens:t,start:a,end:n}}consumeArgs(e,t){if(t){if(t.length!==e+1)throw new sa("The length of delimiters doesn't match the number of args!");for(var r=t[0],n=0;n<r.length;n++){var a=this.popToken();if(r[n]!==a.text)throw new sa("Use of the macro doesn't match its definition",a)}}for(var i=[],o=0;o<e;o++)i.push(this.consumeArg(t&&t[o+1]).tokens);return i}countExpansion(e){if(this.expansionCount+=e,this.expansionCount>this.settings.maxExpand)throw new sa("Too many expansions: infinite loop or need to increase maxExpand setting")}expandOnce(e){var t=this.popToken(),r=t.text,n=t.noexpand?null:this._getExpansion(r);if(null==n||e&&n.unexpandable){if(e&&null==n&&"\\"===r[0]&&!this.isDefined(r))throw new sa("Undefined control sequence: "+r);return this.pushToken(t),!1}this.countExpansion(1);var a=n.tokens,i=this.consumeArgs(n.numArgs,n.delimiters);if(n.numArgs)for(var o=(a=a.slice()).length-1;o>=0;--o){var s=a[o];if("#"===s.text){if(0===o)throw new sa("Incomplete placeholder at end of macro body",s);if("#"===(s=a[--o]).text)a.splice(o+1,1);else{if(!/^[1-9]$/.test(s.text))throw new sa("Not a valid argument number",s);a.splice(o,2,...i[+s.text-1])}}}return this.pushTokens(a),a.length}expandAfterFuture(){return this.expandOnce(),this.future()}expandNextToken(){for(;;)if(!1===this.expandOnce()){var e=this.stack.pop();return e.treatAsRelax&&(e.text="\\relax"),e}throw new Error}expandMacro(e){return this.macros.has(e)?this.expandTokens([new oa(e)]):void 0}expandTokens(e){var t=[],r=this.stack.length;for(this.pushTokens(e);this.stack.length>r;)if(!1===this.expandOnce(!0)){var n=this.stack.pop();n.treatAsRelax&&(n.noexpand=!1,n.treatAsRelax=!1),t.push(n)}return this.countExpansion(t.length),t}expandMacroAsText(e){var t=this.expandMacro(e);return t?t.map(e=>e.text).join(""):t}_getExpansion(e){var t=this.macros.get(e);if(null==t)return t;if(1===e.length){var r=this.lexer.catcodes[e];if(null!=r&&13!==r)return}var n="function"==typeof t?t(this):t;if("string"==typeof n){var a=0;if(-1!==n.indexOf("#"))for(var i=n.replace(/##/g,"");-1!==i.indexOf("#"+(a+1));)++a;for(var o=new Ul(n,this.settings),s=[],l=o.lex();"EOF"!==l.text;)s.push(l),l=o.lex();return s.reverse(),{tokens:s,numArgs:a}}return n}isDefined(e){return this.macros.has(e)||Ml.hasOwnProperty(e)||si.math.hasOwnProperty(e)||si.text.hasOwnProperty(e)||jl.hasOwnProperty(e)}isExpandable(e){var t=this.macros.get(e);return null!=t?"string"==typeof t||"function"==typeof t||!t.unexpandable:Ml.hasOwnProperty(e)&&!Ml[e].primitive}}var Kl=/^[₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ]/,Xl=Object.freeze({"₊":"+","₋":"-","₌":"=","₍":"(","₎":")","₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","ₐ":"a","ₑ":"e","ₕ":"h","ᵢ":"i","ⱼ":"j","ₖ":"k","ₗ":"l","ₘ":"m","ₙ":"n","ₒ":"o","ₚ":"p","ᵣ":"r","ₛ":"s","ₜ":"t","ᵤ":"u","ᵥ":"v","ₓ":"x","ᵦ":"β","ᵧ":"γ","ᵨ":"ρ","ᵩ":"ϕ","ᵪ":"χ","⁺":"+","⁻":"-","⁼":"=","⁽":"(","⁾":")","⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","ᴬ":"A","ᴮ":"B","ᴰ":"D","ᴱ":"E","ᴳ":"G","ᴴ":"H","ᴵ":"I","ᴶ":"J","ᴷ":"K","ᴸ":"L","ᴹ":"M","ᴺ":"N","ᴼ":"O","ᴾ":"P","ᴿ":"R","ᵀ":"T","ᵁ":"U","ⱽ":"V","ᵂ":"W","ᵃ":"a","ᵇ":"b","ᶜ":"c","ᵈ":"d","ᵉ":"e","ᶠ":"f","ᵍ":"g","ʰ":"h","ⁱ":"i","ʲ":"j","ᵏ":"k","ˡ":"l","ᵐ":"m","ⁿ":"n","ᵒ":"o","ᵖ":"p","ʳ":"r","ˢ":"s","ᵗ":"t","ᵘ":"u","ᵛ":"v","ʷ":"w","ˣ":"x","ʸ":"y","ᶻ":"z","ᵝ":"β","ᵞ":"γ","ᵟ":"δ","ᵠ":"ϕ","ᵡ":"χ","ᶿ":"θ"}),Zl={"́":{text:"\\'",math:"\\acute"},"̀":{text:"\\`",math:"\\grave"},"̈":{text:'\\"',math:"\\ddot"},"̃":{text:"\\~",math:"\\tilde"},"̄":{text:"\\=",math:"\\bar"},"̆":{text:"\\u",math:"\\breve"},"̌":{text:"\\v",math:"\\check"},"̂":{text:"\\^",math:"\\hat"},"̇":{text:"\\.",math:"\\dot"},"̊":{text:"\\r",math:"\\mathring"},"̋":{text:"\\H"},"̧":{text:"\\c"}},Jl={"á":"á","à":"à","ä":"ä","ǟ":"ǟ","ã":"ã","ā":"ā","ă":"ă","ắ":"ắ","ằ":"ằ","ẵ":"ẵ","ǎ":"ǎ","â":"â","ấ":"ấ","ầ":"ầ","ẫ":"ẫ","ȧ":"ȧ","ǡ":"ǡ","å":"å","ǻ":"ǻ","ḃ":"ḃ","ć":"ć","ḉ":"ḉ","č":"č","ĉ":"ĉ","ċ":"ċ","ç":"ç","ď":"ď","ḋ":"ḋ","ḑ":"ḑ","é":"é","è":"è","ë":"ë","ẽ":"ẽ","ē":"ē","ḗ":"ḗ","ḕ":"ḕ","ĕ":"ĕ","ḝ":"ḝ","ě":"ě","ê":"ê","ế":"ế","ề":"ề","ễ":"ễ","ė":"ė","ȩ":"ȩ","ḟ":"ḟ","ǵ":"ǵ","ḡ":"ḡ","ğ":"ğ","ǧ":"ǧ","ĝ":"ĝ","ġ":"ġ","ģ":"ģ","ḧ":"ḧ","ȟ":"ȟ","ĥ":"ĥ","ḣ":"ḣ","ḩ":"ḩ","í":"í","ì":"ì","ï":"ï","ḯ":"ḯ","ĩ":"ĩ","ī":"ī","ĭ":"ĭ","ǐ":"ǐ","î":"î","ǰ":"ǰ","ĵ":"ĵ","ḱ":"ḱ","ǩ":"ǩ","ķ":"ķ","ĺ":"ĺ","ľ":"ľ","ļ":"ļ","ḿ":"ḿ","ṁ":"ṁ","ń":"ń","ǹ":"ǹ","ñ":"ñ","ň":"ň","ṅ":"ṅ","ņ":"ņ","ó":"ó","ò":"ò","ö":"ö","ȫ":"ȫ","õ":"õ","ṍ":"ṍ","ṏ":"ṏ","ȭ":"ȭ","ō":"ō","ṓ":"ṓ","ṑ":"ṑ","ŏ":"ŏ","ǒ":"ǒ","ô":"ô","ố":"ố","ồ":"ồ","ỗ":"ỗ","ȯ":"ȯ","ȱ":"ȱ","ő":"ő","ṕ":"ṕ","ṗ":"ṗ","ŕ":"ŕ","ř":"ř","ṙ":"ṙ","ŗ":"ŗ","ś":"ś","ṥ":"ṥ","š":"š","ṧ":"ṧ","ŝ":"ŝ","ṡ":"ṡ","ş":"ş","ẗ":"ẗ","ť":"ť","ṫ":"ṫ","ţ":"ţ","ú":"ú","ù":"ù","ü":"ü","ǘ":"ǘ","ǜ":"ǜ","ǖ":"ǖ","ǚ":"ǚ","ũ":"ũ","ṹ":"ṹ","ū":"ū","ṻ":"ṻ","ŭ":"ŭ","ǔ":"ǔ","û":"û","ů":"ů","ű":"ű","ṽ":"ṽ","ẃ":"ẃ","ẁ":"ẁ","ẅ":"ẅ","ŵ":"ŵ","ẇ":"ẇ","ẘ":"ẘ","ẍ":"ẍ","ẋ":"ẋ","ý":"ý","ỳ":"ỳ","ÿ":"ÿ","ỹ":"ỹ","ȳ":"ȳ","ŷ":"ŷ","ẏ":"ẏ","ẙ":"ẙ","ź":"ź","ž":"ž","ẑ":"ẑ","ż":"ż","Á":"Á","À":"À","Ä":"Ä","Ǟ":"Ǟ","Ã":"Ã","Ā":"Ā","Ă":"Ă","Ắ":"Ắ","Ằ":"Ằ","Ẵ":"Ẵ","Ǎ":"Ǎ","Â":"Â","Ấ":"Ấ","Ầ":"Ầ","Ẫ":"Ẫ","Ȧ":"Ȧ","Ǡ":"Ǡ","Å":"Å","Ǻ":"Ǻ","Ḃ":"Ḃ","Ć":"Ć","Ḉ":"Ḉ","Č":"Č","Ĉ":"Ĉ","Ċ":"Ċ","Ç":"Ç","Ď":"Ď","Ḋ":"Ḋ","Ḑ":"Ḑ","É":"É","È":"È","Ë":"Ë","Ẽ":"Ẽ","Ē":"Ē","Ḗ":"Ḗ","Ḕ":"Ḕ","Ĕ":"Ĕ","Ḝ":"Ḝ","Ě":"Ě","Ê":"Ê","Ế":"Ế","Ề":"Ề","Ễ":"Ễ","Ė":"Ė","Ȩ":"Ȩ","Ḟ":"Ḟ","Ǵ":"Ǵ","Ḡ":"Ḡ","Ğ":"Ğ","Ǧ":"Ǧ","Ĝ":"Ĝ","Ġ":"Ġ","Ģ":"Ģ","Ḧ":"Ḧ","Ȟ":"Ȟ","Ĥ":"Ĥ","Ḣ":"Ḣ","Ḩ":"Ḩ","Í":"Í","Ì":"Ì","Ï":"Ï","Ḯ":"Ḯ","Ĩ":"Ĩ","Ī":"Ī","Ĭ":"Ĭ","Ǐ":"Ǐ","Î":"Î","İ":"İ","Ĵ":"Ĵ","Ḱ":"Ḱ","Ǩ":"Ǩ","Ķ":"Ķ","Ĺ":"Ĺ","Ľ":"Ľ","Ļ":"Ļ","Ḿ":"Ḿ","Ṁ":"Ṁ","Ń":"Ń","Ǹ":"Ǹ","Ñ":"Ñ","Ň":"Ň","Ṅ":"Ṅ","Ņ":"Ņ","Ó":"Ó","Ò":"Ò","Ö":"Ö","Ȫ":"Ȫ","Õ":"Õ","Ṍ":"Ṍ","Ṏ":"Ṏ","Ȭ":"Ȭ","Ō":"Ō","Ṓ":"Ṓ","Ṑ":"Ṑ","Ŏ":"Ŏ","Ǒ":"Ǒ","Ô":"Ô","Ố":"Ố","Ồ":"Ồ","Ỗ":"Ỗ","Ȯ":"Ȯ","Ȱ":"Ȱ","Ő":"Ő","Ṕ":"Ṕ","Ṗ":"Ṗ","Ŕ":"Ŕ","Ř":"Ř","Ṙ":"Ṙ","Ŗ":"Ŗ","Ś":"Ś","Ṥ":"Ṥ","Š":"Š","Ṧ":"Ṧ","Ŝ":"Ŝ","Ṡ":"Ṡ","Ş":"Ş","Ť":"Ť","Ṫ":"Ṫ","Ţ":"Ţ","Ú":"Ú","Ù":"Ù","Ü":"Ü","Ǘ":"Ǘ","Ǜ":"Ǜ","Ǖ":"Ǖ","Ǚ":"Ǚ","Ũ":"Ũ","Ṹ":"Ṹ","Ū":"Ū","Ṻ":"Ṻ","Ŭ":"Ŭ","Ǔ":"Ǔ","Û":"Û","Ů":"Ů","Ű":"Ű","Ṽ":"Ṽ","Ẃ":"Ẃ","Ẁ":"Ẁ","Ẅ":"Ẅ","Ŵ":"Ŵ","Ẇ":"Ẇ","Ẍ":"Ẍ","Ẋ":"Ẋ","Ý":"Ý","Ỳ":"Ỳ","Ÿ":"Ÿ","Ỹ":"Ỹ","Ȳ":"Ȳ","Ŷ":"Ŷ","Ẏ":"Ẏ","Ź":"Ź","Ž":"Ž","Ẑ":"Ẑ","Ż":"Ż","ά":"ά","ὰ":"ὰ","ᾱ":"ᾱ","ᾰ":"ᾰ","έ":"έ","ὲ":"ὲ","ή":"ή","ὴ":"ὴ","ί":"ί","ὶ":"ὶ","ϊ":"ϊ","ΐ":"ΐ","ῒ":"ῒ","ῑ":"ῑ","ῐ":"ῐ","ό":"ό","ὸ":"ὸ","ύ":"ύ","ὺ":"ὺ","ϋ":"ϋ","ΰ":"ΰ","ῢ":"ῢ","ῡ":"ῡ","ῠ":"ῠ","ώ":"ώ","ὼ":"ὼ","Ύ":"Ύ","Ὺ":"Ὺ","Ϋ":"Ϋ","Ῡ":"Ῡ","Ῠ":"Ῠ","Ώ":"Ώ","Ὼ":"Ὼ"};class ec{constructor(e,t){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode="math",this.gullet=new Ql(e,t,this.mode),this.settings=t,this.leftrightDepth=0}expect(e,t){if(void 0===t&&(t=!0),this.fetch().text!==e)throw new sa("Expected '"+e+"', got '"+this.fetch().text+"'",this.fetch());t&&this.consume()}consume(){this.nextToken=null}fetch(){return null==this.nextToken&&(this.nextToken=this.gullet.expandNextToken()),this.nextToken}switchMode(e){this.mode=e,this.gullet.switchMode(e)}parse(){this.settings.globalGroup||this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set("\\color","\\textcolor");try{var e=this.parseExpression(!1);return this.expect("EOF"),this.settings.globalGroup||this.gullet.endGroup(),e}finally{this.gullet.endGroups()}}subparse(e){var t=this.nextToken;this.consume(),this.gullet.pushToken(new oa("}")),this.gullet.pushTokens(e);var r=this.parseExpression(!1);return this.expect("}"),this.nextToken=t,r}parseExpression(e,t){for(var r=[];;){"math"===this.mode&&this.consumeSpaces();var n=this.fetch();if(-1!==ec.endOfExpression.indexOf(n.text))break;if(t&&n.text===t)break;if(e&&Ml[n.text]&&Ml[n.text].infix)break;var a=this.parseAtom(t);if(!a)break;"internal"!==a.type&&r.push(a)}return"text"===this.mode&&this.formLigatures(r),this.handleInfixNodes(r)}handleInfixNodes(e){for(var t,r=-1,n=0;n<e.length;n++)if("infix"===e[n].type){if(-1!==r)throw new sa("only one infix operator per group",e[n].token);r=n,t=e[n].replaceWith}if(-1!==r&&t){var a,i,o=e.slice(0,r),s=e.slice(r+1);return a=1===o.length&&"ordgroup"===o[0].type?o[0]:{type:"ordgroup",mode:this.mode,body:o},i=1===s.length&&"ordgroup"===s[0].type?s[0]:{type:"ordgroup",mode:this.mode,body:s},["\\\\abovefrac"===t?this.callFunction(t,[a,e[r],i],[]):this.callFunction(t,[a,i],[])]}return e}handleSupSubscript(e){var t,r=this.fetch(),n=r.text;this.consume(),this.consumeSpaces();do{var a;t=this.parseGroup(e)}while("internal"===(null==(a=t)?void 0:a.type));if(!t)throw new sa("Expected group after '"+n+"'",r);return t}formatUnsupportedCmd(e){for(var t=[],r=0;r<e.length;r++)t.push({type:"textord",mode:"text",text:e[r]});var n={type:"text",mode:this.mode,body:t};return{type:"color",mode:this.mode,color:this.settings.errorColor,body:[n]}}parseAtom(e){var t,r,n=this.parseGroup("atom",e);if("internal"===(null==n?void 0:n.type))return n;if("text"===this.mode)return n;for(;;){this.consumeSpaces();var a=this.fetch();if("\\limits"===a.text||"\\nolimits"===a.text){if(n&&"op"===n.type){var i="\\limits"===a.text;n.limits=i,n.alwaysHandleSupSub=!0}else{if(!n||"operatorname"!==n.type)throw new sa("Limit controls must follow a math operator",a);n.alwaysHandleSupSub&&(n.limits="\\limits"===a.text)}this.consume()}else if("^"===a.text){if(t)throw new sa("Double superscript",a);t=this.handleSupSubscript("superscript")}else if("_"===a.text){if(r)throw new sa("Double subscript",a);r=this.handleSupSubscript("subscript")}else if("'"===a.text){if(t)throw new sa("Double superscript",a);var o={type:"textord",mode:this.mode,text:"\\prime"},s=[o];for(this.consume();"'"===this.fetch().text;)s.push(o),this.consume();"^"===this.fetch().text&&s.push(this.handleSupSubscript("superscript")),t={type:"ordgroup",mode:this.mode,body:s}}else{if(!Xl[a.text])break;var l=Kl.test(a.text),c=[];for(c.push(new oa(Xl[a.text])),this.consume();;){var d=this.fetch().text;if(!Xl[d])break;if(Kl.test(d)!==l)break;c.unshift(new oa(Xl[d])),this.consume()}var u=this.subparse(c);l?r={type:"ordgroup",mode:"math",body:u}:t={type:"ordgroup",mode:"math",body:u}}}return t||r?{type:"supsub",mode:this.mode,base:n,sup:t,sub:r}:n}parseFunction(e,t){var r=this.fetch(),n=r.text,a=Ml[n];if(!a)return null;if(this.consume(),t&&"atom"!==t&&!a.allowedInArgument)throw new sa("Got function '"+n+"' with no arguments"+(t?" as "+t:""),r);if("text"===this.mode&&!a.allowedInText)throw new sa("Can't use function '"+n+"' in text mode",r);if("math"===this.mode&&!1===a.allowedInMath)throw new sa("Can't use function '"+n+"' in math mode",r);var{args:i,optArgs:o}=this.parseArguments(n,a);return this.callFunction(n,i,o,r,e)}callFunction(e,t,r,n,a){var i={funcName:e,parser:this,token:n,breakOnTokenText:a},o=Ml[e];if(o&&o.handler)return o.handler(i,t,r);throw new sa("No function handler for "+e)}parseArguments(e,t){var r=t.numArgs+t.numOptionalArgs;if(0===r)return{args:[],optArgs:[]};for(var n=[],a=[],i=0;i<r;i++){var o=t.argTypes&&t.argTypes[i],s=i<t.numOptionalArgs;(t.primitive&&null==o||"sqrt"===t.type&&1===i&&null==a[0])&&(o="primitive");var l=this.parseGroupOfType("argument to '"+e+"'",o,s);if(s)a.push(l);else{if(null==l)throw new sa("Null argument, please report this as a bug");n.push(l)}}return{args:n,optArgs:a}}parseGroupOfType(e,t,r){switch(t){case"color":return this.parseColorGroup(r);case"size":return this.parseSizeGroup(r);case"url":return this.parseUrlGroup(r);case"math":case"text":return this.parseArgumentGroup(r,t);case"hbox":var n=this.parseArgumentGroup(r,"text");return null!=n?{type:"styling",mode:n.mode,body:[n],style:"text"}:null;case"raw":var a=this.parseStringGroup("raw",r);return null!=a?{type:"raw",mode:"text",string:a.text}:null;case"primitive":if(r)throw new sa("A primitive argument cannot be optional");var i=this.parseGroup(e);if(null==i)throw new sa("Expected group as "+e,this.fetch());return i;case"original":case null:case void 0:return this.parseArgumentGroup(r);default:throw new sa("Unknown group type as "+e,this.fetch())}}consumeSpaces(){for(;" "===this.fetch().text;)this.consume()}parseStringGroup(e,t){var r=this.gullet.scanArgument(t);if(null==r)return null;for(var n,a="";"EOF"!==(n=this.fetch()).text;)a+=n.text,this.consume();return this.consume(),r.text=a,r}parseRegexGroup(e,t){for(var r,n=this.fetch(),a=n,i="";"EOF"!==(r=this.fetch()).text&&e.test(i+r.text);)i+=(a=r).text,this.consume();if(""===i)throw new sa("Invalid "+t+": '"+n.text+"'",n);return n.range(a,i)}parseColorGroup(e){var t=this.parseStringGroup("color",e);if(null==t)return null;var r=/^(#[a-f0-9]{3,4}|#[a-f0-9]{6}|#[a-f0-9]{8}|[a-f0-9]{6}|[a-z]+)$/i.exec(t.text);if(!r)throw new sa("Invalid color: '"+t.text+"'",t);var n=r[0];return/^[0-9a-f]{6}$/i.test(n)&&(n="#"+n),{type:"color-token",mode:this.mode,color:n}}parseSizeGroup(e){var t,r=!1;if(this.gullet.consumeSpaces(),!(t=e||"{"===this.gullet.future().text?this.parseStringGroup("size",e):this.parseRegexGroup(/^[-+]? *(?:$|\d+|\d+\.\d*|\.\d*) *[a-z]{0,2} *$/,"size")))return null;e||0!==t.text.length||(t.text="0pt",r=!0);var n=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(t.text);if(!n)throw new sa("Invalid size: '"+t.text+"'",t);var a={number:+(n[1]+n[2]),unit:n[3]};if(!Ya(a))throw new sa("Invalid unit: '"+a.unit+"'",t);return{type:"size",mode:this.mode,value:a,isBlank:r}}parseUrlGroup(e){this.gullet.lexer.setCatcode("%",13),this.gullet.lexer.setCatcode("~",12);var t=this.parseStringGroup("url",e);if(this.gullet.lexer.setCatcode("%",14),this.gullet.lexer.setCatcode("~",13),null==t)return null;var r=t.text.replace(/\\([#$%&~_^{}])/g,"$1");return{type:"url",mode:this.mode,url:r}}parseArgumentGroup(e,t){var r=this.gullet.scanArgument(e);if(null==r)return null;var n=this.mode;t&&this.switchMode(t),this.gullet.beginGroup();var a=this.parseExpression(!1,"EOF");this.expect("EOF"),this.gullet.endGroup();var i={type:"ordgroup",mode:this.mode,loc:r.loc,body:a};return t&&this.switchMode(n),i}parseGroup(e,t){var r,n=this.fetch(),a=n.text;if("{"===a||"\\begingroup"===a){this.consume();var i="{"===a?"}":"\\endgroup";this.gullet.beginGroup();var o=this.parseExpression(!1,i),s=this.fetch();this.expect(i),this.gullet.endGroup(),r={type:"ordgroup",mode:this.mode,loc:ia.range(n,s),body:o,semisimple:"\\begingroup"===a||void 0}}else if(null==(r=this.parseFunction(t,e)||this.parseSymbol())&&"\\"===a[0]&&!jl.hasOwnProperty(a)){if(this.settings.throwOnError)throw new sa("Undefined control sequence: "+a,n);r=this.formatUnsupportedCmd(a),this.consume()}return r}formLigatures(e){for(var t=e.length-1,r=0;r<t;++r){var n=e[r],a=n.text;"-"===a&&"-"===e[r+1].text&&(r+1<t&&"-"===e[r+2].text?(e.splice(r,3,{type:"textord",mode:"text",loc:ia.range(n,e[r+2]),text:"---"}),t-=2):(e.splice(r,2,{type:"textord",mode:"text",loc:ia.range(n,e[r+1]),text:"--"}),t-=1)),"'"!==a&&"`"!==a||e[r+1].text!==a||(e.splice(r,2,{type:"textord",mode:"text",loc:ia.range(n,e[r+1]),text:a+a}),t-=1)}}parseSymbol(){var e=this.fetch(),t=e.text;if(/^\\verb[^a-zA-Z]/.test(t)){this.consume();var r=t.slice(5),n="*"===r.charAt(0);if(n&&(r=r.slice(1)),r.length<2||r.charAt(0)!==r.slice(-1))throw new sa("\\verb assertion failed --\n please report what input caused this bug");return{type:"verb",mode:"text",body:r=r.slice(1,-1),star:n}}Jl.hasOwnProperty(t[0])&&!si[this.mode][t[0]]&&(this.settings.strict&&"math"===this.mode&&this.settings.reportNonstrict("unicodeTextInMathMode",'Accented Unicode text character "'+t[0]+'" used in math mode',e),t=Jl[t[0]]+t.slice(1));var a,i=Fl.exec(t);if(i&&("i"===(t=t.substring(0,i.index))?t="ı":"j"===t&&(t="ȷ")),si[this.mode][t]){this.settings.strict&&"math"===this.mode&&Ui.indexOf(t)>=0&&this.settings.reportNonstrict("unicodeTextInMathMode",'Latin-1/Unicode text character "'+t[0]+'" used in math mode',e);var o,s=si[this.mode][t].group,l=ia.range(e);if(ii.hasOwnProperty(s)){var c=s;o={type:"atom",mode:this.mode,family:c,loc:l,text:t}}else o={type:s,mode:this.mode,loc:l,text:t};a=o}else{if(!(t.charCodeAt(0)>=128))return null;this.settings.strict&&(Aa(t.charCodeAt(0))?"math"===this.mode&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+t[0]+'" used in math mode',e):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+t[0]+'" ('+t.charCodeAt(0)+")",e)),a={type:"textord",mode:"text",loc:ia.range(e),text:t}}if(this.consume(),i)for(var d=0;d<i[0].length;d++){var u=i[0][d];if(!Zl[u])throw new sa("Unknown accent ' "+u+"'",e);var p=Zl[u][this.mode]||Zl[u].text;if(!p)throw new sa("Accent "+u+" unsupported in "+this.mode+" mode",e);a={type:"accent",mode:this.mode,loc:ia.range(e),label:p,isStretchy:!1,isShifty:!0,base:a}}return a}}ec.endOfExpression=["}","\\endgroup","\\end","\\right","&"];var tc=function(e,t){if(!("string"==typeof e||e instanceof String))throw new TypeError("KaTeX can only parse string typed expression");var r=new ec(e,t);delete r.gullet.macros.current["\\df@tag"];var n=r.parse();if(delete r.gullet.macros.current["\\current@color"],delete r.gullet.macros.current["\\color"],r.gullet.macros.get("\\df@tag")){if(!t.displayMode)throw new sa("\\tag works only in display equations");n=[{type:"tag",mode:"text",body:n,tag:r.subparse([new oa("\\df@tag")])}]}return n},rc=function(e,t,r){t.textContent="";var n=ac(e,r).toNode();t.appendChild(n)};"undefined"!=typeof document&&"CSS1Compat"!==document.compatMode&&("undefined"!=typeof console&&console.warn("Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype."),rc=function(){throw new sa("KaTeX doesn't work in quirks mode.")});var nc=function(e,t,r){if(r.throwOnError||!(e instanceof sa))throw e;var n=eo.makeSpan(["katex-error"],[new ei(t)]);return n.setAttribute("title",e.toString()),n.setAttribute("style","color:"+r.errorColor),n},ac=function(e,t){var r=new ga(t);try{return function(e,t,r){var n,a=Go(r);if("mathml"===r.output)return Uo(e,t,a,r.displayMode,!0);if("html"===r.output){var i=Ao(e,a);n=eo.makeSpan(["katex"],[i])}else{var o=Uo(e,t,a,r.displayMode,!1),s=Ao(e,a);n=eo.makeSpan(["katex"],[o,s])}return zo(n,r)}(tc(e,r),e,r)}catch(t){return nc(t,e,r)}},ic={version:"0.16.28",render:rc,renderToString:function(e,t){return ac(e,t).toMarkup()},ParseError:sa,SETTINGS_SCHEMA:_a,__parse:function(e,t){var r=new ga(t);return tc(e,r)},__renderToDomTree:ac,__renderToHTMLTree:function(e,t){var r=new ga(t);try{return function(e,t,r){var n=Ao(e,Go(r)),a=eo.makeSpan(["katex"],[n]);return zo(a,r)}(tc(e,r),0,r)}catch(t){return nc(t,e,r)}},__setFontMetrics:function(e,t){wa[e]=t},__defineSymbol:li,__defineFunction:co,__defineMacro:$s,__domTree:{Span:Ka,Anchor:Xa,SymbolNode:ei,SvgNode:ti,PathNode:ri,LineNode:ni}};ic.__defineMacro("\\ce",function(e){return oc(e.consumeArgs(1)[0],"ce")}),ic.__defineMacro("\\pu",function(e){return oc(e.consumeArgs(1)[0],"pu")}),ic.__defineMacro("\\tripledash","{\\vphantom{-}\\raisebox{2.56mu}{$\\mkern2mu\\tiny\\text{-}\\mkern1mu\\text{-}\\mkern1mu\\text{-}\\mkern2mu$}}");var oc=function(e,t){for(var r="",n=e.length&&e[e.length-1].loc.start,a=e.length-1;a>=0;a--)e[a].loc.start>n&&(r+=" ",n=e[a].loc.start),r+=e[a].text,n+=e[a].text.length;return lc.go(sc.go(r,t))},sc={go:function(e,t){if(!e)return[];void 0===t&&(t="ce");var r,n="0",a={};a.parenthesisLevel=0,e=(e=(e=e.replace(/\n/g," ")).replace(/[\u2212\u2013\u2014\u2010]/g,"-")).replace(/[\u2026]/g,"...");for(var i=10,o=[];;){r!==e?(i=10,r=e):i--;var s=sc.stateMachines[t],l=s.transitions[n]||s.transitions["*"];e:for(var c=0;c<l.length;c++){var d=sc.patterns.match_(l[c].pattern,e);if(d){for(var u=l[c].task,p=0;p<u.action_.length;p++){var _;if(s.actions[u.action_[p].type_])_=s.actions[u.action_[p].type_](a,d.match_,u.action_[p].option);else{if(!sc.actions[u.action_[p].type_])throw["MhchemBugA","mhchem bug A. Please report. ("+u.action_[p].type_+")"];_=sc.actions[u.action_[p].type_](a,d.match_,u.action_[p].option)}sc.concatArray(o,_)}if(n=u.nextState||n,!(e.length>0))return o;if(u.revisit||(e=d.remainder),!u.toContinue)break e}}if(i<=0)throw["MhchemBugU","mhchem bug U. Please report."]}},concatArray:function(e,t){if(t)if(Array.isArray(t))for(var r=0;r<t.length;r++)e.push(t[r]);else e.push(t)},patterns:{patterns:{empty:/^$/,else:/^./,else2:/^./,space:/^\s/,"space A":/^\s(?=[A-Z\\$])/,space$:/^\s$/,"a-z":/^[a-z]/,x:/^x/,x$:/^x$/,i$:/^i$/,letters:/^(?:[a-zA-Z\u03B1-\u03C9\u0391-\u03A9?@]|(?:\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)(?:\s+|\{\}|(?![a-zA-Z]))))+/,"\\greek":/^\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)(?:\s+|\{\}|(?![a-zA-Z]))/,"one lowercase latin letter $":/^(?:([a-z])(?:$|[^a-zA-Z]))$/,"$one lowercase latin letter$ $":/^\$(?:([a-z])(?:$|[^a-zA-Z]))\$$/,"one lowercase greek letter $":/^(?:\$?[\u03B1-\u03C9]\$?|\$?\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega)\s*\$?)(?:\s+|\{\}|(?![a-zA-Z]))$/,digits:/^[0-9]+/,"-9.,9":/^[+\-]?(?:[0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))/,"-9.,9 no missing 0":/^[+\-]?[0-9]+(?:[.,][0-9]+)?/,"(-)(9.,9)(e)(99)":function(e){var t=e.match(/^(\+\-|\+\/\-|\+|\-|\\pm\s?)?([0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))?(\((?:[0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))\))?(?:([eE]|\s*(\*|x|\\times|\u00D7)\s*10\^)([+\-]?[0-9]+|\{[+\-]?[0-9]+\}))?/);return t&&t[0]?{match_:t.splice(1),remainder:e.substr(t[0].length)}:null},"(-)(9)^(-9)":function(e){var t=e.match(/^(\+\-|\+\/\-|\+|\-|\\pm\s?)?([0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+)?)\^([+\-]?[0-9]+|\{[+\-]?[0-9]+\})/);return t&&t[0]?{match_:t.splice(1),remainder:e.substr(t[0].length)}:null},"state of aggregation $":function(e){var t=sc.patterns.findObserveGroups(e,"",/^\([a-z]{1,3}(?=[\),])/,")","");if(t&&t.remainder.match(/^($|[\s,;\)\]\}])/))return t;var r=e.match(/^(?:\((?:\\ca\s?)?\$[amothc]\$\))/);return r?{match_:r[0],remainder:e.substr(r[0].length)}:null},"_{(state of aggregation)}$":/^_\{(\([a-z]{1,3}\))\}/,"{[(":/^(?:\\\{|\[|\()/,")]}":/^(?:\)|\]|\\\})/,", ":/^[,;]\s*/,",":/^[,;]/,".":/^[.]/,". ":/^([.\u22C5\u00B7\u2022])\s*/,"...":/^\.\.\.(?=$|[^.])/,"* ":/^([*])\s*/,"^{(...)}":function(e){return sc.patterns.findObserveGroups(e,"^{","","","}")},"^($...$)":function(e){return sc.patterns.findObserveGroups(e,"^","$","$","")},"^a":/^\^([0-9]+|[^\\_])/,"^\\x{}{}":function(e){return sc.patterns.findObserveGroups(e,"^",/^\\[a-zA-Z]+\{/,"}","","","{","}","",!0)},"^\\x{}":function(e){return sc.patterns.findObserveGroups(e,"^",/^\\[a-zA-Z]+\{/,"}","")},"^\\x":/^\^(\\[a-zA-Z]+)\s*/,"^(-1)":/^\^(-?\d+)/,"'":/^'/,"_{(...)}":function(e){return sc.patterns.findObserveGroups(e,"_{","","","}")},"_($...$)":function(e){return sc.patterns.findObserveGroups(e,"_","$","$","")},_9:/^_([+\-]?[0-9]+|[^\\])/,"_\\x{}{}":function(e){return sc.patterns.findObserveGroups(e,"_",/^\\[a-zA-Z]+\{/,"}","","","{","}","",!0)},"_\\x{}":function(e){return sc.patterns.findObserveGroups(e,"_",/^\\[a-zA-Z]+\{/,"}","")},"_\\x":/^_(\\[a-zA-Z]+)\s*/,"^_":/^(?:\^(?=_)|\_(?=\^)|[\^_]$)/,"{}":/^\{\}/,"{...}":function(e){return sc.patterns.findObserveGroups(e,"","{","}","")},"{(...)}":function(e){return sc.patterns.findObserveGroups(e,"{","","","}")},"$...$":function(e){return sc.patterns.findObserveGroups(e,"","$","$","")},"${(...)}$":function(e){return sc.patterns.findObserveGroups(e,"${","","","}$")},"$(...)$":function(e){return sc.patterns.findObserveGroups(e,"$","","","$")},"=<>":/^[=<>]/,"#":/^[#\u2261]/,"+":/^\+/,"-$":/^-(?=[\s_},;\]/]|$|\([a-z]+\))/,"-9":/^-(?=[0-9])/,"- orbital overlap":/^-(?=(?:[spd]|sp)(?:$|[\s,;\)\]\}]))/,"-":/^-/,"pm-operator":/^(?:\\pm|\$\\pm\$|\+-|\+\/-)/,operator:/^(?:\+|(?:[\-=<>]|<<|>>|\\approx|\$\\approx\$)(?=\s|$|-?[0-9]))/,arrowUpDown:/^(?:v|\(v\)|\^|\(\^\))(?=$|[\s,;\)\]\}])/,"\\bond{(...)}":function(e){return sc.patterns.findObserveGroups(e,"\\bond{","","","}")},"->":/^(?:<->|<-->|->|<-|<=>>|<<=>|<=>|[\u2192\u27F6\u21CC])/,CMT:/^[CMT](?=\[)/,"[(...)]":function(e){return sc.patterns.findObserveGroups(e,"[","","","]")},"1st-level escape":/^(&|\\\\|\\hline)\s*/,"\\,":/^(?:\\[,\ ;:])/,"\\x{}{}":function(e){return sc.patterns.findObserveGroups(e,"",/^\\[a-zA-Z]+\{/,"}","","","{","}","",!0)},"\\x{}":function(e){return sc.patterns.findObserveGroups(e,"",/^\\[a-zA-Z]+\{/,"}","")},"\\ca":/^\\ca(?:\s+|(?![a-zA-Z]))/,"\\x":/^(?:\\[a-zA-Z]+\s*|\\[_&{}%])/,orbital:/^(?:[0-9]{1,2}[spdfgh]|[0-9]{0,2}sp)(?=$|[^a-zA-Z])/,others:/^[\/~|]/,"\\frac{(...)}":function(e){return sc.patterns.findObserveGroups(e,"\\frac{","","","}","{","","","}")},"\\overset{(...)}":function(e){return sc.patterns.findObserveGroups(e,"\\overset{","","","}","{","","","}")},"\\underset{(...)}":function(e){return sc.patterns.findObserveGroups(e,"\\underset{","","","}","{","","","}")},"\\underbrace{(...)}":function(e){return sc.patterns.findObserveGroups(e,"\\underbrace{","","","}_","{","","","}")},"\\color{(...)}0":function(e){return sc.patterns.findObserveGroups(e,"\\color{","","","}")},"\\color{(...)}{(...)}1":function(e){return sc.patterns.findObserveGroups(e,"\\color{","","","}","{","","","}")},"\\color(...){(...)}2":function(e){return sc.patterns.findObserveGroups(e,"\\color","\\","",/^(?=\{)/,"{","","","}")},"\\ce{(...)}":function(e){return sc.patterns.findObserveGroups(e,"\\ce{","","","}")},oxidation$:/^(?:[+-][IVX]+|\\pm\s*0|\$\\pm\$\s*0)$/,"d-oxidation$":/^(?:[+-]?\s?[IVX]+|\\pm\s*0|\$\\pm\$\s*0)$/,"roman numeral":/^[IVX]+/,"1/2$":/^[+\-]?(?:[0-9]+|\$[a-z]\$|[a-z])\/[0-9]+(?:\$[a-z]\$|[a-z])?$/,amount:function(e){var t;if(t=e.match(/^(?:(?:(?:\([+\-]?[0-9]+\/[0-9]+\)|[+\-]?(?:[0-9]+|\$[a-z]\$|[a-z])\/[0-9]+|[+\-]?[0-9]+[.,][0-9]+|[+\-]?\.[0-9]+|[+\-]?[0-9]+)(?:[a-z](?=\s*[A-Z]))?)|[+\-]?[a-z](?=\s*[A-Z])|\+(?!\s))/))return{match_:t[0],remainder:e.substr(t[0].length)};var r=sc.patterns.findObserveGroups(e,"","$","$","");return r&&(t=r.match_.match(/^\$(?:\(?[+\-]?(?:[0-9]*[a-z]?[+\-])?[0-9]*[a-z](?:[+\-][0-9]*[a-z]?)?\)?|\+|-)\$$/))?{match_:t[0],remainder:e.substr(t[0].length)}:null},amount2:function(e){return this.amount(e)},"(KV letters),":/^(?:[A-Z][a-z]{0,2}|i)(?=,)/,formula$:function(e){if(e.match(/^\([a-z]+\)$/))return null;var t=e.match(/^(?:[a-z]|(?:[0-9\ \+\-\,\.\(\)]+[a-z])+[0-9\ \+\-\,\.\(\)]*|(?:[a-z][0-9\ \+\-\,\.\(\)]+)+[a-z]?)$/);return t?{match_:t[0],remainder:e.substr(t[0].length)}:null},uprightEntities:/^(?:pH|pOH|pC|pK|iPr|iBu)(?=$|[^a-zA-Z])/,"/":/^\s*(\/)\s*/,"//":/^\s*(\/\/)\s*/,"*":/^\s*[*.]\s*/},findObserveGroups:function(e,t,r,n,a,i,o,s,l,c){var d=function(e,t){if("string"==typeof t)return 0!==e.indexOf(t)?null:t;var r=e.match(t);return r?r[0]:null},u=d(e,t);if(null===u)return null;if(e=e.substr(u.length),null===(u=d(e,r)))return null;var p=function(e,t,r){for(var n=0;t<e.length;){var a=e.charAt(t),i=d(e.substr(t),r);if(null!==i&&0===n)return{endMatchBegin:t,endMatchEnd:t+i.length};if("{"===a)n++;else if("}"===a){if(0===n)throw["ExtraCloseMissingOpen","Extra close brace or missing open brace"];n--}t++}return null}(e,u.length,n||a);if(null===p)return null;var _=e.substring(0,n?p.endMatchEnd:p.endMatchBegin);if(i||o){var m=this.findObserveGroups(e.substr(p.endMatchEnd),i,o,s,l);if(null===m)return null;var g=[_,m.match_];return{match_:c?g.join(""):g,remainder:m.remainder}}return{match_:_,remainder:e.substr(p.endMatchEnd)}},match_:function(e,t){var r=sc.patterns.patterns[e];if(void 0===r)throw["MhchemBugP","mhchem bug P. Please report. ("+e+")"];if("function"==typeof r)return sc.patterns.patterns[e](t);var n=t.match(r);return n?{match_:n[2]?[n[1],n[2]]:n[1]?n[1]:n[0],remainder:t.substr(n[0].length)}:null}},actions:{"a=":function(e,t){e.a=(e.a||"")+t},"b=":function(e,t){e.b=(e.b||"")+t},"p=":function(e,t){e.p=(e.p||"")+t},"o=":function(e,t){e.o=(e.o||"")+t},"q=":function(e,t){e.q=(e.q||"")+t},"d=":function(e,t){e.d=(e.d||"")+t},"rm=":function(e,t){e.rm=(e.rm||"")+t},"text=":function(e,t){e.text_=(e.text_||"")+t},insert:function(e,t,r){return{type_:r}},"insert+p1":function(e,t,r){return{type_:r,p1:t}},"insert+p1+p2":function(e,t,r){return{type_:r,p1:t[0],p2:t[1]}},copy:function(e,t){return t},rm:function(e,t){return{type_:"rm",p1:t||""}},text:function(e,t){return sc.go(t,"text")},"{text}":function(e,t){var r=["{"];return sc.concatArray(r,sc.go(t,"text")),r.push("}"),r},"tex-math":function(e,t){return sc.go(t,"tex-math")},"tex-math tight":function(e,t){return sc.go(t,"tex-math tight")},bond:function(e,t,r){return{type_:"bond",kind_:r||t}},"color0-output":function(e,t){return{type_:"color0",color:t[0]}},ce:function(e,t){return sc.go(t)},"1/2":function(e,t){var r=[];t.match(/^[+\-]/)&&(r.push(t.substr(0,1)),t=t.substr(1));var n=t.match(/^([0-9]+|\$[a-z]\$|[a-z])\/([0-9]+)(\$[a-z]\$|[a-z])?$/);return n[1]=n[1].replace(/\$/g,""),r.push({type_:"frac",p1:n[1],p2:n[2]}),n[3]&&(n[3]=n[3].replace(/\$/g,""),r.push({type_:"tex-math",p1:n[3]})),r},"9,9":function(e,t){return sc.go(t,"9,9")}},createTransitions:function(e){var t,r,n,a,i={};for(t in e)for(r in e[t])for(n=r.split("|"),e[t][r].stateArray=n,a=0;a<n.length;a++)i[n[a]]=[];for(t in e)for(r in e[t])for(n=e[t][r].stateArray||[],a=0;a<n.length;a++){var o=e[t][r];if(o.action_){o.action_=[].concat(o.action_);for(var s=0;s<o.action_.length;s++)"string"==typeof o.action_[s]&&(o.action_[s]={type_:o.action_[s]})}else o.action_=[];for(var l=t.split("|"),c=0;c<l.length;c++)if("*"===n[a])for(var d in i)i[d].push({pattern:l[c],task:o});else i[n[a]].push({pattern:l[c],task:o})}return i},stateMachines:{}};sc.stateMachines={ce:{transitions:sc.createTransitions({empty:{"*":{action_:"output"}},else:{"0|1|2":{action_:"beginsWithBond=false",revisit:!0,toContinue:!0}},oxidation$:{0:{action_:"oxidation-output"}},CMT:{r:{action_:"rdt=",nextState:"rt"},rd:{action_:"rqt=",nextState:"rdt"}},arrowUpDown:{"0|1|2|as":{action_:["sb=false","output","operator"],nextState:"1"}},uprightEntities:{"0|1|2":{action_:["o=","output"],nextState:"1"}},orbital:{"0|1|2|3":{action_:"o=",nextState:"o"}},"->":{"0|1|2|3":{action_:"r=",nextState:"r"},"a|as":{action_:["output","r="],nextState:"r"},"*":{action_:["output","r="],nextState:"r"}},"+":{o:{action_:"d= kv",nextState:"d"},"d|D":{action_:"d=",nextState:"d"},q:{action_:"d=",nextState:"qd"},"qd|qD":{action_:"d=",nextState:"qd"},dq:{action_:["output","d="],nextState:"d"},3:{action_:["sb=false","output","operator"],nextState:"0"}},amount:{"0|2":{action_:"a=",nextState:"a"}},"pm-operator":{"0|1|2|a|as":{action_:["sb=false","output",{type_:"operator",option:"\\pm"}],nextState:"0"}},operator:{"0|1|2|a|as":{action_:["sb=false","output","operator"],nextState:"0"}},"-$":{"o|q":{action_:["charge or bond","output"],nextState:"qd"},d:{action_:"d=",nextState:"d"},D:{action_:["output",{type_:"bond",option:"-"}],nextState:"3"},q:{action_:"d=",nextState:"qd"},qd:{action_:"d=",nextState:"qd"},"qD|dq":{action_:["output",{type_:"bond",option:"-"}],nextState:"3"}},"-9":{"3|o":{action_:["output",{type_:"insert",option:"hyphen"}],nextState:"3"}},"- orbital overlap":{o:{action_:["output",{type_:"insert",option:"hyphen"}],nextState:"2"},d:{action_:["output",{type_:"insert",option:"hyphen"}],nextState:"2"}},"-":{"0|1|2":{action_:[{type_:"output",option:1},"beginsWithBond=true",{type_:"bond",option:"-"}],nextState:"3"},3:{action_:{type_:"bond",option:"-"}},a:{action_:["output",{type_:"insert",option:"hyphen"}],nextState:"2"},as:{action_:[{type_:"output",option:2},{type_:"bond",option:"-"}],nextState:"3"},b:{action_:"b="},o:{action_:{type_:"- after o/d",option:!1},nextState:"2"},q:{action_:{type_:"- after o/d",option:!1},nextState:"2"},"d|qd|dq":{action_:{type_:"- after o/d",option:!0},nextState:"2"},"D|qD|p":{action_:["output",{type_:"bond",option:"-"}],nextState:"3"}},amount2:{"1|3":{action_:"a=",nextState:"a"}},letters:{"0|1|2|3|a|as|b|p|bp|o":{action_:"o=",nextState:"o"},"q|dq":{action_:["output","o="],nextState:"o"},"d|D|qd|qD":{action_:"o after d",nextState:"o"}},digits:{o:{action_:"q=",nextState:"q"},"d|D":{action_:"q=",nextState:"dq"},q:{action_:["output","o="],nextState:"o"},a:{action_:"o=",nextState:"o"}},"space A":{"b|p|bp":{}},space:{a:{nextState:"as"},0:{action_:"sb=false"},"1|2":{action_:"sb=true"},"r|rt|rd|rdt|rdq":{action_:"output",nextState:"0"},"*":{action_:["output","sb=true"],nextState:"1"}},"1st-level escape":{"1|2":{action_:["output",{type_:"insert+p1",option:"1st-level escape"}]},"*":{action_:["output",{type_:"insert+p1",option:"1st-level escape"}],nextState:"0"}},"[(...)]":{"r|rt":{action_:"rd=",nextState:"rd"},"rd|rdt":{action_:"rq=",nextState:"rdq"}},"...":{"o|d|D|dq|qd|qD":{action_:["output",{type_:"bond",option:"..."}],nextState:"3"},"*":{action_:[{type_:"output",option:1},{type_:"insert",option:"ellipsis"}],nextState:"1"}},". |* ":{"*":{action_:["output",{type_:"insert",option:"addition compound"}],nextState:"1"}},"state of aggregation $":{"*":{action_:["output","state of aggregation"],nextState:"1"}},"{[(":{"a|as|o":{action_:["o=","output","parenthesisLevel++"],nextState:"2"},"0|1|2|3":{action_:["o=","output","parenthesisLevel++"],nextState:"2"},"*":{action_:["output","o=","output","parenthesisLevel++"],nextState:"2"}},")]}":{"0|1|2|3|b|p|bp|o":{action_:["o=","parenthesisLevel--"],nextState:"o"},"a|as|d|D|q|qd|qD|dq":{action_:["output","o=","parenthesisLevel--"],nextState:"o"}},", ":{"*":{action_:["output","comma"],nextState:"0"}},"^_":{"*":{}},"^{(...)}|^($...$)":{"0|1|2|as":{action_:"b=",nextState:"b"},p:{action_:"b=",nextState:"bp"},"3|o":{action_:"d= kv",nextState:"D"},q:{action_:"d=",nextState:"qD"},"d|D|qd|qD|dq":{action_:["output","d="],nextState:"D"}},"^a|^\\x{}{}|^\\x{}|^\\x|'":{"0|1|2|as":{action_:"b=",nextState:"b"},p:{action_:"b=",nextState:"bp"},"3|o":{action_:"d= kv",nextState:"d"},q:{action_:"d=",nextState:"qd"},"d|qd|D|qD":{action_:"d="},dq:{action_:["output","d="],nextState:"d"}},"_{(state of aggregation)}$":{"d|D|q|qd|qD|dq":{action_:["output","q="],nextState:"q"}},"_{(...)}|_($...$)|_9|_\\x{}{}|_\\x{}|_\\x":{"0|1|2|as":{action_:"p=",nextState:"p"},b:{action_:"p=",nextState:"bp"},"3|o":{action_:"q=",nextState:"q"},"d|D":{action_:"q=",nextState:"dq"},"q|qd|qD|dq":{action_:["output","q="],nextState:"q"}},"=<>":{"0|1|2|3|a|as|o|q|d|D|qd|qD|dq":{action_:[{type_:"output",option:2},"bond"],nextState:"3"}},"#":{"0|1|2|3|a|as|o":{action_:[{type_:"output",option:2},{type_:"bond",option:"#"}],nextState:"3"}},"{}":{"*":{action_:{type_:"output",option:1},nextState:"1"}},"{...}":{"0|1|2|3|a|as|b|p|bp":{action_:"o=",nextState:"o"},"o|d|D|q|qd|qD|dq":{action_:["output","o="],nextState:"o"}},"$...$":{a:{action_:"a="},"0|1|2|3|as|b|p|bp|o":{action_:"o=",nextState:"o"},"as|o":{action_:"o="},"q|d|D|qd|qD|dq":{action_:["output","o="],nextState:"o"}},"\\bond{(...)}":{"*":{action_:[{type_:"output",option:2},"bond"],nextState:"3"}},"\\frac{(...)}":{"*":{action_:[{type_:"output",option:1},"frac-output"],nextState:"3"}},"\\overset{(...)}":{"*":{action_:[{type_:"output",option:2},"overset-output"],nextState:"3"}},"\\underset{(...)}":{"*":{action_:[{type_:"output",option:2},"underset-output"],nextState:"3"}},"\\underbrace{(...)}":{"*":{action_:[{type_:"output",option:2},"underbrace-output"],nextState:"3"}},"\\color{(...)}{(...)}1|\\color(...){(...)}2":{"*":{action_:[{type_:"output",option:2},"color-output"],nextState:"3"}},"\\color{(...)}0":{"*":{action_:[{type_:"output",option:2},"color0-output"]}},"\\ce{(...)}":{"*":{action_:[{type_:"output",option:2},"ce"],nextState:"3"}},"\\,":{"*":{action_:[{type_:"output",option:1},"copy"],nextState:"1"}},"\\x{}{}|\\x{}|\\x":{"0|1|2|3|a|as|b|p|bp|o|c0":{action_:["o=","output"],nextState:"3"},"*":{action_:["output","o=","output"],nextState:"3"}},others:{"*":{action_:[{type_:"output",option:1},"copy"],nextState:"3"}},else2:{a:{action_:"a to o",nextState:"o",revisit:!0},as:{action_:["output","sb=true"],nextState:"1",revisit:!0},"r|rt|rd|rdt|rdq":{action_:["output"],nextState:"0",revisit:!0},"*":{action_:["output","copy"],nextState:"3"}}}),actions:{"o after d":function(e,t){var r;if((e.d||"").match(/^[0-9]+$/)){var n=e.d;e.d=void 0,r=this.output(e),e.b=n}else r=this.output(e);return sc.actions["o="](e,t),r},"d= kv":function(e,t){e.d=t,e.dType="kv"},"charge or bond":function(e,t){if(e.beginsWithBond){var r=[];return sc.concatArray(r,this.output(e)),sc.concatArray(r,sc.actions.bond(e,t,"-")),r}e.d=t},"- after o/d":function(e,t,r){var n=sc.patterns.match_("orbital",e.o||""),a=sc.patterns.match_("one lowercase greek letter $",e.o||""),i=sc.patterns.match_("one lowercase latin letter $",e.o||""),o=sc.patterns.match_("$one lowercase latin letter$ $",e.o||""),s="-"===t&&(n&&""===n.remainder||a||i||o);!s||e.a||e.b||e.p||e.d||e.q||n||!i||(e.o="$"+e.o+"$");var l=[];return s?(sc.concatArray(l,this.output(e)),l.push({type_:"hyphen"})):(n=sc.patterns.match_("digits",e.d||""),r&&n&&""===n.remainder?(sc.concatArray(l,sc.actions["d="](e,t)),sc.concatArray(l,this.output(e))):(sc.concatArray(l,this.output(e)),sc.concatArray(l,sc.actions.bond(e,t,"-")))),l},"a to o":function(e){e.o=e.a,e.a=void 0},"sb=true":function(e){e.sb=!0},"sb=false":function(e){e.sb=!1},"beginsWithBond=true":function(e){e.beginsWithBond=!0},"beginsWithBond=false":function(e){e.beginsWithBond=!1},"parenthesisLevel++":function(e){e.parenthesisLevel++},"parenthesisLevel--":function(e){e.parenthesisLevel--},"state of aggregation":function(e,t){return{type_:"state of aggregation",p1:sc.go(t,"o")}},comma:function(e,t){var r=t.replace(/\s*$/,"");return r!==t&&0===e.parenthesisLevel?{type_:"comma enumeration L",p1:r}:{type_:"comma enumeration M",p1:r}},output:function(e,t,r){var n,a,i;e.r?(a="M"===e.rdt?sc.go(e.rd,"tex-math"):"T"===e.rdt?[{type_:"text",p1:e.rd||""}]:sc.go(e.rd),i="M"===e.rqt?sc.go(e.rq,"tex-math"):"T"===e.rqt?[{type_:"text",p1:e.rq||""}]:sc.go(e.rq),n={type_:"arrow",r:e.r,rd:a,rq:i}):(n=[],(e.a||e.b||e.p||e.o||e.q||e.d||r)&&(e.sb&&n.push({type_:"entitySkip"}),e.o||e.q||e.d||e.b||e.p||2===r?e.o||e.q||e.d||!e.b&&!e.p?e.o&&"kv"===e.dType&&sc.patterns.match_("d-oxidation$",e.d||"")?e.dType="oxidation":e.o&&"kv"===e.dType&&!e.q&&(e.dType=void 0):(e.o=e.a,e.d=e.b,e.q=e.p,e.a=e.b=e.p=void 0):(e.o=e.a,e.a=void 0),n.push({type_:"chemfive",a:sc.go(e.a,"a"),b:sc.go(e.b,"bd"),p:sc.go(e.p,"pq"),o:sc.go(e.o,"o"),q:sc.go(e.q,"pq"),d:sc.go(e.d,"oxidation"===e.dType?"oxidation":"bd"),dType:e.dType})));for(var o in e)"parenthesisLevel"!==o&&"beginsWithBond"!==o&&delete e[o];return n},"oxidation-output":function(e,t){var r=["{"];return sc.concatArray(r,sc.go(t,"oxidation")),r.push("}"),r},"frac-output":function(e,t){return{type_:"frac-ce",p1:sc.go(t[0]),p2:sc.go(t[1])}},"overset-output":function(e,t){return{type_:"overset",p1:sc.go(t[0]),p2:sc.go(t[1])}},"underset-output":function(e,t){return{type_:"underset",p1:sc.go(t[0]),p2:sc.go(t[1])}},"underbrace-output":function(e,t){return{type_:"underbrace",p1:sc.go(t[0]),p2:sc.go(t[1])}},"color-output":function(e,t){return{type_:"color",color1:t[0],color2:sc.go(t[1])}},"r=":function(e,t){e.r=t},"rdt=":function(e,t){e.rdt=t},"rd=":function(e,t){e.rd=t},"rqt=":function(e,t){e.rqt=t},"rq=":function(e,t){e.rq=t},operator:function(e,t,r){return{type_:"operator",kind_:r||t}}}},a:{transitions:sc.createTransitions({empty:{"*":{}},"1/2$":{0:{action_:"1/2"}},else:{0:{nextState:"1",revisit:!0}},"$(...)$":{"*":{action_:"tex-math tight",nextState:"1"}},",":{"*":{action_:{type_:"insert",option:"commaDecimal"}}},else2:{"*":{action_:"copy"}}}),actions:{}},o:{transitions:sc.createTransitions({empty:{"*":{}},"1/2$":{0:{action_:"1/2"}},else:{0:{nextState:"1",revisit:!0}},letters:{"*":{action_:"rm"}},"\\ca":{"*":{action_:{type_:"insert",option:"circa"}}},"\\x{}{}|\\x{}|\\x":{"*":{action_:"copy"}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},"{(...)}":{"*":{action_:"{text}"}},else2:{"*":{action_:"copy"}}}),actions:{}},text:{transitions:sc.createTransitions({empty:{"*":{action_:"output"}},"{...}":{"*":{action_:"text="}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},"\\greek":{"*":{action_:["output","rm"]}},"\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:["output","copy"]}},else:{"*":{action_:"text="}}}),actions:{output:function(e){if(e.text_){var t={type_:"text",p1:e.text_};for(var r in e)delete e[r];return t}}}},pq:{transitions:sc.createTransitions({empty:{"*":{}},"state of aggregation $":{"*":{action_:"state of aggregation"}},i$:{0:{nextState:"!f",revisit:!0}},"(KV letters),":{0:{action_:"rm",nextState:"0"}},formula$:{0:{nextState:"f",revisit:!0}},"1/2$":{0:{action_:"1/2"}},else:{0:{nextState:"!f",revisit:!0}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},"{(...)}":{"*":{action_:"text"}},"a-z":{f:{action_:"tex-math"}},letters:{"*":{action_:"rm"}},"-9.,9":{"*":{action_:"9,9"}},",":{"*":{action_:{type_:"insert+p1",option:"comma enumeration S"}}},"\\color{(...)}{(...)}1|\\color(...){(...)}2":{"*":{action_:"color-output"}},"\\color{(...)}0":{"*":{action_:"color0-output"}},"\\ce{(...)}":{"*":{action_:"ce"}},"\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:"copy"}},else2:{"*":{action_:"copy"}}}),actions:{"state of aggregation":function(e,t){return{type_:"state of aggregation subscript",p1:sc.go(t,"o")}},"color-output":function(e,t){return{type_:"color",color1:t[0],color2:sc.go(t[1],"pq")}}}},bd:{transitions:sc.createTransitions({empty:{"*":{}},x$:{0:{nextState:"!f",revisit:!0}},formula$:{0:{nextState:"f",revisit:!0}},else:{0:{nextState:"!f",revisit:!0}},"-9.,9 no missing 0":{"*":{action_:"9,9"}},".":{"*":{action_:{type_:"insert",option:"electron dot"}}},"a-z":{f:{action_:"tex-math"}},x:{"*":{action_:{type_:"insert",option:"KV x"}}},letters:{"*":{action_:"rm"}},"'":{"*":{action_:{type_:"insert",option:"prime"}}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},"{(...)}":{"*":{action_:"text"}},"\\color{(...)}{(...)}1|\\color(...){(...)}2":{"*":{action_:"color-output"}},"\\color{(...)}0":{"*":{action_:"color0-output"}},"\\ce{(...)}":{"*":{action_:"ce"}},"\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:"copy"}},else2:{"*":{action_:"copy"}}}),actions:{"color-output":function(e,t){return{type_:"color",color1:t[0],color2:sc.go(t[1],"bd")}}}},oxidation:{transitions:sc.createTransitions({empty:{"*":{}},"roman numeral":{"*":{action_:"roman-numeral"}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},else:{"*":{action_:"copy"}}}),actions:{"roman-numeral":function(e,t){return{type_:"roman numeral",p1:t||""}}}},"tex-math":{transitions:sc.createTransitions({empty:{"*":{action_:"output"}},"\\ce{(...)}":{"*":{action_:["output","ce"]}},"{...}|\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:"o="}},else:{"*":{action_:"o="}}}),actions:{output:function(e){if(e.o){var t={type_:"tex-math",p1:e.o};for(var r in e)delete e[r];return t}}}},"tex-math tight":{transitions:sc.createTransitions({empty:{"*":{action_:"output"}},"\\ce{(...)}":{"*":{action_:["output","ce"]}},"{...}|\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:"o="}},"-|+":{"*":{action_:"tight operator"}},else:{"*":{action_:"o="}}}),actions:{"tight operator":function(e,t){e.o=(e.o||"")+"{"+t+"}"},output:function(e){if(e.o){var t={type_:"tex-math",p1:e.o};for(var r in e)delete e[r];return t}}}},"9,9":{transitions:sc.createTransitions({empty:{"*":{}},",":{"*":{action_:"comma"}},else:{"*":{action_:"copy"}}}),actions:{comma:function(){return{type_:"commaDecimal"}}}},pu:{transitions:sc.createTransitions({empty:{"*":{action_:"output"}},space$:{"*":{action_:["output","space"]}},"{[(|)]}":{"0|a":{action_:"copy"}},"(-)(9)^(-9)":{0:{action_:"number^",nextState:"a"}},"(-)(9.,9)(e)(99)":{0:{action_:"enumber",nextState:"a"}},space:{"0|a":{}},"pm-operator":{"0|a":{action_:{type_:"operator",option:"\\pm"},nextState:"0"}},operator:{"0|a":{action_:"copy",nextState:"0"}},"//":{d:{action_:"o=",nextState:"/"}},"/":{d:{action_:"o=",nextState:"/"}},"{...}|else":{"0|d":{action_:"d=",nextState:"d"},a:{action_:["space","d="],nextState:"d"},"/|q":{action_:"q=",nextState:"q"}}}),actions:{enumber:function(e,t){var r=[];return"+-"===t[0]||"+/-"===t[0]?r.push("\\pm "):t[0]&&r.push(t[0]),t[1]&&(sc.concatArray(r,sc.go(t[1],"pu-9,9")),t[2]&&(t[2].match(/[,.]/)?sc.concatArray(r,sc.go(t[2],"pu-9,9")):r.push(t[2])),t[3]=t[4]||t[3],t[3]&&(t[3]=t[3].trim(),"e"===t[3]||"*"===t[3].substr(0,1)?r.push({type_:"cdot"}):r.push({type_:"times"}))),t[3]&&r.push("10^{"+t[5]+"}"),r},"number^":function(e,t){var r=[];return"+-"===t[0]||"+/-"===t[0]?r.push("\\pm "):t[0]&&r.push(t[0]),sc.concatArray(r,sc.go(t[1],"pu-9,9")),r.push("^{"+t[2]+"}"),r},operator:function(e,t,r){return{type_:"operator",kind_:r||t}},space:function(){return{type_:"pu-space-1"}},output:function(e){var t,r=sc.patterns.match_("{(...)}",e.d||"");r&&""===r.remainder&&(e.d=r.match_);var n=sc.patterns.match_("{(...)}",e.q||"");if(n&&""===n.remainder&&(e.q=n.match_),e.d&&(e.d=e.d.replace(/\u00B0C|\^oC|\^{o}C/g,"{}^{\\circ}C"),e.d=e.d.replace(/\u00B0F|\^oF|\^{o}F/g,"{}^{\\circ}F")),e.q){e.q=e.q.replace(/\u00B0C|\^oC|\^{o}C/g,"{}^{\\circ}C"),e.q=e.q.replace(/\u00B0F|\^oF|\^{o}F/g,"{}^{\\circ}F");var a={d:sc.go(e.d,"pu"),q:sc.go(e.q,"pu")};"//"===e.o?t={type_:"pu-frac",p1:a.d,p2:a.q}:(t=a.d,a.d.length>1||a.q.length>1?t.push({type_:" / "}):t.push({type_:"/"}),sc.concatArray(t,a.q))}else t=sc.go(e.d,"pu-2");for(var i in e)delete e[i];return t}}},"pu-2":{transitions:sc.createTransitions({empty:{"*":{action_:"output"}},"*":{"*":{action_:["output","cdot"],nextState:"0"}},"\\x":{"*":{action_:"rm="}},space:{"*":{action_:["output","space"],nextState:"0"}},"^{(...)}|^(-1)":{1:{action_:"^(-1)"}},"-9.,9":{0:{action_:"rm=",nextState:"0"},1:{action_:"^(-1)",nextState:"0"}},"{...}|else":{"*":{action_:"rm=",nextState:"1"}}}),actions:{cdot:function(){return{type_:"tight cdot"}},"^(-1)":function(e,t){e.rm+="^{"+t+"}"},space:function(){return{type_:"pu-space-2"}},output:function(e){var t=[];if(e.rm){var r=sc.patterns.match_("{(...)}",e.rm||"");t=r&&""===r.remainder?sc.go(r.match_,"pu"):{type_:"rm",p1:e.rm}}for(var n in e)delete e[n];return t}}},"pu-9,9":{transitions:sc.createTransitions({empty:{0:{action_:"output-0"},o:{action_:"output-o"}},",":{0:{action_:["output-0","comma"],nextState:"o"}},".":{0:{action_:["output-0","copy"],nextState:"o"}},else:{"*":{action_:"text="}}}),actions:{comma:function(){return{type_:"commaDecimal"}},"output-0":function(e){var t=[];if(e.text_=e.text_||"",e.text_.length>4){var r=e.text_.length%3;0===r&&(r=3);for(var n=e.text_.length-3;n>0;n-=3)t.push(e.text_.substr(n,3)),t.push({type_:"1000 separator"});t.push(e.text_.substr(0,r)),t.reverse()}else t.push(e.text_);for(var a in e)delete e[a];return t},"output-o":function(e){var t=[];if(e.text_=e.text_||"",e.text_.length>4){for(var r=e.text_.length-3,n=0;n<r;n+=3)t.push(e.text_.substr(n,3)),t.push({type_:"1000 separator"});t.push(e.text_.substr(n))}else t.push(e.text_);for(var a in e)delete e[a];return t}}}};var lc={go:function(e,t){if(!e)return"";for(var r="",n=!1,a=0;a<e.length;a++){var i=e[a];"string"==typeof i?r+=i:(r+=lc._go2(i),"1st-level escape"===i.type_&&(n=!0))}return t||n||!r||(r="{"+r+"}"),r},_goInner:function(e){return e?lc.go(e,!0):e},_go2:function(e){var t;switch(e.type_){case"chemfive":t="";var r={a:lc._goInner(e.a),b:lc._goInner(e.b),p:lc._goInner(e.p),o:lc._goInner(e.o),q:lc._goInner(e.q),d:lc._goInner(e.d)};r.a&&(r.a.match(/^[+\-]/)&&(r.a="{"+r.a+"}"),t+=r.a+"\\,"),(r.b||r.p)&&(t+="{\\vphantom{X}}",t+="^{\\hphantom{"+(r.b||"")+"}}_{\\hphantom{"+(r.p||"")+"}}",t+="{\\vphantom{X}}",t+="^{\\smash[t]{\\vphantom{2}}\\mathllap{"+(r.b||"")+"}}",t+="_{\\vphantom{2}\\mathllap{\\smash[t]{"+(r.p||"")+"}}}"),r.o&&(r.o.match(/^[+\-]/)&&(r.o="{"+r.o+"}"),t+=r.o),"kv"===e.dType?((r.d||r.q)&&(t+="{\\vphantom{X}}"),r.d&&(t+="^{"+r.d+"}"),r.q&&(t+="_{\\smash[t]{"+r.q+"}}")):"oxidation"===e.dType?(r.d&&(t+="{\\vphantom{X}}",t+="^{"+r.d+"}"),r.q&&(t+="{\\vphantom{X}}",t+="_{\\smash[t]{"+r.q+"}}")):(r.q&&(t+="{\\vphantom{X}}",t+="_{\\smash[t]{"+r.q+"}}"),r.d&&(t+="{\\vphantom{X}}",t+="^{"+r.d+"}"));break;case"rm":case"roman numeral":t="\\mathrm{"+e.p1+"}";break;case"text":e.p1.match(/[\^_]/)?(e.p1=e.p1.replace(" ","~").replace("-","\\text{-}"),t="\\mathrm{"+e.p1+"}"):t="\\text{"+e.p1+"}";break;case"state of aggregation":t="\\mskip2mu "+lc._goInner(e.p1);break;case"state of aggregation subscript":t="\\mskip1mu "+lc._goInner(e.p1);break;case"bond":if(!(t=lc._getBond(e.kind_)))throw["MhchemErrorBond","mhchem Error. Unknown bond type ("+e.kind_+")"];break;case"frac":var n="\\frac{"+e.p1+"}{"+e.p2+"}";t="\\mathchoice{\\textstyle"+n+"}{"+n+"}{"+n+"}{"+n+"}";break;case"pu-frac":var a="\\frac{"+lc._goInner(e.p1)+"}{"+lc._goInner(e.p2)+"}";t="\\mathchoice{\\textstyle"+a+"}{"+a+"}{"+a+"}{"+a+"}";break;case"tex-math":case"1st-level escape":t=e.p1+" ";break;case"frac-ce":t="\\frac{"+lc._goInner(e.p1)+"}{"+lc._goInner(e.p2)+"}";break;case"overset":t="\\overset{"+lc._goInner(e.p1)+"}{"+lc._goInner(e.p2)+"}";break;case"underset":t="\\underset{"+lc._goInner(e.p1)+"}{"+lc._goInner(e.p2)+"}";break;case"underbrace":t="\\underbrace{"+lc._goInner(e.p1)+"}_{"+lc._goInner(e.p2)+"}";break;case"color":t="{\\color{"+e.color1+"}{"+lc._goInner(e.color2)+"}}";break;case"color0":t="\\color{"+e.color+"}";break;case"arrow":var i={rd:lc._goInner(e.rd),rq:lc._goInner(e.rq)},o="\\x"+lc._getArrow(e.r);i.rq&&(o+="[{"+i.rq+"}]"),t=o+=i.rd?"{"+i.rd+"}":"{}";break;case"operator":t=lc._getOperator(e.kind_);break;case"space":t=" ";break;case"entitySkip":case"pu-space-1":t="~";break;case"pu-space-2":t="\\mkern3mu ";break;case"1000 separator":t="\\mkern2mu ";break;case"commaDecimal":t="{,}";break;case"comma enumeration L":t="{"+e.p1+"}\\mkern6mu ";break;case"comma enumeration M":t="{"+e.p1+"}\\mkern3mu ";break;case"comma enumeration S":t="{"+e.p1+"}\\mkern1mu ";break;case"hyphen":t="\\text{-}";break;case"addition compound":t="\\,{\\cdot}\\,";break;case"electron dot":t="\\mkern1mu \\bullet\\mkern1mu ";break;case"KV x":t="{\\times}";break;case"prime":t="\\prime ";break;case"cdot":t="\\cdot ";break;case"tight cdot":t="\\mkern1mu{\\cdot}\\mkern1mu ";break;case"times":t="\\times ";break;case"circa":t="{\\sim}";break;case"^":t="uparrow";break;case"v":t="downarrow";break;case"ellipsis":t="\\ldots ";break;case"/":t="/";break;case" / ":t="\\,/\\,";break;default:throw["MhchemBugT","mhchem bug T. Please report."]}return t},_getArrow:function(e){switch(e){case"->":case"→":case"⟶":return"rightarrow";case"<-":return"leftarrow";case"<->":return"leftrightarrow";case"<--\x3e":return"rightleftarrows";case"<=>":case"⇌":return"rightleftharpoons";case"<=>>":return"rightequilibrium";case"<<=>":return"leftequilibrium";default:throw["MhchemBugT","mhchem bug T. Please report."]}},_getBond:function(e){switch(e){case"-":case"1":return"{-}";case"=":case"2":return"{=}";case"#":case"3":return"{\\equiv}";case"~":return"{\\tripledash}";case"~-":return"{\\mathrlap{\\raisebox{-.1em}{$-$}}\\raisebox{.1em}{$\\tripledash$}}";case"~=":case"~--":return"{\\mathrlap{\\raisebox{-.2em}{$-$}}\\mathrlap{\\raisebox{.2em}{$\\tripledash$}}-}";case"-~-":return"{\\mathrlap{\\raisebox{-.2em}{$-$}}\\mathrlap{\\raisebox{.2em}{$-$}}\\tripledash}";case"...":return"{{\\cdot}{\\cdot}{\\cdot}}";case"....":return"{{\\cdot}{\\cdot}{\\cdot}{\\cdot}}";case"->":return"{\\rightarrow}";case"<-":return"{\\leftarrow}";case"<":return"{<}";case">":return"{>}";default:throw["MhchemBugT","mhchem bug T. Please report."]}},_getOperator:function(e){switch(e){case"+":return" {}+{} ";case"-":return" {}-{} ";case"=":return" {}={} ";case"<":return" {}<{} ";case">":return" {}>{} ";case"<<":return" {}\\ll{} ";case">>":return" {}\\gg{} ";case"\\pm":return" {}\\pm{} ";case"\\approx":case"$\\approx$":return" {}\\approx{} ";case"v":case"(v)":return" \\downarrow{} ";case"^":case"(^)":return" \\uparrow{} ";default:throw["MhchemBugT","mhchem bug T. Please report."]}}},cc=["katex","enableBareBlocks","enableMathBlockInHtml","enableMathInlineInHtml","enableFencedBlocks","macros","smiles"];function dc(e,t){var r=e.src[t-1],n=e.src[t],a=e.src[t+1];return"$"!==n?{can_open:!1,can_close:!1}:{can_open:"$"!==r&&"\\"!==r,can_close:"$"!==a}}function uc(e,t){var r=e.src[t-1],n=e.src[t],a=e.src[t+1],i=e.src[t+2];return"$"===n&&"$"!==r&&"\\"!==r&&"$"===a&&"$"!==i?{can_open:!0,can_close:!0}:{can_open:!1,can_close:!1}}function pc(e,t){if("$"!==e.src[e.pos])return!1;if(function(e){var t,r=new Set(["code","pre","kbd","samp","script","style","textarea"]),a=[],i=n(e);try{for(i.s();!(t=i.n()).done;){var o=t.value;if("html_inline"===o.type){var s=o.content.match(/^<(\/?)([a-z][\w-]*)\b/i);if(s&&r.has(s[2].toLowerCase())){var l=s[2].toLowerCase();if(s[1]){var c=a.lastIndexOf(l);-1!==c&&(a.length=c)}else/\/\s*>$/.test(o.content)||a.push(l)}}}}catch(e){i.e(e)}finally{i.f()}return a.length>0}(e.tokens))return!1;var r=dc(e,e.pos);if(!r.can_open)return t||(e.pending+="$"),e.pos+=1,!0;for(var a,i=e.pos+1,o=i;-1!==(o=e.src.indexOf("$",o));){for(a=o-1;"\\"===e.src[a];)a-=1;if((o-a)%2==1)break;o+=1}if(-1===o)return t||(e.pending+="$"),e.pos=i,!0;if(o-i===0)return t||(e.pending+="$$"),e.pos=i+1,!0;if(!(r=dc(e,o)).can_close)return t||(e.pending+="$"),e.pos=i,!0;if(!t){var s=e.push("math_inline","math",0);s.markup="$",s.content=e.src.slice(i,o)}return e.pos=o+1,!0}function _c(e,t){var r,n,a,i;if("$$"!==e.src.slice(e.pos,e.pos+2))return!1;if(!uc(e,e.pos).can_open)return t||(e.pending+="$$"),e.pos+=2,!0;for(n=r=e.pos+2;-1!==(n=e.src.indexOf("$$",n));){for(i=n-1;"\\"===e.src[i];)i-=1;if((n-i)%2==1)break;n+=2}return-1===n?(t||(e.pending+="$$"),e.pos=r,!0):n-r===0?(t||(e.pending+="$$$$"),e.pos=r+2,!0):uc(e,n).can_close?(t||((a=e.push("math_block","math",0)).block=!0,a.markup="$$",a.content=e.src.slice(r,n)),e.pos=n+2,!0):(t||(e.pending+="$$"),e.pos=r,!0)}function mc(e,t){var r=e.src.slice(e.pos);if(!/^\n\\begin/.test(r))return!1;if(e.pos+=1,t)return!0;var a,i=r.split(/\n/g).slice(1),o=[];e:for(var s=0;s<i.length;++s){var l,c=n(i[s].matchAll(/(\\begin|\\end)\s*\{([^{}]+)\}/g));try{for(c.s();!(l=c.n()).done;){var d=l.value;if("\\begin"===d[1])o.push(d[2].trim());else if("\\end"===d[1]&&(o.pop(),!o.length)){a=s;break e}}}catch(e){c.e(e)}finally{c.f()}}if(void 0===a)return!1;var u=i.slice(0,a+1).reduce(function(e,t){return e+t.length},0)+a+1,p=e.push("math_inline_bare_block","math",0);return p.block=!0,p.markup="$$",p.content=r.slice(1,u),e.pos=e.pos+u,!0}function gc(e,t,r,a){for(var i=e.tokens,s=i.length-1;s>=0;s--){var l=i[s],c=[];if("html_block"===l.type){var d,u=n(l.content.matchAll(a));try{for(u.s();!(d=u.n()).done;){var p=d.value;if(p.groups){var _=p.groups.html_before_math,m=p.groups.math,g=p.groups.html_after_math;_&&c.push(o(o({},l),{},{type:"html_block",map:null,content:_})),m&&c.push(o(o({},l),{},{type:t,map:null,content:m,markup:r,block:!0,tag:"math"})),g&&c.push(o(o({},l),{},{type:"html_block",map:null,content:g}))}}}catch(e){u.e(e)}finally{u.f()}c.length>0&&i.splice.apply(i,[s,1].concat(c))}}return!0}function hc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function fc(e,t){var r=t||{},a=r.katex,i=r.enableBareBlocks,s=r.enableMathBlockInHtml,l=r.enableMathInlineInHtml,d=r.enableFencedBlocks,u=r.macros,_=r.smiles,m=function(e,t){if(null==e)return{};var r,n,a=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==t.indexOf(n))continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}(r,cc),g=null!=a?a:ic,h=o({"\\smiles":na()},u||{}),f=!1===_?null:new ra(_||{});e.inline.ruler.after("escape","math_inline",pc),e.inline.ruler.after("escape","math_inline_block",_c),i&&e.inline.ruler.before("text","math_inline_bare_block",mc),e.block.ruler.after("blockquote","math_block",function(e,t,r,a){return!(!i||!function(e,t,r,a){var i=e.bMarks[t]+e.tShift[t],o=e.eMarks[t];if(!e.src.slice(i,o).match(/^\s*\\begin\s*\{([^{}]+)\}/))return!1;if(t>0){var s=e.bMarks[t-1]+e.tShift[t-1],l=e.eMarks[t-1],c=e.src.slice(s,l);if(!/^\s*$/.test(c))return!1}if(a)return!0;var d,u=[],p=t,_=!1;e:for(;!(_||p>=r);p++){var m=e.bMarks[p]+e.tShift[p],g=e.eMarks[p];if(m<g&&e.tShift[p]<e.blkIndent)break;var h,f=n(e.src.slice(m,g).matchAll(/(\\begin|\\end)\s*\{([^{}]+)\}/g));try{for(f.s();!(h=f.n()).done;){var E=h.value;if("\\begin"===E[1])u.push(E[2].trim());else if("\\end"===E[1]&&(u.pop(),!u.length)){d=e.src.slice(m,g),_=!0;break e}}}catch(e){f.e(e)}finally{f.f()}}e.line=p+1;var b=e.push("math_block","math",0);return b.block=!0,b.content=(e.getLines(t,p,e.tShift[t],!0)+(null!=d?d:"")).trim(),b.map=[t,e.line],b.markup="$$",!0}(e,t,r,a))||function(e,t,r,n){var a=!1,i=e.bMarks[t]+e.tShift[t],o=e.eMarks[t];if(i+2>o)return!1;if("$$"!==e.src.slice(i,i+2))return!1;i+=2;var s,l,d,u=e.src.slice(i,o),p=c(u.matchAll(/\$\$/g));if(1===p.length&&p[0].index===u.length-2)u=u.trim().slice(0,-2),a=!0;else if(p.length>1)return!1;if(n)return!0;for(l=t;!(a||++l>=r||(i=e.bMarks[l]+e.tShift[l])<(o=e.eMarks[l])&&e.tShift[l]<e.blkIndent);)"$$"===e.src.slice(i,o).trim().slice(-2)?(d=e.src.slice(0,o).lastIndexOf("$$"),s=e.src.slice(i,d),a=!0):e.src.slice(i,o).trim().includes("$$")&&(d=e.src.slice(0,o).trim().indexOf("$$"),s=e.src.slice(i,d),a=!0);e.line=l+1;var _=e.push("math_block","math",0);return _.block=!0,_.content=(u&&u.trim()?u+"\n":"")+e.getLines(t+1,l,e.tShift[t],!0)+(s&&s.trim()?s:""),_.map=[t,e.line],_.markup="$$",!0}(e,t,r,a)},{alt:["paragraph","reference","blockquote","list"]});var E=p(/([\s\S]*?)\$\$([\s\S]+?)\$\$((?:(?!\$\$[\s\S]+?\$\$)[\s\S])*)/gm,{html_before_math:1,math:2,html_after_math:3}),b=p(/([\s\S]*?)\$(.*?)\$((?:(?!\$.*?\$)[\s\S])*)/gm,{html_before_math:1,math:2,html_after_math:3});s&&e.core.ruler.push("math_block_in_html_block",function(e){return gc(e,"math_block","$$",E)}),l&&e.core.ruler.push("math_inline_in_html_block",function(e){return gc(e,"math_inline","$",b)});var S=function(r){var n=r.content;try{var a=g.renderToString(n,o(o({},m),{},{macros:h,displayMode:!0})),i=f?aa(a,f):a;return r.attrJoin("class","katex-block"),"<p".concat(e.renderer.renderAttrs(r),">").concat(i,"</p>")}catch(a){return null!=t&&t.throwOnError&&console.log(a),r.attrJoin("class","katex-block"),r.attrJoin("class","katex-error"),r.attrSet("title",hc(n)),"<p".concat(e.renderer.renderAttrs(r),">").concat(hc(a+""),"</p>")}},v=function(e,t){return S(e[t])+"\n"};if(e.renderer.rules.math_inline=function(e,r){var n=e[r].content;return function(e){var r=/\\begin\{(align|equation|gather|cd|alignat)\}/gi.test(e);try{var n=g.renderToString(e,o(o({},m),{},{macros:h,displayMode:r}));return f?aa(n,f):n}catch(r){return null!=t&&t.throwOnError&&console.log(r),'<span class="katex-error" title="'.concat(hc(e),'">').concat(hc(r+""),"</span>")}}(n.length>2&&"`"===n[0]&&"`"===n[n.length-1]?n.slice(1,-1):n)},e.renderer.rules.math_inline_block=v,e.renderer.rules.math_inline_bare_block=v,e.renderer.rules.math_block=v,d){var T=e.renderer.rules.fence;e.renderer.rules.fence=function(e,t,r,n,a){var i=e[t];return"math"===i.info.trim().toLowerCase()&&d?S(i)+"\n":(null==T?void 0:T.call(this,e,t,r,n,a))||""}}}var Ec={includeLevel:[1,2],containerClass:"table-of-contents",slugify:function(e){return encodeURIComponent(String(e).trim().toLowerCase().replace(/\s+/g,"-"))},markerPattern:/^\[\[toc\]\]/im,omitTag:"\x3c!-- omit from toc --\x3e",listType:"ul",format:function(e,t){return t.renderInline(e)},containerHeaderHtml:void 0,containerFooterHtml:void 0,transformLink:void 0,transformContainerOpen:function(e,t){var r='<div class="'+e+'">';return t&&(r+=t),r},transformContainerClose:function(e){var t="";return e&&(t=e),t+"</div>"},getTokensText:function(e){return e.filter(function(e){return["text","code_inline"].includes(e.type)}).map(function(e){return e.content}).join("").trim()}};function bc(e,t,r){var n=[],a=null;return t.forEach(function(i,o){if("heading_open"===i.type){var s=o>0?t[o-1]:null;if(s&&"html_block"===s.type&&s.content.trim().toLowerCase().replace("\n","")===r.omitTag)return;var c=function(e){if(e&&e.attrs&&e.attrs.length>0){var t=e.attrs.find(function(e){return!!(Array.isArray(e)&&e.length>=2)&&"id"===e[0]});if(t&&Array.isArray(t)&&t.length>=2)return l(t,2)[1]}return null}(i),d=parseInt(i.tag.toLowerCase().replace("h",""),10);e.indexOf(d)>=0&&(a={level:d,text:"",anchor:c||null,token:null})}else if(a&&"inline"===i.type){var u=r.getTokensText(i.children,i);a.text=u,a.token=i,a.anchor||(a.anchor=r.slugify(u,i))}else"heading_close"===i.type&&(a&&n.push(a),a=null)}),n}function Sc(e){return Math.min.apply(Math,c(e.map(function(e){return e.level})))}function vc(e,t,r,n){var a={level:e,text:t,anchor:r,children:[],parent:n};return n.children.push(a),a}function Tc(e,t,r){return"<"+t.listType+">"+e.children.map(function(e){var n="<li>",a=e.anchor;t&&t.transformLink&&(a=t.transformLink(a));var i=e.text?t.format(e.text,r,a):null;return(n+=a?'<a href="#'.concat(a,'">').concat(i,"</a>"):i||"")+(e.children.length>0?Tc(e,t,r):"")+"</li>"}).join("")+"</"+t.listType+">"}var yc=function(e,t){var r=Object.assign({},Ec,t),n=r.markerPattern;e.renderer.rules.toc_open=function(e,t,r,n,a){var i=e[t],o=Ec.containerClass||"table-of-contents",s=i.attrGet("class");s?s.includes(o)||i.attrJoin("class",o):i.attrSet("class",o);var l=a.renderAttrs(i),c="<div".concat(l,">");return Ec.containerHeaderHtml&&(c+=Ec.containerHeaderHtml),c},e.renderer.rules.toc_close=function(){return r.transformContainerClose(r.containerFooterHtml)+"\n"},e.renderer.rules.toc_body=function(t){var n=function(e){var t={level:Sc(e)-1,anchor:null,text:"",children:[],parent:null},r=t,n=r;return e.forEach(function(e){if(e.level>n.level)Array.from({length:e.level-n.level}).forEach(function(){r=n,n=vc(e.level,"",null,r)}),n.text=e.text,n.anchor=e.anchor;else if(e.level===n.level)n=vc(e.level,e.text,e.anchor,r);else if(e.level<n.level){for(var t=0;t<n.level-e.level;t++)r.parent&&(r=r.parent);n=vc(e.level,e.text,e.anchor,r)}}),t}(bc(r.includeLevel,t,r));return Tc(n,r,e)},e.block.ruler.before("heading","toc",function(e,t,r,a){var i,o,s=e.bMarks[t]+e.tShift[t],l=e.eMarks[t];return 91===e.src.charCodeAt(s)&&(!((o=(o=n.exec(e.src.substring(s,l)))?o.filter(function(e){return e}):[]).length<1)&&(a||(e.line=t+1,(i=e.push("toc_open","toc",1)).markup="[[toc]]",i.map=[t,e.line],(i=e.push("toc_body","",0)).markup="",i.map=[t,e.line],i.children=[],(i=e.push("toc_close","toc",-1)).markup=""),!0))},{alt:["paragraph","reference","blockquote"]})};function Cc(e){return e instanceof Map?e.clear=e.delete=e.set=function(){throw new Error("map is read-only")}:e instanceof Set&&(e.add=e.clear=e.delete=function(){throw new Error("set is read-only")}),Object.freeze(e),Object.getOwnPropertyNames(e).forEach(t=>{const r=e[t],n=typeof r;"object"!==n&&"function"!==n||Object.isFrozen(r)||Cc(r)}),e}class Nc{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function Rc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}function Ac(e,...t){const r=Object.create(null);for(const t in e)r[t]=e[t];return t.forEach(function(e){for(const t in e)r[t]=e[t]}),r}const Oc=e=>!!e.scope;class Ic{constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=Rc(e)}openNode(e){if(!Oc(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const r=e.split(".");return[`${t}${r.shift()}`,...r.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){Oc(e)&&(this.buffer+="</span>")}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}}const xc=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class wc{constructor(){this.rootNode=xc(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){const t=xc({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{wc._collapse(e)}))}}class Dc extends wc{constructor(e){super(),this.options=e}addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){const r=e.root;t&&(r.scope=`language:${t}`),this.add(r)}toHTML(){return new Ic(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function Mc(e){return e?"string"==typeof e?e:e.source:null}function kc(e){return Fc("(?=",e,")")}function Lc(e){return Fc("(?:",e,")*")}function Pc(e){return Fc("(?:",e,")?")}function Fc(...e){return e.map(e=>Mc(e)).join("")}function Bc(...e){const t=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(t.capture?"":"?:")+e.map(e=>Mc(e)).join("|")+")"}function Uc(e){return new RegExp(e.toString()+"|").exec("").length-1}const Gc=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function zc(e,{joinWith:t}){let r=0;return e.map(e=>{r+=1;const t=r;let n=Mc(e),a="";for(;n.length>0;){const e=Gc.exec(n);if(!e){a+=n;break}a+=n.substring(0,e.index),n=n.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?a+="\\"+String(Number(e[1])+t):(a+=e[0],"("===e[0]&&r++)}return a}).map(e=>`(${e})`).join(t)}const Yc="[a-zA-Z]\\w*",qc="[a-zA-Z_]\\w*",Hc="\\b\\d+(\\.\\d+)?",Vc="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",$c="\\b(0b[01]+)",Wc={begin:"\\\\[\\s\\S]",relevance:0},jc={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[Wc]},Qc={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[Wc]},Kc=function(e,t,r={}){const n=Ac({scope:"comment",begin:e,end:t,contains:[]},r);n.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const a=Bc("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return n.contains.push({begin:Fc(/[ ]+/,"(",a,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),n},Xc=Kc("//","$"),Zc=Kc("/\\*","\\*/"),Jc=Kc("#","$"),ed={scope:"number",begin:Hc,relevance:0},td={scope:"number",begin:Vc,relevance:0},rd={scope:"number",begin:$c,relevance:0},nd={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[Wc,{begin:/\[/,end:/\]/,relevance:0,contains:[Wc]}]},ad={scope:"title",begin:Yc,relevance:0},id={scope:"title",begin:qc,relevance:0},od={begin:"\\.\\s*"+qc,relevance:0};var sd=Object.freeze({__proto__:null,APOS_STRING_MODE:jc,BACKSLASH_ESCAPE:Wc,BINARY_NUMBER_MODE:rd,BINARY_NUMBER_RE:$c,COMMENT:Kc,C_BLOCK_COMMENT_MODE:Zc,C_LINE_COMMENT_MODE:Xc,C_NUMBER_MODE:td,C_NUMBER_RE:Vc,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:Jc,IDENT_RE:Yc,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:od,NUMBER_MODE:ed,NUMBER_RE:Hc,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:Qc,REGEXP_MODE:nd,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=Fc(t,/.*\b/,e.binary,/\b.*/)),Ac({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},TITLE_MODE:ad,UNDERSCORE_IDENT_RE:qc,UNDERSCORE_TITLE_MODE:id});function ld(e,t){"."===e.input[e.index-1]&&t.ignoreMatch()}function cd(e,t){void 0!==e.className&&(e.scope=e.className,delete e.className)}function dd(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=ld,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0))}function ud(e,t){Array.isArray(e.illegal)&&(e.illegal=Bc(...e.illegal))}function pd(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function _d(e,t){void 0===e.relevance&&(e.relevance=1)}const md=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const r=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]}),e.keywords=r.keywords,e.begin=Fc(r.beforeMatch,kc(r.begin)),e.starts={relevance:0,contains:[Object.assign(r,{endsParent:!0})]},e.relevance=0,delete r.beforeMatch},gd=["of","and","for","in","not","or","if","then","parent","list","value"];function hd(e,t,r="keyword"){const n=Object.create(null);return"string"==typeof e?a(r,e.split(" ")):Array.isArray(e)?a(r,e):Object.keys(e).forEach(function(r){Object.assign(n,hd(e[r],t,r))}),n;function a(e,r){t&&(r=r.map(e=>e.toLowerCase())),r.forEach(function(t){const r=t.split("|");n[r[0]]=[e,fd(r[0],r[1])]})}}function fd(e,t){return t?Number(t):function(e){return gd.includes(e.toLowerCase())}(e)?0:1}const Ed={},bd=e=>{console.error(e)},Sd=(e,...t)=>{console.log(`WARN: ${e}`,...t)},vd=(e,t)=>{Ed[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),Ed[`${e}/${t}`]=!0)},Td=new Error;function yd(e,t,{key:r}){let n=0;const a=e[r],i={},o={};for(let e=1;e<=t.length;e++)o[e+n]=a[e],i[e+n]=!0,n+=Uc(t[e-1]);e[r]=o,e[r]._emit=i,e[r]._multi=!0}function Cd(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope)}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw bd("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),Td;if("object"!=typeof e.beginScope||null===e.beginScope)throw bd("beginScope must be object"),Td;yd(e,e.begin,{key:"beginScope"}),e.begin=zc(e.begin,{joinWith:""})}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw bd("skip, excludeEnd, returnEnd not compatible with endScope: {}"),Td;if("object"!=typeof e.endScope||null===e.endScope)throw bd("endScope must be object"),Td;yd(e,e.end,{key:"endScope"}),e.end=zc(e.end,{joinWith:""})}}(e)}function Nd(e){function t(t,r){return new RegExp(Mc(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(r?"g":""))}class r{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=Uc(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=t(zc(e,{joinWith:"|"}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const r=t.findIndex((e,t)=>t>0&&void 0!==e),n=this.matchIndexes[r];return t.splice(0,r),Object.assign(t,n)}}class n{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new r;return this.rules.slice(e).forEach(([e,r])=>t.addRule(e,r)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let r=t.exec(e);if(this.resumingScanAtSamePosition())if(r&&r.index===this.lastIndex);else{const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,r=t.exec(e)}return r&&(this.regexIndex+=r.position+1,this.regexIndex===this.count&&this.considerAll()),r}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=Ac(e.classNameAliases||{}),function r(a,i){const o=a;if(a.isCompiled)return o;[cd,pd,Cd,md].forEach(e=>e(a,i)),e.compilerExtensions.forEach(e=>e(a,i)),a.__beforeBegin=null,[dd,ud,_d].forEach(e=>e(a,i)),a.isCompiled=!0;let s=null;return"object"==typeof a.keywords&&a.keywords.$pattern&&(a.keywords=Object.assign({},a.keywords),s=a.keywords.$pattern,delete a.keywords.$pattern),s=s||/\w+/,a.keywords&&(a.keywords=hd(a.keywords,e.case_insensitive)),o.keywordPatternRe=t(s,!0),i&&(a.begin||(a.begin=/\B|\b/),o.beginRe=t(o.begin),a.end||a.endsWithParent||(a.end=/\B|\b/),a.end&&(o.endRe=t(o.end)),o.terminatorEnd=Mc(o.end)||"",a.endsWithParent&&i.terminatorEnd&&(o.terminatorEnd+=(a.end?"|":"")+i.terminatorEnd)),a.illegal&&(o.illegalRe=t(a.illegal)),a.contains||(a.contains=[]),a.contains=[].concat(...a.contains.map(function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return Ac(e,{variants:null},t)}));if(e.cachedVariants)return e.cachedVariants;if(Rd(e))return Ac(e,{starts:e.starts?Ac(e.starts):null});if(Object.isFrozen(e))return Ac(e);return e}("self"===e?a:e)})),a.contains.forEach(function(e){r(e,o)}),a.starts&&r(a.starts,i),o.matcher=function(e){const t=new n;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(o),o}(e)}function Rd(e){return!!e&&(e.endsWithParent||Rd(e.starts))}class Ad extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}}const Od=Rc,Id=Ac,xd=Symbol("nomatch"),wd=function(e){const t=Object.create(null),r=Object.create(null),n=[];let a=!0;const i="Could not find the language '{}', did you forget to load/include a language module?",o={disableAutodetect:!0,name:"Plain text",contains:[]};let s={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:Dc};function l(e){return s.noHighlightRe.test(e)}function c(e,t,r){let n="",a="";"object"==typeof t?(n=e,r=t.ignoreIllegals,a=t.language):(vd("10.7.0","highlight(lang, code, ...args) has been deprecated."),vd("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),a=e,n=t),void 0===r&&(r=!0);const i={code:n,language:a};E("before:highlight",i);const o=i.result?i.result:d(i.language,i.code,r);return o.code=i.code,E("after:highlight",o),o}function d(e,r,n,o){const l=Object.create(null);function c(e,t){return e.keywords[t]}function p(){if(!R.keywords)return void O.addText(I);let e=0;R.keywordPatternRe.lastIndex=0;let t=R.keywordPatternRe.exec(I),r="";for(;t;){r+=I.substring(e,t.index);const n=y.case_insensitive?t[0].toLowerCase():t[0],a=c(R,n);if(a){const[e,i]=a;if(O.addText(r),r="",l[n]=(l[n]||0)+1,l[n]<=7&&(x+=i),e.startsWith("_"))r+=t[0];else{const r=y.classNameAliases[e]||e;m(t[0],r)}}else r+=t[0];e=R.keywordPatternRe.lastIndex,t=R.keywordPatternRe.exec(I)}r+=I.substring(e),O.addText(r)}function _(){null!=R.subLanguage?function(){if(""===I)return;let e=null;if("string"==typeof R.subLanguage){if(!t[R.subLanguage])return void O.addText(I);e=d(R.subLanguage,I,!0,A[R.subLanguage]),A[R.subLanguage]=e._top}else e=u(I,R.subLanguage.length?R.subLanguage:null);R.relevance>0&&(x+=e.relevance),O.__addSublanguage(e._emitter,e.language)}():p(),I=""}function m(e,t){""!==e&&(O.startScope(t),O.addText(e),O.endScope())}function h(e,t){let r=1;const n=t.length-1;for(;r<=n;){if(!e._emit[r]){r++;continue}const n=y.classNameAliases[e[r]]||e[r],a=t[r];n?m(a,n):(I=a,p(),I=""),r++}}function f(e,t){return e.scope&&"string"==typeof e.scope&&O.openNode(y.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(m(I,y.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),I=""):e.beginScope._multi&&(h(e.beginScope,t),I="")),R=Object.create(e,{parent:{value:R}}),R}function E(e,t,r){let n=function(e,t){const r=e&&e.exec(t);return r&&0===r.index}(e.endRe,r);if(n){if(e["on:end"]){const r=new Nc(e);e["on:end"](t,r),r.isMatchIgnored&&(n=!1)}if(n){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return E(e.parent,t,r)}function b(e){return 0===R.matcher.regexIndex?(I+=e[0],1):(M=!0,0)}function S(e){const t=e[0],n=r.substring(e.index),a=E(R,e,n);if(!a)return xd;const i=R;R.endScope&&R.endScope._wrap?(_(),m(t,R.endScope._wrap)):R.endScope&&R.endScope._multi?(_(),h(R.endScope,e)):i.skip?I+=t:(i.returnEnd||i.excludeEnd||(I+=t),_(),i.excludeEnd&&(I=t));do{R.scope&&O.closeNode(),R.skip||R.subLanguage||(x+=R.relevance),R=R.parent}while(R!==a.parent);return a.starts&&f(a.starts,e),i.returnEnd?0:t.length}let v={};function T(t,i){const o=i&&i[0];if(I+=t,null==o)return _(),0;if("begin"===v.type&&"end"===i.type&&v.index===i.index&&""===o){if(I+=r.slice(i.index,i.index+1),!a){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=v.rule,t}return 1}if(v=i,"begin"===i.type)return function(e){const t=e[0],r=e.rule,n=new Nc(r),a=[r.__beforeBegin,r["on:begin"]];for(const r of a)if(r&&(r(e,n),n.isMatchIgnored))return b(t);return r.skip?I+=t:(r.excludeBegin&&(I+=t),_(),r.returnBegin||r.excludeBegin||(I=t)),f(r,e),r.returnBegin?0:t.length}(i);if("illegal"===i.type&&!n){const e=new Error('Illegal lexeme "'+o+'" for mode "'+(R.scope||"<unnamed>")+'"');throw e.mode=R,e}if("end"===i.type){const e=S(i);if(e!==xd)return e}if("illegal"===i.type&&""===o)return I+="\n",1;if(D>1e5&&D>3*i.index){throw new Error("potential infinite loop, way more iterations than matches")}return I+=o,o.length}const y=g(e);if(!y)throw bd(i.replace("{}",e)),new Error('Unknown language: "'+e+'"');const C=Nd(y);let N="",R=o||C;const A={},O=new s.__emitter(s);!function(){const e=[];for(let t=R;t!==y;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>O.openNode(e))}();let I="",x=0,w=0,D=0,M=!1;try{if(y.__emitTokens)y.__emitTokens(r,O);else{for(R.matcher.considerAll();;){D++,M?M=!1:R.matcher.considerAll(),R.matcher.lastIndex=w;const e=R.matcher.exec(r);if(!e)break;const t=T(r.substring(w,e.index),e);w=e.index+t}T(r.substring(w))}return O.finalize(),N=O.toHTML(),{language:e,value:N,relevance:x,illegal:!1,_emitter:O,_top:R}}catch(t){if(t.message&&t.message.includes("Illegal"))return{language:e,value:Od(r),illegal:!0,relevance:0,_illegalBy:{message:t.message,index:w,context:r.slice(w-100,w+100),mode:t.mode,resultSoFar:N},_emitter:O};if(a)return{language:e,value:Od(r),illegal:!1,relevance:0,errorRaised:t,_emitter:O,_top:R};throw t}}function u(e,r){r=r||s.languages||Object.keys(t);const n=function(e){const t={value:Od(e),illegal:!1,relevance:0,_top:o,_emitter:new s.__emitter(s)};return t._emitter.addText(e),t}(e),a=r.filter(g).filter(f).map(t=>d(t,e,!1));a.unshift(n);const i=a.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(g(e.language).supersetOf===t.language)return 1;if(g(t.language).supersetOf===e.language)return-1}return 0}),[l,c]=i,u=l;return u.secondBest=c,u}function p(e){let t=null;const n=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const r=s.languageDetectRe.exec(t);if(r){const t=g(r[1]);return t||(Sd(i.replace("{}",r[1])),Sd("Falling back to no-highlight mode for this block.",e)),t?r[1]:"no-highlight"}return t.split(/\s+/).find(e=>l(e)||g(e))}(e);if(l(n))return;if(E("before:highlightElement",{el:e,language:n}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(s.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),s.throwUnescapedHTML)){throw new Ad("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const a=t.textContent,o=n?c(a,{language:n,ignoreIllegals:!0}):u(a);e.innerHTML=o.value,e.dataset.highlighted="yes",function(e,t,n){const a=t&&r[t]||n;e.classList.add("hljs"),e.classList.add(`language-${a}`)}(e,n,o.language),e.result={language:o.language,re:o.relevance,relevance:o.relevance},o.secondBest&&(e.secondBest={language:o.secondBest.language,relevance:o.secondBest.relevance}),E("after:highlightElement",{el:e,result:o,text:a})}let _=!1;function m(){if("loading"===document.readyState)return _||window.addEventListener("DOMContentLoaded",function(){m()},!1),void(_=!0);document.querySelectorAll(s.cssSelector).forEach(p)}function g(e){return e=(e||"").toLowerCase(),t[e]||t[r[e]]}function h(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{r[e.toLowerCase()]=t})}function f(e){const t=g(e);return t&&!t.disableAutodetect}function E(e,t){const r=e;n.forEach(function(e){e[r]&&e[r](t)})}Object.assign(e,{highlight:c,highlightAuto:u,highlightAll:m,highlightElement:p,highlightBlock:function(e){return vd("10.7.0","highlightBlock will be removed entirely in v12.0"),vd("10.7.0","Please use highlightElement now."),p(e)},configure:function(e){s=Id(s,e)},initHighlighting:()=>{m(),vd("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")},initHighlightingOnLoad:function(){m(),vd("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")},registerLanguage:function(r,n){let i=null;try{i=n(e)}catch(e){if(bd("Language definition for '{}' could not be registered.".replace("{}",r)),!a)throw e;bd(e),i=o}i.name||(i.name=r),t[r]=i,i.rawDefinition=n.bind(null,e),i.aliases&&h(i.aliases,{languageName:r})},unregisterLanguage:function(e){delete t[e];for(const t of Object.keys(r))r[t]===e&&delete r[t]},listLanguages:function(){return Object.keys(t)},getLanguage:g,registerAliases:h,autoDetection:f,inherit:Id,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t))}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t))})}(e),n.push(e)},removePlugin:function(e){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}),e.debugMode=function(){a=!1},e.safeMode=function(){a=!0},e.versionString="11.11.1",e.regex={concat:Fc,lookahead:kc,either:Bc,optional:Pc,anyNumberOfTimes:Lc};for(const e in sd)"object"==typeof sd[e]&&Cc(sd[e]);return Object.assign(e,sd),e},Dd=wd({});Dd.newInstance=()=>wd({});var Md,kd,Ld,Pd,Fd,Bd,Ud,Gd,zd,Yd,qd,Hd,Vd,$d,Wd,jd,Qd,Kd,Xd,Zd,Jd,eu,tu,ru,nu,au,iu,ou,su,lu,cu,du,uu,pu,_u,mu,gu,hu,fu,Eu,bu,Su,vu,Tu,yu,Cu,Nu,Ru,Au,Ou,Iu,xu,wu,Du,Mu,ku,Lu,Pu,Fu,Bu,Uu,Gu,zu,Yu,qu,Hu,Vu,$u,Wu,ju,Qu,Ku,Xu,Zu,Ju,ep,tp,rp,np,ap,ip,op,sp,lp,cp,dp,up,pp,_p,mp,gp,hp,fp,Ep,bp,Sp,vp,Tp,yp,Cp,Np,Rp,Ap,Op,Ip,xp,wp,Dp,Mp,kp,Lp,Pp,Fp,Bp,Up,Gp,zp,Yp,qp,Hp,Vp,$p,Wp,jp,Qp,Kp,Xp,Zp,Jp,e_,t_,r_,n_,a_,i_,o_,s_,l_,c_,d_,u_,p_,__,m_,g_,h_,f_,E_,b_,S_,v_,T_,y_,C_,N_,R_,A_,O_,I_,x_,w_,D_,M_,k_,L_,P_,F_,B_,U_,G_,z_,Y_,q_,H_,V_,$_,W_,j_,Q_,K_,X_,Z_,J_,em,tm,rm,nm,am,im,om,sm,lm,cm,dm,um,pm,_m,mm,gm,hm,fm,Em,bm,Sm,vm,Tm,ym,Cm,Nm,Rm,Am,Om,Im,xm,wm,Dm,Mm,km,Lm,Pm,Fm,Bm,Um,Gm,zm,Ym,qm,Hm,Vm,$m,Wm,jm,Qm,Km,Xm,Zm,Jm,eg,tg,rg,ng,ag,ig,og,sg,lg,cg,dg,ug,pg,_g,mg,gg,hg,fg,Eg,bg,Sg,vg,Tg,yg,Cg,Ng,Rg,Ag,Og,Ig,xg,wg,Dg,Mg,kg,Lg,Pg,Fg,Bg,Ug,Gg,zg,Yg,qg,Hg,Vg,$g,Wg,jg,Qg,Kg,Xg,Zg,Jg,eh,th,rh,nh,ah,ih,oh,sh,lh,ch,dh,uh,ph,_h,mh,gh,hh,fh,Eh,bh,Sh,vh,Th,yh,Ch,Nh,Rh,Ah,Oh,Ih,xh,wh,Dh,Mh,kh,Lh,Ph,Fh,Bh,Uh,Gh,zh,Yh,qh,Hh,Vh,$h,Wh,jh,Qh,Kh,Xh,Zh,Jh,ef,tf,rf,nf,af,of,sf,lf,cf,df,uf,pf,_f,mf,gf,hf,ff,Ef,bf,Sf,vf,Tf,yf,Cf,Nf,Rf,Af,Of,If,xf,wf,Df,Mf,kf,Lf,Pf,Ff,Bf,Uf,Gf=Dd;Dd.HighlightJS=Dd,Dd.default=Dd;var zf=Gf;zf.registerLanguage("1c",(kd||(kd=1,Md=function(e){const t="[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]+",r="далее возврат вызватьисключение выполнить для если и из или иначе иначеесли исключение каждого конецесли конецпопытки конеццикла не новый перейти перем по пока попытка прервать продолжить тогда цикл экспорт ",n="null истина ложь неопределено",a=e.inherit(e.NUMBER_MODE),i={className:"string",begin:'"|\\|',end:'"|$',contains:[{begin:'""'}]},o={begin:"'",end:"'",excludeBegin:!0,excludeEnd:!0,contains:[{className:"number",begin:"\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}"}]},s=e.inherit(e.C_LINE_COMMENT_MODE);return{name:"1C:Enterprise",case_insensitive:!0,keywords:{$pattern:t,keyword:r,built_in:"разделительстраниц разделительстрок символтабуляции ansitooem oemtoansi ввестивидсубконто ввестиперечисление ввестипериод ввестиплансчетов выбранныйплансчетов датагод датамесяц датачисло заголовоксистемы значениевстроку значениеизстроки каталогиб каталогпользователя кодсимв конгода конецпериодаби конецрассчитанногопериодаби конецстандартногоинтервала конквартала конмесяца коннедели лог лог10 максимальноеколичествосубконто названиеинтерфейса названиенабораправ назначитьвид назначитьсчет найтиссылки началопериодаби началостандартногоинтервала начгода начквартала начмесяца начнедели номерднягода номерднянедели номернеделигода обработкаожидания основнойжурналрасчетов основнойплансчетов основнойязык очиститьокносообщений периодстр получитьвремята получитьдатута получитьдокументта получитьзначенияотбора получитьпозициюта получитьпустоезначение получитьта префиксавтонумерации пропись пустоезначение разм разобратьпозициюдокумента рассчитатьрегистрына рассчитатьрегистрыпо симв создатьобъект статусвозврата стрколичествострок сформироватьпозициюдокумента счетпокоду текущеевремя типзначения типзначениястр установитьтана установитьтапо фиксшаблон шаблон acos asin atan base64значение base64строка cos exp log log10 pow sin sqrt tan xmlзначение xmlстрока xmlтип xmlтипзнч активноеокно безопасныйрежим безопасныйрежимразделенияданных булево ввестидату ввестизначение ввестистроку ввестичисло возможностьчтенияxml вопрос восстановитьзначение врег выгрузитьжурналрегистрации выполнитьобработкуоповещения выполнитьпроверкуправдоступа вычислить год данныеформывзначение дата день деньгода деньнедели добавитьмесяц заблокироватьданныедляредактирования заблокироватьработупользователя завершитьработусистемы загрузитьвнешнююкомпоненту закрытьсправку записатьjson записатьxml записатьдатуjson записьжурналарегистрации заполнитьзначениясвойств запроситьразрешениепользователя запуститьприложение запуститьсистему зафиксироватьтранзакцию значениевданныеформы значениевстрокувнутр значениевфайл значениезаполнено значениеизстрокивнутр значениеизфайла изxmlтипа импортмоделиxdto имякомпьютера имяпользователя инициализироватьпредопределенныеданные информацияобошибке каталогбиблиотекимобильногоустройства каталогвременныхфайлов каталогдокументов каталогпрограммы кодироватьстроку кодлокализацииинформационнойбазы кодсимвола командасистемы конецгода конецдня конецквартала конецмесяца конецминуты конецнедели конецчаса конфигурациябазыданныхизмененадинамически конфигурацияизменена копироватьданныеформы копироватьфайл краткоепредставлениеошибки лев макс местноевремя месяц мин минута монопольныйрежим найти найтинедопустимыесимволыxml найтиокнопонавигационнойссылке найтипомеченныенаудаление найтипоссылкам найтифайлы началогода началодня началоквартала началомесяца началоминуты началонедели началочаса начатьзапросразрешенияпользователя начатьзапускприложения начатькопированиефайла начатьперемещениефайла начатьподключениевнешнейкомпоненты начатьподключениерасширенияработыскриптографией начатьподключениерасширенияработысфайлами начатьпоискфайлов начатьполучениекаталогавременныхфайлов начатьполучениекаталогадокументов начатьполучениерабочегокаталогаданныхпользователя начатьполучениефайлов начатьпомещениефайла начатьпомещениефайлов начатьсозданиедвоичныхданныхизфайла начатьсозданиекаталога начатьтранзакцию начатьудалениефайлов начатьустановкувнешнейкомпоненты начатьустановкурасширенияработыскриптографией начатьустановкурасширенияработысфайлами неделягода необходимостьзавершениясоединения номерсеансаинформационнойбазы номерсоединенияинформационнойбазы нрег нстр обновитьинтерфейс обновитьнумерациюобъектов обновитьповторноиспользуемыезначения обработкапрерыванияпользователя объединитьфайлы окр описаниеошибки оповестить оповеститьобизменении отключитьобработчикзапросанастроекклиенталицензирования отключитьобработчикожидания отключитьобработчикоповещения открытьзначение открытьиндекссправки открытьсодержаниесправки открытьсправку открытьформу открытьформумодально отменитьтранзакцию очиститьжурналрегистрации очиститьнастройкипользователя очиститьсообщения параметрыдоступа перейтипонавигационнойссылке переместитьфайл подключитьвнешнююкомпоненту подключитьобработчикзапросанастроекклиенталицензирования подключитьобработчикожидания подключитьобработчикоповещения подключитьрасширениеработыскриптографией подключитьрасширениеработысфайлами подробноепредставлениеошибки показатьвводдаты показатьвводзначения показатьвводстроки показатьвводчисла показатьвопрос показатьзначение показатьинформациюобошибке показатьнакарте показатьоповещениепользователя показатьпредупреждение полноеимяпользователя получитьcomобъект получитьxmlтип получитьадреспоместоположению получитьблокировкусеансов получитьвремязавершенияспящегосеанса получитьвремязасыпанияпассивногосеанса получитьвремяожиданияблокировкиданных получитьданныевыбора получитьдополнительныйпараметрклиенталицензирования получитьдопустимыекодылокализации получитьдопустимыечасовыепояса получитьзаголовокклиентскогоприложения получитьзаголовоксистемы получитьзначенияотборажурналарегистрации получитьидентификаторконфигурации получитьизвременногохранилища получитьимявременногофайла получитьимяклиенталицензирования получитьинформациюэкрановклиента получитьиспользованиежурналарегистрации получитьиспользованиесобытияжурналарегистрации получитькраткийзаголовокприложения получитьмакетоформления получитьмаскувсефайлы получитьмаскувсефайлыклиента получитьмаскувсефайлысервера получитьместоположениепоадресу получитьминимальнуюдлинупаролейпользователей получитьнавигационнуюссылку получитьнавигационнуюссылкуинформационнойбазы получитьобновлениеконфигурациибазыданных получитьобновлениепредопределенныхданныхинформационнойбазы получитьобщиймакет получитьобщуюформу получитьокна получитьоперативнуюотметкувремени получитьотключениебезопасногорежима получитьпараметрыфункциональныхопцийинтерфейса получитьполноеимяпредопределенногозначения получитьпредставлениянавигационныхссылок получитьпроверкусложностипаролейпользователей получитьразделительпути получитьразделительпутиклиента получитьразделительпутисервера получитьсеансыинформационнойбазы получитьскоростьклиентскогосоединения получитьсоединенияинформационнойбазы получитьсообщенияпользователю получитьсоответствиеобъектаиформы получитьсоставстандартногоинтерфейсаodata получитьструктурухранениябазыданных получитьтекущийсеансинформационнойбазы получитьфайл получитьфайлы получитьформу получитьфункциональнуюопцию получитьфункциональнуюопциюинтерфейса получитьчасовойпоясинформационнойбазы пользователиос поместитьвовременноехранилище поместитьфайл поместитьфайлы прав праводоступа предопределенноезначение представлениекодалокализации представлениепериода представлениеправа представлениеприложения представлениесобытияжурналарегистрации представлениечасовогопояса предупреждение прекратитьработусистемы привилегированныйрежим продолжитьвызов прочитатьjson прочитатьxml прочитатьдатуjson пустаястрока рабочийкаталогданныхпользователя разблокироватьданныедляредактирования разделитьфайл разорватьсоединениесвнешнимисточникомданных раскодироватьстроку рольдоступна секунда сигнал символ скопироватьжурналрегистрации смещениелетнеговремени смещениестандартноговремени соединитьбуферыдвоичныхданных создатькаталог создатьфабрикуxdto сокрл сокрлп сокрп сообщить состояние сохранитьзначение сохранитьнастройкипользователя сред стрдлина стрзаканчиваетсяна стрзаменить стрнайти стрначинаетсяс строка строкасоединенияинформационнойбазы стрполучитьстроку стрразделить стрсоединить стрсравнить стрчисловхождений стрчислострок стршаблон текущаядата текущаядатасеанса текущаяуниверсальнаядата текущаяуниверсальнаядатавмиллисекундах текущийвариантинтерфейсаклиентскогоприложения текущийвариантосновногошрифтаклиентскогоприложения текущийкодлокализации текущийрежимзапуска текущийязык текущийязыксистемы тип типзнч транзакцияактивна трег удалитьданныеинформационнойбазы удалитьизвременногохранилища удалитьобъекты удалитьфайлы универсальноевремя установитьбезопасныйрежим установитьбезопасныйрежимразделенияданных установитьблокировкусеансов установитьвнешнююкомпоненту установитьвремязавершенияспящегосеанса установитьвремязасыпанияпассивногосеанса установитьвремяожиданияблокировкиданных установитьзаголовокклиентскогоприложения установитьзаголовоксистемы установитьиспользованиежурналарегистрации установитьиспользованиесобытияжурналарегистрации установитькраткийзаголовокприложения установитьминимальнуюдлинупаролейпользователей установитьмонопольныйрежим установитьнастройкиклиенталицензирования установитьобновлениепредопределенныхданныхинформационнойбазы установитьотключениебезопасногорежима установитьпараметрыфункциональныхопцийинтерфейса установитьпривилегированныйрежим установитьпроверкусложностипаролейпользователей установитьрасширениеработыскриптографией установитьрасширениеработысфайлами установитьсоединениесвнешнимисточникомданных установитьсоответствиеобъектаиформы установитьсоставстандартногоинтерфейсаodata установитьчасовойпоясинформационнойбазы установитьчасовойпояссеанса формат цел час часовойпояс часовойпояссеанса число числопрописью этоадресвременногохранилища wsссылки библиотекакартинок библиотекамакетовоформлениякомпоновкиданных библиотекастилей бизнеспроцессы внешниеисточникиданных внешниеобработки внешниеотчеты встроенныепокупки главныйинтерфейс главныйстиль документы доставляемыеуведомления журналыдокументов задачи информацияобинтернетсоединении использованиерабочейдаты историяработыпользователя константы критерииотбора метаданные обработки отображениерекламы отправкадоставляемыхуведомлений отчеты панельзадачос параметрзапуска параметрысеанса перечисления планывидоврасчета планывидовхарактеристик планыобмена планысчетов полнотекстовыйпоиск пользователиинформационнойбазы последовательности проверкавстроенныхпокупок рабочаядата расширенияконфигурации регистрыбухгалтерии регистрынакопления регистрырасчета регистрысведений регламентныезадания сериализаторxdto справочники средствагеопозиционирования средствакриптографии средствамультимедиа средстваотображениярекламы средствапочты средствателефонии фабрикаxdto файловыепотоки фоновыезадания хранилищанастроек хранилищевариантовотчетов хранилищенастроекданныхформ хранилищеобщихнастроек хранилищепользовательскихнастроекдинамическихсписков хранилищепользовательскихнастроекотчетов хранилищесистемныхнастроек ",class:"webцвета windowsцвета windowsшрифты библиотекакартинок рамкистиля символы цветастиля шрифтыстиля автоматическоесохранениеданныхформывнастройках автонумерациявформе автораздвижениесерий анимациядиаграммы вариантвыравниванияэлементовизаголовков вариантуправлениявысотойтаблицы вертикальнаяпрокруткаформы вертикальноеположение вертикальноеположениеэлемента видгруппыформы виддекорацииформы виддополненияэлементаформы видизмененияданных видкнопкиформы видпереключателя видподписейкдиаграмме видполяформы видфлажка влияниеразмеранапузырекдиаграммы горизонтальноеположение горизонтальноеположениеэлемента группировкаколонок группировкаподчиненныхэлементовформы группыиэлементы действиеперетаскивания дополнительныйрежимотображения допустимыедействияперетаскивания интервалмеждуэлементамиформы использованиевывода использованиеполосыпрокрутки используемоезначениеточкибиржевойдиаграммы историявыборапривводе источникзначенийоситочекдиаграммы источникзначенияразмерапузырькадиаграммы категориягруппыкоманд максимумсерий начальноеотображениедерева начальноеотображениесписка обновлениетекстаредактирования ориентациядендрограммы ориентациядиаграммы ориентацияметокдиаграммы ориентацияметоксводнойдиаграммы ориентацияэлементаформы отображениевдиаграмме отображениевлегендедиаграммы отображениегруппыкнопок отображениезаголовкашкалыдиаграммы отображениезначенийсводнойдиаграммы отображениезначенияизмерительнойдиаграммы отображениеинтерваладиаграммыганта отображениекнопки отображениекнопкивыбора отображениеобсужденийформы отображениеобычнойгруппы отображениеотрицательныхзначенийпузырьковойдиаграммы отображениепанелипоиска отображениеподсказки отображениепредупрежденияприредактировании отображениеразметкиполосырегулирования отображениестраницформы отображениетаблицы отображениетекстазначениядиаграммыганта отображениеуправленияобычнойгруппы отображениефигурыкнопки палитрацветовдиаграммы поведениеобычнойгруппы поддержкамасштабадендрограммы поддержкамасштабадиаграммыганта поддержкамасштабасводнойдиаграммы поисквтаблицепривводе положениезаголовкаэлементаформы положениекартинкикнопкиформы положениекартинкиэлементаграфическойсхемы положениекоманднойпанелиформы положениекоманднойпанелиэлементаформы положениеопорнойточкиотрисовки положениеподписейкдиаграмме положениеподписейшкалызначенийизмерительнойдиаграммы положениесостоянияпросмотра положениестрокипоиска положениетекстасоединительнойлинии положениеуправленияпоиском положениешкалывремени порядокотображенияточекгоризонтальнойгистограммы порядоксерийвлегендедиаграммы размеркартинки расположениезаголовкашкалыдиаграммы растягиваниеповертикалидиаграммыганта режимавтоотображениясостояния режимвводастроктаблицы режимвыборанезаполненного режимвыделениядаты режимвыделениястрокитаблицы режимвыделениятаблицы режимизмененияразмера режимизменениясвязанногозначения режимиспользованиядиалогапечати режимиспользованияпараметракоманды режиммасштабированияпросмотра режимосновногоокнаклиентскогоприложения режимоткрытияокнаформы режимотображениявыделения режимотображениягеографическойсхемы режимотображениязначенийсерии режимотрисовкисеткиграфическойсхемы режимполупрозрачностидиаграммы режимпробеловдиаграммы режимразмещениянастранице режимредактированияколонки режимсглаживаниядиаграммы режимсглаживанияиндикатора режимсписказадач сквозноевыравнивание сохранениеданныхформывнастройках способзаполнениятекстазаголовкашкалыдиаграммы способопределенияограничивающегозначениядиаграммы стандартнаягруппакоманд стандартноеоформление статусоповещенияпользователя стильстрелки типаппроксимациилиниитрендадиаграммы типдиаграммы типединицышкалывремени типимпортасерийслоягеографическойсхемы типлиниигеографическойсхемы типлиниидиаграммы типмаркерагеографическойсхемы типмаркерадиаграммы типобластиоформления типорганизацииисточникаданныхгеографическойсхемы типотображениясериислоягеографическойсхемы типотображенияточечногообъектагеографическойсхемы типотображенияшкалыэлементалегендыгеографическойсхемы типпоискаобъектовгеографическойсхемы типпроекциигеографическойсхемы типразмещенияизмерений типразмещенияреквизитовизмерений типрамкиэлементауправления типсводнойдиаграммы типсвязидиаграммыганта типсоединениязначенийпосериямдиаграммы типсоединенияточекдиаграммы типсоединительнойлинии типстороныэлементаграфическойсхемы типформыотчета типшкалырадарнойдиаграммы факторлиниитрендадиаграммы фигуракнопки фигурыграфическойсхемы фиксациявтаблице форматдняшкалывремени форматкартинки ширинаподчиненныхэлементовформы виддвижениябухгалтерии виддвижениянакопления видпериодарегистрарасчета видсчета видточкимаршрутабизнеспроцесса использованиеагрегатарегистранакопления использованиегруппиэлементов использованиережимапроведения использованиесреза периодичностьагрегатарегистранакопления режимавтовремя режимзаписидокумента режимпроведениядокумента авторегистрацияизменений допустимыйномерсообщения отправкаэлементаданных получениеэлементаданных использованиерасшифровкитабличногодокумента ориентациястраницы положениеитоговколоноксводнойтаблицы положениеитоговстроксводнойтаблицы положениетекстаотносительнокартинки расположениезаголовкагруппировкитабличногодокумента способчтениязначенийтабличногодокумента типдвустороннейпечати типзаполненияобластитабличногодокумента типкурсоровтабличногодокумента типлиниирисункатабличногодокумента типлинииячейкитабличногодокумента типнаправленияпереходатабличногодокумента типотображениявыделениятабличногодокумента типотображениялинийсводнойтаблицы типразмещениятекстатабличногодокумента типрисункатабличногодокумента типсмещениятабличногодокумента типузоратабличногодокумента типфайлатабличногодокумента точностьпечати чередованиерасположениястраниц отображениевремениэлементовпланировщика типфайлаформатированногодокумента обходрезультатазапроса типзаписизапроса видзаполнениярасшифровкипостроителяотчета типдобавленияпредставлений типизмеренияпостроителяотчета типразмещенияитогов доступкфайлу режимдиалогавыборафайла режимоткрытияфайла типизмеренияпостроителязапроса видданныханализа методкластеризации типединицыинтервалавременианализаданных типзаполнениятаблицырезультатаанализаданных типиспользованиячисловыхзначенийанализаданных типисточникаданныхпоискаассоциаций типколонкианализаданныхдереворешений типколонкианализаданныхкластеризация типколонкианализаданныхобщаястатистика типколонкианализаданныхпоискассоциаций типколонкианализаданныхпоискпоследовательностей типколонкимоделипрогноза типмерырасстоянияанализаданных типотсеченияправилассоциации типполяанализаданных типстандартизациианализаданных типупорядочиванияправилассоциациианализаданных типупорядочиванияшаблоновпоследовательностейанализаданных типупрощениядереварешений wsнаправлениепараметра вариантxpathxs вариантзаписидатыjson вариантпростоготипаxs видгруппымоделиxs видфасетаxdto действиепостроителяdom завершенностьпростоготипаxs завершенностьсоставноготипаxs завершенностьсхемыxs запрещенныеподстановкиxs исключениягруппподстановкиxs категорияиспользованияатрибутаxs категорияограниченияидентичностиxs категорияограниченияпространствименxs методнаследованияxs модельсодержимогоxs назначениетипаxml недопустимыеподстановкиxs обработкапробельныхсимволовxs обработкасодержимогоxs ограничениезначенияxs параметрыотбораузловdom переносстрокjson позициявдокументеdom пробельныесимволыxml типатрибутаxml типзначенияjson типканоническогоxml типкомпонентыxs типпроверкиxml типрезультатаdomxpath типузлаdom типузлаxml формаxml формапредставленияxs форматдатыjson экранированиесимволовjson видсравнениякомпоновкиданных действиеобработкирасшифровкикомпоновкиданных направлениесортировкикомпоновкиданных расположениевложенныхэлементоврезультатакомпоновкиданных расположениеитоговкомпоновкиданных расположениегруппировкикомпоновкиданных расположениеполейгруппировкикомпоновкиданных расположениеполякомпоновкиданных расположениереквизитовкомпоновкиданных расположениересурсовкомпоновкиданных типбухгалтерскогоостаткакомпоновкиданных типвыводатекстакомпоновкиданных типгруппировкикомпоновкиданных типгруппыэлементовотборакомпоновкиданных типдополненияпериодакомпоновкиданных типзаголовкаполейкомпоновкиданных типмакетагруппировкикомпоновкиданных типмакетаобластикомпоновкиданных типостаткакомпоновкиданных типпериодакомпоновкиданных типразмещениятекстакомпоновкиданных типсвязинаборовданныхкомпоновкиданных типэлементарезультатакомпоновкиданных расположениелегендыдиаграммыкомпоновкиданных типпримененияотборакомпоновкиданных режимотображенияэлементанастройкикомпоновкиданных режимотображениянастроеккомпоновкиданных состояниеэлементанастройкикомпоновкиданных способвосстановлениянастроеккомпоновкиданных режимкомпоновкирезультата использованиепараметракомпоновкиданных автопозицияресурсовкомпоновкиданных вариантиспользованиягруппировкикомпоновкиданных расположениересурсоввдиаграммекомпоновкиданных фиксациякомпоновкиданных использованиеусловногооформлениякомпоновкиданных важностьинтернетпочтовогосообщения обработкатекстаинтернетпочтовогосообщения способкодированияинтернетпочтовоговложения способкодированиянеasciiсимволовинтернетпочтовогосообщения типтекстапочтовогосообщения протоколинтернетпочты статусразборапочтовогосообщения режимтранзакциизаписижурналарегистрации статустранзакциизаписижурналарегистрации уровеньжурналарегистрации расположениехранилищасертификатовкриптографии режимвключениясертификатовкриптографии режимпроверкисертификатакриптографии типхранилищасертификатовкриптографии кодировкаименфайловвzipфайле методсжатияzip методшифрованияzip режимвосстановленияпутейфайловzip режимобработкиподкаталоговzip режимсохраненияпутейzip уровеньсжатияzip звуковоеоповещение направлениепереходакстроке позициявпотоке порядокбайтов режимблокировкиданных режимуправленияблокировкойданных сервисвстроенныхпокупок состояниефоновогозадания типподписчикадоставляемыхуведомлений уровеньиспользованиязащищенногосоединенияftp направлениепорядкасхемызапроса типдополненияпериодамисхемызапроса типконтрольнойточкисхемызапроса типобъединениясхемызапроса типпараметрадоступнойтаблицысхемызапроса типсоединениясхемызапроса httpметод автоиспользованиеобщегореквизита автопрефиксномеразадачи вариантвстроенногоязыка видиерархии видрегистранакопления видтаблицывнешнегоисточникаданных записьдвиженийприпроведении заполнениепоследовательностей индексирование использованиебазыпланавидоврасчета использованиебыстроговыбора использованиеобщегореквизита использованиеподчинения использованиеполнотекстовогопоиска использованиеразделяемыхданныхобщегореквизита использованиереквизита назначениеиспользованияприложения назначениерасширенияконфигурации направлениепередачи обновлениепредопределенныхданных оперативноепроведение основноепредставлениевидарасчета основноепредставлениевидахарактеристики основноепредставлениезадачи основноепредставлениепланаобмена основноепредставлениесправочника основноепредставлениесчета перемещениеграницыприпроведении периодичностьномерабизнеспроцесса периодичностьномерадокумента периодичностьрегистрарасчета периодичностьрегистрасведений повторноеиспользованиевозвращаемыхзначений полнотекстовыйпоискпривводепостроке принадлежностьобъекта проведение разделениеаутентификацииобщегореквизита разделениеданныхобщегореквизита разделениерасширенийконфигурацииобщегореквизита режимавтонумерацииобъектов режимзаписирегистра режимиспользованиямодальности режимиспользованиясинхронныхвызововрасширенийплатформыивнешнихкомпонент режимповторногоиспользованиясеансов режимполученияданныхвыборапривводепостроке режимсовместимости режимсовместимостиинтерфейса режимуправленияблокировкойданныхпоумолчанию сериикодовпланавидовхарактеристик сериикодовпланасчетов сериикодовсправочника созданиепривводе способвыбора способпоискастрокипривводепостроке способредактирования типданныхтаблицывнешнегоисточникаданных типкодапланавидоврасчета типкодасправочника типмакета типномерабизнеспроцесса типномерадокумента типномеразадачи типформы удалениедвижений важностьпроблемыприменениярасширенияконфигурации вариантинтерфейсаклиентскогоприложения вариантмасштабаформклиентскогоприложения вариантосновногошрифтаклиентскогоприложения вариантстандартногопериода вариантстандартнойдатыначала видграницы видкартинки видотображенияполнотекстовогопоиска видрамки видсравнения видцвета видчисловогозначения видшрифта допустимаядлина допустимыйзнак использованиеbyteordermark использованиеметаданныхполнотекстовогопоиска источникрасширенийконфигурации клавиша кодвозвратадиалога кодировкаxbase кодировкатекста направлениепоиска направлениесортировки обновлениепредопределенныхданных обновлениеприизмененииданных отображениепанелиразделов проверказаполнения режимдиалогавопрос режимзапускаклиентскогоприложения режимокругления режимоткрытияформприложения режимполнотекстовогопоиска скоростьклиентскогосоединения состояниевнешнегоисточникаданных состояниеобновленияконфигурациибазыданных способвыборасертификатаwindows способкодированиястроки статуссообщения типвнешнейкомпоненты типплатформы типповеденияклавишиenter типэлементаинформацииовыполненииобновленияконфигурациибазыданных уровеньизоляциитранзакций хешфункция частидаты",type:"comобъект ftpсоединение httpзапрос httpсервисответ httpсоединение wsопределения wsпрокси xbase анализданных аннотацияxs блокировкаданных буфердвоичныхданных включениеxs выражениекомпоновкиданных генераторслучайныхчисел географическаясхема географическиекоординаты графическаясхема группамоделиxs данныерасшифровкикомпоновкиданных двоичныеданные дендрограмма диаграмма диаграммаганта диалогвыборафайла диалогвыборацвета диалогвыборашрифта диалограсписаниярегламентногозадания диалогредактированиястандартногопериода диапазон документdom документhtml документацияxs доставляемоеуведомление записьdom записьfastinfoset записьhtml записьjson записьxml записьzipфайла записьданных записьтекста записьузловdom запрос защищенноесоединениеopenssl значенияполейрасшифровкикомпоновкиданных извлечениетекста импортxs интернетпочта интернетпочтовоесообщение интернетпочтовыйпрофиль интернетпрокси интернетсоединение информациядляприложенияxs использованиеатрибутаxs использованиесобытияжурналарегистрации источникдоступныхнастроеккомпоновкиданных итераторузловdom картинка квалификаторыдаты квалификаторыдвоичныхданных квалификаторыстроки квалификаторычисла компоновщикмакетакомпоновкиданных компоновщикнастроеккомпоновкиданных конструктормакетаоформлениякомпоновкиданных конструкторнастроеккомпоновкиданных конструкторформатнойстроки линия макеткомпоновкиданных макетобластикомпоновкиданных макетоформлениякомпоновкиданных маскаxs менеджеркриптографии наборсхемxml настройкикомпоновкиданных настройкисериализацииjson обработкакартинок обработкарасшифровкикомпоновкиданных обходдереваdom объявлениеатрибутаxs объявлениенотацииxs объявлениеэлементаxs описаниеиспользованиясобытиядоступжурналарегистрации описаниеиспользованиясобытияотказвдоступежурналарегистрации описаниеобработкирасшифровкикомпоновкиданных описаниепередаваемогофайла описаниетипов определениегруппыатрибутовxs определениегруппымоделиxs определениеограниченияидентичностиxs определениепростоготипаxs определениесоставноготипаxs определениетипадокументаdom определенияxpathxs отборкомпоновкиданных пакетотображаемыхдокументов параметрвыбора параметркомпоновкиданных параметрызаписиjson параметрызаписиxml параметрычтенияxml переопределениеxs планировщик полеанализаданных полекомпоновкиданных построительdom построительзапроса построительотчета построительотчетаанализаданных построительсхемxml поток потоквпамяти почта почтовоесообщение преобразованиеxsl преобразованиекканоническомуxml процессорвыводарезультатакомпоновкиданныхвколлекциюзначений процессорвыводарезультатакомпоновкиданныхвтабличныйдокумент процессоркомпоновкиданных разыменовательпространствименdom рамка расписаниерегламентногозадания расширенноеимяxml результатчтенияданных своднаядиаграмма связьпараметравыбора связьпотипу связьпотипукомпоновкиданных сериализаторxdto сертификатклиентаwindows сертификатклиентафайл сертификаткриптографии сертификатыудостоверяющихцентровwindows сертификатыудостоверяющихцентровфайл сжатиеданных системнаяинформация сообщениепользователю сочетаниеклавиш сравнениезначений стандартнаядатаначала стандартныйпериод схемаxml схемакомпоновкиданных табличныйдокумент текстовыйдокумент тестируемоеприложение типданныхxml уникальныйидентификатор фабрикаxdto файл файловыйпоток фасетдлиныxs фасетколичестваразрядовдробнойчастиxs фасетмаксимальноговключающегозначенияxs фасетмаксимальногоисключающегозначенияxs фасетмаксимальнойдлиныxs фасетминимальноговключающегозначенияxs фасетминимальногоисключающегозначенияxs фасетминимальнойдлиныxs фасетобразцаxs фасетобщегоколичестваразрядовxs фасетперечисленияxs фасетпробельныхсимволовxs фильтрузловdom форматированнаястрока форматированныйдокумент фрагментxs хешированиеданных хранилищезначения цвет чтениеfastinfoset чтениеhtml чтениеjson чтениеxml чтениеzipфайла чтениеданных чтениетекста чтениеузловdom шрифт элементрезультатакомпоновкиданных comsafearray деревозначений массив соответствие списокзначений структура таблицазначений фиксированнаяструктура фиксированноесоответствие фиксированныймассив ",literal:n},contains:[{className:"meta",begin:"#|&",end:"$",keywords:{$pattern:t,keyword:r+"загрузитьизфайла вебклиент вместо внешнеесоединение клиент конецобласти мобильноеприложениеклиент мобильноеприложениесервер наклиенте наклиентенасервере наклиентенасерверебезконтекста насервере насерверебезконтекста область перед после сервер толстыйклиентобычноеприложение толстыйклиентуправляемоеприложение тонкийклиент "},contains:[s]},{className:"function",variants:[{begin:"процедура|функция",end:"\\)",keywords:"процедура функция"},{begin:"конецпроцедуры|конецфункции",keywords:"конецпроцедуры конецфункции"}],contains:[{begin:"\\(",end:"\\)",endsParent:!0,contains:[{className:"params",begin:t,end:",",excludeEnd:!0,endsWithParent:!0,keywords:{$pattern:t,keyword:"знач",literal:n},contains:[a,i,o]},s]},e.inherit(e.TITLE_MODE,{begin:t})]},s,{className:"symbol",begin:"~",end:";|:",excludeEnd:!0},a,i,o,{match:/[;()+\-:=,]/,className:"punctuation",relevance:0}]}}),Md)),zf.registerLanguage("abnf",(Pd||(Pd=1,Ld=function(e){const t=e.regex,r=e.COMMENT(/;/,/$/);return{name:"Augmented Backus-Naur Form",illegal:/[!@#$^&',?+~`|:]/,keywords:["ALPHA","BIT","CHAR","CR","CRLF","CTL","DIGIT","DQUOTE","HEXDIG","HTAB","LF","LWSP","OCTET","SP","VCHAR","WSP"],contains:[{scope:"operator",match:/=\/?/},{scope:"attribute",match:t.concat(/^[a-zA-Z][a-zA-Z0-9-]*/,/(?=\s*=)/)},r,{scope:"symbol",match:/%b[0-1]+(-[0-1]+|(\.[0-1]+)+)?/},{scope:"symbol",match:/%d[0-9]+(-[0-9]+|(\.[0-9]+)+)?/},{scope:"symbol",match:/%x[0-9A-F]+(-[0-9A-F]+|(\.[0-9A-F]+)+)?/},{scope:"symbol",match:/%[si](?=".*")/},e.QUOTE_STRING_MODE,e.NUMBER_MODE]}}),Ld)),zf.registerLanguage("accesslog",(Bd||(Bd=1,Fd=function(e){const t=e.regex,r=["GET","POST","HEAD","PUT","DELETE","CONNECT","OPTIONS","PATCH","TRACE"];return{name:"Apache Access Log",contains:[{className:"number",begin:/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?\b/,relevance:5},{className:"number",begin:/\b\d+\b/,relevance:0},{className:"string",begin:t.concat(/"/,t.either(...r)),end:/"/,keywords:r,illegal:/\n/,relevance:5,contains:[{begin:/HTTP\/[12]\.\d'/,relevance:5}]},{className:"string",begin:/\[\d[^\]\n]{8,}\]/,illegal:/\n/,relevance:1},{className:"string",begin:/\[/,end:/\]/,illegal:/\n/,relevance:0},{className:"string",begin:/"Mozilla\/\d\.\d \(/,end:/"/,illegal:/\n/,relevance:3},{className:"string",begin:/"/,end:/"/,illegal:/\n/,relevance:0}]}}),Fd)),zf.registerLanguage("actionscript",(Gd||(Gd=1,Ud=function(e){const t=e.regex,r=/[a-zA-Z_$][a-zA-Z0-9_$]*/,n=t.concat(r,t.concat("(\\.",r,")*")),a={className:"rest_arg",begin:/[.]{3}/,end:r,relevance:10};return{name:"ActionScript",aliases:["as"],keywords:{keyword:["as","break","case","catch","class","const","continue","default","delete","do","dynamic","each","else","extends","final","finally","for","function","get","if","implements","import","in","include","instanceof","interface","internal","is","namespace","native","new","override","package","private","protected","public","return","set","static","super","switch","this","throw","try","typeof","use","var","void","while","with"],literal:["true","false","null","undefined"]},contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.C_NUMBER_MODE,{match:[/\bpackage/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{match:[/\b(?:class|interface|extends|implements)/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{className:"meta",beginKeywords:"import include",end:/;/,keywords:{keyword:"import include"}},{beginKeywords:"function",end:/[{;]/,excludeEnd:!0,illegal:/\S/,contains:[e.inherit(e.TITLE_MODE,{className:"title.function"}),{className:"params",begin:/\(/,end:/\)/,contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,a]},{begin:t.concat(/:\s*/,/([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)/)}]},e.METHOD_GUARD],illegal:/#/}}),Ud)),zf.registerLanguage("ada",(Yd||(Yd=1,zd=function(e){const t="\\d(_|\\d)*",r="[eE][-+]?"+t,n="\\b("+t+"#\\w+(\\.\\w+)?#("+r+")?|"+t+"(\\."+t+")?("+r+")?)",a="[A-Za-z](_?[A-Za-z0-9.])*",i="[]\\{\\}%#'\"",o=e.COMMENT("--","$"),s={begin:"\\s+:\\s+",end:"\\s*(:=|;|\\)|=>|$)",illegal:i,contains:[{beginKeywords:"loop for declare others",endsParent:!0},{className:"keyword",beginKeywords:"not null constant access function procedure in out aliased exception"},{className:"type",begin:a,endsParent:!0,relevance:0}]};return{name:"Ada",case_insensitive:!0,keywords:{keyword:["abort","else","new","return","abs","elsif","not","reverse","abstract","end","accept","entry","select","access","exception","of","separate","aliased","exit","or","some","all","others","subtype","and","for","out","synchronized","array","function","overriding","at","tagged","generic","package","task","begin","goto","pragma","terminate","body","private","then","if","procedure","type","case","in","protected","constant","interface","is","raise","use","declare","range","delay","limited","record","when","delta","loop","rem","while","digits","renames","with","do","mod","requeue","xor"],literal:["True","False"]},contains:[o,{className:"string",begin:/"/,end:/"/,contains:[{begin:/""/,relevance:0}]},{className:"string",begin:/'.'/},{className:"number",begin:n,relevance:0},{className:"symbol",begin:"'"+a},{className:"title",begin:"(\\bwith\\s+)?(\\bprivate\\s+)?\\bpackage\\s+(\\bbody\\s+)?",end:"(is|$)",keywords:"package body",excludeBegin:!0,excludeEnd:!0,illegal:i},{begin:"(\\b(with|overriding)\\s+)?\\b(function|procedure)\\s+",end:"(\\bis|\\bwith|\\brenames|\\)\\s*;)",keywords:"overriding function procedure with is renames return",returnBegin:!0,contains:[o,{className:"title",begin:"(\\bwith\\s+)?\\b(function|procedure)\\s+",end:"(\\(|\\s+|$)",excludeBegin:!0,excludeEnd:!0,illegal:i},s,{className:"type",begin:"\\breturn\\s+",end:"(\\s+|;|$)",keywords:"return",excludeBegin:!0,excludeEnd:!0,endsParent:!0,illegal:i}]},{className:"type",begin:"\\b(sub)?type\\s+",end:"\\s+",keywords:"type",excludeBegin:!0,illegal:i},s]}}),zd)),zf.registerLanguage("angelscript",(Hd||(Hd=1,qd=function(e){const t={className:"built_in",begin:"\\b(void|bool|int8|int16|int32|int64|int|uint8|uint16|uint32|uint64|uint|string|ref|array|double|float|auto|dictionary)"},r={className:"symbol",begin:"[a-zA-Z0-9_]+@"},n={className:"keyword",begin:"<",end:">",contains:[t,r]};return t.contains=[n],r.contains=[n],{name:"AngelScript",aliases:["asc"],keywords:["for","in|0","break","continue","while","do|0","return","if","else","case","switch","namespace","is","cast","or","and","xor","not","get|0","in","inout|10","out","override","set|0","private","public","const","default|0","final","shared","external","mixin|10","enum","typedef","funcdef","this","super","import","from","interface","abstract|0","try","catch","protected","explicit","property"],illegal:"(^using\\s+[A-Za-z0-9_\\.]+;$|\\bfunction\\s*[^\\(])",contains:[{className:"string",begin:"'",end:"'",illegal:"\\n",contains:[e.BACKSLASH_ESCAPE],relevance:0},{className:"string",begin:'"""',end:'"""'},{className:"string",begin:'"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE],relevance:0},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"string",begin:"^\\s*\\[",end:"\\]"},{beginKeywords:"interface namespace",end:/\{/,illegal:"[;.\\-]",contains:[{className:"symbol",begin:"[a-zA-Z0-9_]+"}]},{beginKeywords:"class",end:/\{/,illegal:"[;.\\-]",contains:[{className:"symbol",begin:"[a-zA-Z0-9_]+",contains:[{begin:"[:,]\\s*",contains:[{className:"symbol",begin:"[a-zA-Z0-9_]+"}]}]}]},t,r,{className:"literal",begin:"\\b(null|true|false)"},{className:"number",relevance:0,begin:"(-?)(\\b0[xXbBoOdD][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?f?|\\.\\d+f?)([eE][-+]?\\d+f?)?)"}]}}),qd)),zf.registerLanguage("apache",($d||($d=1,Vd=function(e){const t={className:"number",begin:/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?/};return{name:"Apache config",aliases:["apacheconf"],case_insensitive:!0,contains:[e.HASH_COMMENT_MODE,{className:"section",begin:/<\/?/,end:/>/,contains:[t,{className:"number",begin:/:\d{1,5}/},e.inherit(e.QUOTE_STRING_MODE,{relevance:0})]},{className:"attribute",begin:/\w+/,relevance:0,keywords:{_:["order","deny","allow","setenv","rewriterule","rewriteengine","rewritecond","documentroot","sethandler","errordocument","loadmodule","options","header","listen","serverroot","servername"]},starts:{end:/$/,relevance:0,keywords:{literal:"on off all deny allow"},contains:[{scope:"punctuation",match:/\\\n/},{className:"meta",begin:/\s\[/,end:/\]$/},{className:"variable",begin:/[\$%]\{/,end:/\}/,contains:["self",{className:"number",begin:/[$%]\d+/}]},t,{className:"number",begin:/\b\d+/},e.QUOTE_STRING_MODE]}}],illegal:/\S/}}),Vd)),zf.registerLanguage("applescript",(jd||(jd=1,Wd=function(e){const t=e.regex,r=e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),n={className:"params",begin:/\(/,end:/\)/,contains:["self",e.C_NUMBER_MODE,r]},a=e.COMMENT(/--/,/$/),i=[a,e.COMMENT(/\(\*/,/\*\)/,{contains:["self",a]}),e.HASH_COMMENT_MODE];return{name:"AppleScript",aliases:["osascript"],keywords:{keyword:"about above after against and around as at back before beginning behind below beneath beside between but by considering contain contains continue copy div does eighth else end equal equals error every exit fifth first for fourth from front get given global if ignoring in into is it its last local me middle mod my ninth not of on onto or over prop property put ref reference repeat returning script second set seventh since sixth some tell tenth that the|0 then third through thru timeout times to transaction try until where while whose with without",literal:"AppleScript false linefeed return pi quote result space tab true",built_in:"alias application boolean class constant date file integer list number real record string text activate beep count delay launch log offset read round run say summarize write character characters contents day frontmost id item length month name|0 paragraph paragraphs rest reverse running time version weekday word words year"},contains:[r,e.C_NUMBER_MODE,{className:"built_in",begin:t.concat(/\b/,t.either(/clipboard info/,/the clipboard/,/info for/,/list (disks|folder)/,/mount volume/,/path to/,/(close|open for) access/,/(get|set) eof/,/current date/,/do shell script/,/get volume settings/,/random number/,/set volume/,/system attribute/,/system info/,/time to GMT/,/(load|run|store) script/,/scripting components/,/ASCII (character|number)/,/localized string/,/choose (application|color|file|file name|folder|from list|remote application|URL)/,/display (alert|dialog)/),/\b/)},{className:"built_in",begin:/^\s*return\b/},{className:"literal",begin:/\b(text item delimiters|current application|missing value)\b/},{className:"keyword",begin:t.concat(/\b/,t.either(/apart from/,/aside from/,/instead of/,/out of/,/greater than/,/isn't|(doesn't|does not) (equal|come before|come after|contain)/,/(greater|less) than( or equal)?/,/(starts?|ends|begins?) with/,/contained by/,/comes (before|after)/,/a (ref|reference)/,/POSIX (file|path)/,/(date|time) string/,/quoted form/),/\b/)},{beginKeywords:"on",illegal:/[${=;\n]/,contains:[e.UNDERSCORE_TITLE_MODE,n]},...i],illegal:/\/\/|->|=>|\[\[/}}),Wd)),zf.registerLanguage("arcade",(Kd||(Kd=1,Qd=function(e){const t="[A-Za-z_][0-9A-Za-z_]*",r={keyword:["break","case","catch","continue","debugger","do","else","export","for","function","if","import","in","new","of","return","switch","try","var","void","while"],literal:["BackSlash","DoubleQuote","ForwardSlash","Infinity","NaN","NewLine","PI","SingleQuote","Tab","TextFormatting","false","null","true","undefined"],built_in:["Abs","Acos","All","Angle","Any","Area","AreaGeodetic","Array","Asin","Atan","Atan2","Attachments","Average","Back","Bearing","Boolean","Buffer","BufferGeodetic","Ceil","Centroid","ChangeTimeZone","Clip","Concatenate","Console","Constrain","Contains","ConvertDirection","ConvexHull","Cos","Count","Crosses","Cut","Date|0","DateAdd","DateDiff","DateOnly","Day","Decode","DefaultValue","Densify","DensifyGeodetic","Dictionary","Difference","Disjoint","Distance","DistanceGeodetic","DistanceToCoordinate","Distinct","Domain","DomainCode","DomainName","EnvelopeIntersects","Equals","Erase","Exp","Expects","Extent","Feature","FeatureInFilter","FeatureSet","FeatureSetByAssociation","FeatureSetById","FeatureSetByName","FeatureSetByPortalItem","FeatureSetByRelationshipClass","FeatureSetByRelationshipName","Filter","FilterBySubtypeCode","Find","First|0","Floor","FromCharCode","FromCodePoint","FromJSON","Front","GdbVersion","Generalize","Geometry","GetEnvironment","GetFeatureSet","GetFeatureSetInfo","GetUser","GroupBy","Guid","HasKey","HasValue","Hash","Hour","IIf","ISOMonth","ISOWeek","ISOWeekday","ISOYear","Includes","IndexOf","Insert","Intersection","Intersects","IsEmpty","IsNan","IsSelfIntersecting","IsSimple","KnowledgeGraphByPortalItem","Left|0","Length","Length3D","LengthGeodetic","Log","Lower","Map","Max","Mean","MeasureToCoordinate","Mid","Millisecond","Min","Minute","Month","MultiPartToSinglePart","Multipoint","NearestCoordinate","NearestVertex","NextSequenceValue","None","Now","Number","Offset","OrderBy","Overlaps","Point","PointToCoordinate","Polygon","Polyline","Pop","Portal","Pow","Proper","Push","QueryGraph","Random","Reduce","Relate","Replace","Resize","Reverse","Right|0","RingIsClockwise","Rotate","Round","Schema","Second","SetGeometry","Simplify","Sin","Slice","Sort","Splice","Split","Sqrt","StandardizeFilename","StandardizeGuid","Stdev","SubtypeCode","SubtypeName","Subtypes","Sum","SymmetricDifference","Tan","Text","Time","TimeZone","TimeZoneOffset","Timestamp","ToCharCode","ToCodePoint","ToHex","ToLocal","ToUTC","Today","Top|0","Touches","TrackAccelerationAt","TrackAccelerationWindow","TrackCurrentAcceleration","TrackCurrentDistance","TrackCurrentSpeed","TrackCurrentTime","TrackDistanceAt","TrackDistanceWindow","TrackDuration","TrackFieldWindow","TrackGeometryWindow","TrackIndex","TrackSpeedAt","TrackSpeedWindow","TrackStartTime","TrackWindow","Trim","TypeOf","Union","Upper","UrlEncode","Variance","Week","Weekday","When|0","Within","Year|0"]},n={className:"symbol",begin:"\\$"+e.regex.either("aggregatedFeatures","analytic","config","datapoint","datastore","editcontext","feature","featureSet","feedfeature","fencefeature","fencenotificationtype","graph","join","layer","locationupdate","map","measure","measure","originalFeature","record","reference","rowindex","sourcedatastore","sourcefeature","sourcelayer","target","targetdatastore","targetfeature","targetlayer","userInput","value","variables","view")},a={className:"number",variants:[{begin:"\\b(0[bB][01]+)"},{begin:"\\b(0[oO][0-7]+)"},{begin:e.C_NUMBER_RE}],relevance:0},i={className:"subst",begin:"\\$\\{",end:"\\}",keywords:r,contains:[]},o={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,i]};i.contains=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,o,a,e.REGEXP_MODE];const s=i.contains.concat([e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]);return{name:"ArcGIS Arcade",case_insensitive:!0,keywords:r,contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,o,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,n,a,{begin:/[{,]\s*/,relevance:0,contains:[{begin:t+"\\s*:",returnBegin:!0,relevance:0,contains:[{className:"attr",begin:t,relevance:0}]}]},{begin:"("+e.RE_STARTERS_RE+"|\\b(return)\\b)\\s*",keywords:"return",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.REGEXP_MODE,{className:"function",begin:"(\\(.*?\\)|"+t+")\\s*=>",returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:t},{begin:/\(\s*\)/},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:r,contains:s}]}]}],relevance:0},{beginKeywords:"function",end:/\{/,excludeEnd:!0,contains:[e.inherit(e.TITLE_MODE,{className:"title.function",begin:t}),{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,contains:s}],illegal:/\[|%/},{begin:/\$[(.]/}],illegal:/#(?!!)/}}),Qd)),zf.registerLanguage("arduino",(Zd||(Zd=1,Xd=function(e){const t={type:["boolean","byte","word","String"],built_in:["KeyboardController","MouseController","SoftwareSerial","EthernetServer","EthernetClient","LiquidCrystal","RobotControl","GSMVoiceCall","EthernetUDP","EsploraTFT","HttpClient","RobotMotor","WiFiClient","GSMScanner","FileSystem","Scheduler","GSMServer","YunClient","YunServer","IPAddress","GSMClient","GSMModem","Keyboard","Ethernet","Console","GSMBand","Esplora","Stepper","Process","WiFiUDP","GSM_SMS","Mailbox","USBHost","Firmata","PImage","Client","Server","GSMPIN","FileIO","Bridge","Serial","EEPROM","Stream","Mouse","Audio","Servo","File","Task","GPRS","WiFi","Wire","TFT","GSM","SPI","SD"],_hints:["setup","loop","runShellCommandAsynchronously","analogWriteResolution","retrieveCallingNumber","printFirmwareVersion","analogReadResolution","sendDigitalPortPair","noListenOnLocalhost","readJoystickButton","setFirmwareVersion","readJoystickSwitch","scrollDisplayRight","getVoiceCallStatus","scrollDisplayLeft","writeMicroseconds","delayMicroseconds","beginTransmission","getSignalStrength","runAsynchronously","getAsynchronously","listenOnLocalhost","getCurrentCarrier","readAccelerometer","messageAvailable","sendDigitalPorts","lineFollowConfig","countryNameWrite","runShellCommand","readStringUntil","rewindDirectory","readTemperature","setClockDivider","readLightSensor","endTransmission","analogReference","detachInterrupt","countryNameRead","attachInterrupt","encryptionType","readBytesUntil","robotNameWrite","readMicrophone","robotNameRead","cityNameWrite","userNameWrite","readJoystickY","readJoystickX","mouseReleased","openNextFile","scanNetworks","noInterrupts","digitalWrite","beginSpeaker","mousePressed","isActionDone","mouseDragged","displayLogos","noAutoscroll","addParameter","remoteNumber","getModifiers","keyboardRead","userNameRead","waitContinue","processInput","parseCommand","printVersion","readNetworks","writeMessage","blinkVersion","cityNameRead","readMessage","setDataMode","parsePacket","isListening","setBitOrder","beginPacket","isDirectory","motorsWrite","drawCompass","digitalRead","clearScreen","serialEvent","rightToLeft","setTextSize","leftToRight","requestFrom","keyReleased","compassRead","analogWrite","interrupts","WiFiServer","disconnect","playMelody","parseFloat","autoscroll","getPINUsed","setPINUsed","setTimeout","sendAnalog","readSlider","analogRead","beginWrite","createChar","motorsStop","keyPressed","tempoWrite","readButton","subnetMask","debugPrint","macAddress","writeGreen","randomSeed","attachGPRS","readString","sendString","remotePort","releaseAll","mouseMoved","background","getXChange","getYChange","answerCall","getResult","voiceCall","endPacket","constrain","getSocket","writeJSON","getButton","available","connected","findUntil","readBytes","exitValue","readGreen","writeBlue","startLoop","IPAddress","isPressed","sendSysex","pauseMode","gatewayIP","setCursor","getOemKey","tuneWrite","noDisplay","loadImage","switchPIN","onRequest","onReceive","changePIN","playFile","noBuffer","parseInt","overflow","checkPIN","knobRead","beginTFT","bitClear","updateIR","bitWrite","position","writeRGB","highByte","writeRed","setSpeed","readBlue","noStroke","remoteIP","transfer","shutdown","hangCall","beginSMS","endWrite","attached","maintain","noCursor","checkReg","checkPUK","shiftOut","isValid","shiftIn","pulseIn","connect","println","localIP","pinMode","getIMEI","display","noBlink","process","getBand","running","beginSD","drawBMP","lowByte","setBand","release","bitRead","prepare","pointTo","readRed","setMode","noFill","remove","listen","stroke","detach","attach","noTone","exists","buffer","height","bitSet","circle","config","cursor","random","IRread","setDNS","endSMS","getKey","micros","millis","begin","print","write","ready","flush","width","isPIN","blink","clear","press","mkdir","rmdir","close","point","yield","image","BSSID","click","delay","read","text","move","peek","beep","rect","line","open","seek","fill","size","turn","stop","home","find","step","tone","sqrt","RSSI","SSID","end","bit","tan","cos","sin","pow","map","abs","max","min","get","run","put"],literal:["DIGITAL_MESSAGE","FIRMATA_STRING","ANALOG_MESSAGE","REPORT_DIGITAL","REPORT_ANALOG","INPUT_PULLUP","SET_PIN_MODE","INTERNAL2V56","SYSTEM_RESET","LED_BUILTIN","INTERNAL1V1","SYSEX_START","INTERNAL","EXTERNAL","DEFAULT","OUTPUT","INPUT","HIGH","LOW"]},r=function(e){const t=e.regex,r=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),n="decltype\\(auto\\)",a="[a-zA-Z_]\\w*::",i="(?!struct)("+n+"|"+t.optional(a)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",o={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},s={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},c={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(s,{className:"string"}),{className:"string",begin:/<.*?>/},r,e.C_BLOCK_COMMENT_MODE]},d={className:"title",begin:t.optional(a)+e.IDENT_RE,relevance:0},u=t.optional(a)+e.IDENT_RE+"\\s*\\(",p={type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],keyword:["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"]},_={className:"function.dispatch",relevance:0,keywords:{_hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"]},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},m=[_,c,o,r,e.C_BLOCK_COMMENT_MODE,l,s],g={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:p,contains:m.concat([{begin:/\(/,end:/\)/,keywords:p,contains:m.concat(["self"]),relevance:0}]),relevance:0},h={className:"function",begin:"("+i+"[\\*&\\s]+)+"+u,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:p,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:n,keywords:p,relevance:0},{begin:u,returnBegin:!0,contains:[d],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[s,l]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:[r,e.C_BLOCK_COMMENT_MODE,s,l,o,{begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:["self",r,e.C_BLOCK_COMMENT_MODE,s,l,o]}]},o,r,e.C_BLOCK_COMMENT_MODE,c]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:p,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(g,h,_,m,[c,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:p,contains:["self",o]},{begin:e.IDENT_RE+"::",keywords:p},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}(e),n=r.keywords;return n.type=[...n.type,...t.type],n.literal=[...n.literal,...t.literal],n.built_in=[...n.built_in,...t.built_in],n._hints=t._hints,r.name="Arduino",r.aliases=["ino"],r.supersetOf="cpp",r}),Xd)),zf.registerLanguage("armasm",(eu||(eu=1,Jd=function(e){const t={variants:[e.COMMENT("^[ \\t]*(?=#)","$",{relevance:0,excludeBegin:!0}),e.COMMENT("[;@]","$",{relevance:0}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]};return{name:"ARM Assembly",case_insensitive:!0,aliases:["arm"],keywords:{$pattern:"\\.?"+e.IDENT_RE,meta:".2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .arm .thumb .code16 .code32 .force_thumb .thumb_func .ltorg ALIAS ALIGN ARM AREA ASSERT ATTR CN CODE CODE16 CODE32 COMMON CP DATA DCB DCD DCDU DCDO DCFD DCFDU DCI DCQ DCQU DCW DCWU DN ELIF ELSE END ENDFUNC ENDIF ENDP ENTRY EQU EXPORT EXPORTAS EXTERN FIELD FILL FUNCTION GBLA GBLL GBLS GET GLOBAL IF IMPORT INCBIN INCLUDE INFO KEEP LCLA LCLL LCLS LTORG MACRO MAP MEND MEXIT NOFP OPT PRESERVE8 PROC QN READONLY RELOC REQUIRE REQUIRE8 RLIST FN ROUT SETA SETL SETS SN SPACE SUBT THUMB THUMBX TTL WHILE WEND ",built_in:"r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 w0 w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12 w13 w14 w15 w16 w17 w18 w19 w20 w21 w22 w23 w24 w25 w26 w27 w28 w29 w30 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 pc lr sp ip sl sb fp a1 a2 a3 a4 v1 v2 v3 v4 v5 v6 v7 v8 f0 f1 f2 f3 f4 f5 f6 f7 p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 q0 q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 cpsr_c cpsr_x cpsr_s cpsr_f cpsr_cx cpsr_cxs cpsr_xs cpsr_xsf cpsr_sf cpsr_cxsf spsr_c spsr_x spsr_s spsr_f spsr_cx spsr_cxs spsr_xs spsr_xsf spsr_sf spsr_cxsf s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 s16 s17 s18 s19 s20 s21 s22 s23 s24 s25 s26 s27 s28 s29 s30 s31 d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 d16 d17 d18 d19 d20 d21 d22 d23 d24 d25 d26 d27 d28 d29 d30 d31 {PC} {VAR} {TRUE} {FALSE} {OPT} {CONFIG} {ENDIAN} {CODESIZE} {CPU} {FPU} {ARCHITECTURE} {PCSTOREOFFSET} {ARMASM_VERSION} {INTER} {ROPI} {RWPI} {SWST} {NOSWST} . @"},contains:[{className:"keyword",begin:"\\b(adc|(qd?|sh?|u[qh]?)?add(8|16)?|usada?8|(q|sh?|u[qh]?)?(as|sa)x|and|adrl?|sbc|rs[bc]|asr|b[lx]?|blx|bxj|cbn?z|tb[bh]|bic|bfc|bfi|[su]bfx|bkpt|cdp2?|clz|clrex|cmp|cmn|cpsi[ed]|cps|setend|dbg|dmb|dsb|eor|isb|it[te]{0,3}|lsl|lsr|ror|rrx|ldm(([id][ab])|f[ds])?|ldr((s|ex)?[bhd])?|movt?|mvn|mra|mar|mul|[us]mull|smul[bwt][bt]|smu[as]d|smmul|smmla|mla|umlaal|smlal?([wbt][bt]|d)|mls|smlsl?[ds]|smc|svc|sev|mia([bt]{2}|ph)?|mrr?c2?|mcrr2?|mrs|msr|orr|orn|pkh(tb|bt)|rbit|rev(16|sh)?|sel|[su]sat(16)?|nop|pop|push|rfe([id][ab])?|stm([id][ab])?|str(ex)?[bhd]?|(qd?)?sub|(sh?|q|u[qh]?)?sub(8|16)|[su]xt(a?h|a?b(16)?)|srs([id][ab])?|swpb?|swi|smi|tst|teq|wfe|wfi|yield)(eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al|hs|lo)?[sptrx]?(?=\\s)"},t,e.QUOTE_STRING_MODE,{className:"string",begin:"'",end:"[^\\\\]'",relevance:0},{className:"title",begin:"\\|",end:"\\|",illegal:"\\n",relevance:0},{className:"number",variants:[{begin:"[#$=]?0x[0-9a-f]+"},{begin:"[#$=]?0b[01]+"},{begin:"[#$=]\\d+"},{begin:"\\b\\d+"}],relevance:0},{className:"symbol",variants:[{begin:"^[ \\t]*[a-z_\\.\\$][a-z0-9_\\.\\$]+:"},{begin:"^[a-z_\\.\\$][a-z0-9_\\.\\$]+"},{begin:"[=#]\\w+"}],relevance:0}]}}),Jd)),zf.registerLanguage("xml",(ru||(ru=1,tu=function(e){const t=e.regex,r=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),n={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},i=e.inherit(a,{begin:/\(/,end:/\)/}),o=e.inherit(e.APOS_STRING_MODE,{className:"string"}),s=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),l={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:/[\p{L}0-9._:-]+/u,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[n]},{begin:/'/,end:/'/,contains:[n]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[a,s,o,i,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[a,i,s,o]}]}]},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},n,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[s]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[l],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[l],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(/</,t.lookahead(t.concat(r,t.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:r,relevance:0,starts:l}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(r,/>/))),contains:[{className:"name",begin:r,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}),tu)),zf.registerLanguage("asciidoc",(au||(au=1,nu=function(e){const t=e.regex,r=[{className:"strong",begin:/\*{2}([^\n]+?)\*{2}/},{className:"strong",begin:t.concat(/\*\*/,/((\*(?!\*)|\\[^\n]|[^*\n\\])+\n)+/,/(\*(?!\*)|\\[^\n]|[^*\n\\])*/,/\*\*/),relevance:0},{className:"strong",begin:/\B\*(\S|\S[^\n]*?\S)\*(?!\w)/},{className:"strong",begin:/\*[^\s]([^\n]+\n)+([^\n]+)\*/}],n=[{className:"emphasis",begin:/_{2}([^\n]+?)_{2}/},{className:"emphasis",begin:t.concat(/__/,/((_(?!_)|\\[^\n]|[^_\n\\])+\n)+/,/(_(?!_)|\\[^\n]|[^_\n\\])*/,/__/),relevance:0},{className:"emphasis",begin:/\b_(\S|\S[^\n]*?\S)_(?!\w)/},{className:"emphasis",begin:/_[^\s]([^\n]+\n)+([^\n]+)_/},{className:"emphasis",begin:"\\B'(?!['\\s])",end:"(\\n{2}|')",contains:[{begin:"\\\\'\\w",relevance:0}],relevance:0}];return{name:"AsciiDoc",aliases:["adoc"],contains:[e.COMMENT("^/{4,}\\n","\\n/{4,}$",{relevance:10}),e.COMMENT("^//","$",{relevance:0}),{className:"title",begin:"^\\.\\w.*$"},{begin:"^[=\\*]{4,}\\n",end:"\\n^[=\\*]{4,}$",relevance:10},{className:"section",relevance:10,variants:[{begin:"^(={1,6})[ \t].+?([ \t]\\1)?$"},{begin:"^[^\\[\\]\\n]+?\\n[=\\-~\\^\\+]{2,}$"}]},{className:"meta",begin:"^:.+?:",end:"\\s",excludeEnd:!0,relevance:10},{className:"meta",begin:"^\\[.+?\\]$",relevance:0},{className:"quote",begin:"^_{4,}\\n",end:"\\n_{4,}$",relevance:10},{className:"code",begin:"^[\\-\\.]{4,}\\n",end:"\\n[\\-\\.]{4,}$",relevance:10},{begin:"^\\+{4,}\\n",end:"\\n\\+{4,}$",contains:[{begin:"<",end:">",subLanguage:"xml",relevance:0}],relevance:10},{className:"bullet",begin:"^(\\*+|-+|\\.+|[^\\n]+?::)\\s+"},{className:"symbol",begin:"^(NOTE|TIP|IMPORTANT|WARNING|CAUTION):\\s+",relevance:10},{begin:/\\[*_`]/},{begin:/\\\\\*{2}[^\n]*?\*{2}/},{begin:/\\\\_{2}[^\n]*_{2}/},{begin:/\\\\`{2}[^\n]*`{2}/},{begin:/[:;}][*_`](?![*_`])/},...r,...n,{className:"string",variants:[{begin:"``.+?''"},{begin:"`.+?'"}]},{className:"code",begin:/`{2}/,end:/(\n{2}|`{2})/},{className:"code",begin:"(`.+?`|\\+.+?\\+)",relevance:0},{className:"code",begin:"^[ \\t]",end:"$",relevance:0},{begin:"^'{3,}[ \\t]*$",relevance:10},{begin:"(link:)?(http|https|ftp|file|irc|image:?):\\S+?\\[[^[]*?\\]",returnBegin:!0,contains:[{begin:"(link|image:?):",relevance:0},{className:"link",begin:"\\w",end:"[^\\[]+",relevance:0},{className:"string",begin:"\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0,relevance:0}],relevance:10}]}}),nu)),zf.registerLanguage("aspectj",(ou||(ou=1,iu=function(e){const t=e.regex,r=["false","synchronized","int","abstract","float","private","char","boolean","static","null","if","const","for","true","while","long","throw","strictfp","finally","protected","import","native","final","return","void","enum","else","extends","implements","break","transient","new","catch","instanceof","byte","super","volatile","case","assert","short","package","default","double","public","try","this","switch","continue","throws","privileged","aspectOf","adviceexecution","proceed","cflowbelow","cflow","initialization","preinitialization","staticinitialization","withincode","target","within","execution","getWithinTypeName","handler","thisJoinPoint","thisJoinPointStaticPart","thisEnclosingJoinPointStaticPart","declare","parents","warning","error","soft","precedence","thisAspectInstance"],n=["get","set","args","call"];return{name:"AspectJ",keywords:r,illegal:/<\/|#/,contains:[e.COMMENT(/\/\*\*/,/\*\//,{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:/@[A-Za-z]+/}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"class",beginKeywords:"aspect",end:/[{;=]/,excludeEnd:!0,illegal:/[:;"\[\]]/,contains:[{beginKeywords:"extends implements pertypewithin perthis pertarget percflowbelow percflow issingleton"},e.UNDERSCORE_TITLE_MODE,{begin:/\([^\)]*/,end:/[)]+/,keywords:r.concat(n),excludeEnd:!1}]},{className:"class",beginKeywords:"class interface",end:/[{;=]/,excludeEnd:!0,relevance:0,keywords:"class interface",illegal:/[:"\[\]]/,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"pointcut after before around throwing returning",end:/[)]/,excludeEnd:!1,illegal:/["\[\]]/,contains:[{begin:t.concat(e.UNDERSCORE_IDENT_RE,/\s*\(/),returnBegin:!0,contains:[e.UNDERSCORE_TITLE_MODE]}]},{begin:/[:]/,returnBegin:!0,end:/[{;]/,relevance:0,excludeEnd:!1,keywords:r,illegal:/["\[\]]/,contains:[{begin:t.concat(e.UNDERSCORE_IDENT_RE,/\s*\(/),keywords:r.concat(n),relevance:0},e.QUOTE_STRING_MODE]},{beginKeywords:"new throw",relevance:0},{className:"function",begin:/\w+ +\w+(\.\w+)?\s*\([^\)]*\)\s*((throws)[\w\s,]+)?[\{;]/,returnBegin:!0,end:/[{;=]/,keywords:r,excludeEnd:!0,contains:[{begin:t.concat(e.UNDERSCORE_IDENT_RE,/\s*\(/),returnBegin:!0,relevance:0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"params",begin:/\(/,end:/\)/,relevance:0,keywords:r,contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},e.C_NUMBER_MODE,{className:"meta",begin:/@[A-Za-z]+/}]}}),iu)),zf.registerLanguage("autohotkey",(lu||(lu=1,su=function(e){const t={begin:"`[\\s\\S]"};return{name:"AutoHotkey",case_insensitive:!0,aliases:["ahk"],keywords:{keyword:"Break Continue Critical Exit ExitApp Gosub Goto New OnExit Pause return SetBatchLines SetTimer Suspend Thread Throw Until ahk_id ahk_class ahk_pid ahk_exe ahk_group",literal:"true false NOT AND OR",built_in:"ComSpec Clipboard ClipboardAll ErrorLevel"},contains:[t,e.inherit(e.QUOTE_STRING_MODE,{contains:[t]}),e.COMMENT(";","$",{relevance:0}),e.C_BLOCK_COMMENT_MODE,{className:"number",begin:e.NUMBER_RE,relevance:0},{className:"variable",begin:"%[a-zA-Z0-9#_$@]+%"},{className:"built_in",begin:"^\\s*\\w+\\s*(,|%)"},{className:"title",variants:[{begin:'^[^\\n";]+::(?!=)'},{begin:'^[^\\n";]+:(?!=)',relevance:0}]},{className:"meta",begin:"^\\s*#\\w+",end:"$",relevance:0},{className:"built_in",begin:"A_[a-zA-Z0-9]+"},{begin:",\\s*,"}]}}),su)),zf.registerLanguage("autoit",(du||(du=1,cu=function(e){const t={variants:[e.COMMENT(";","$",{relevance:0}),e.COMMENT("#cs","#ce"),e.COMMENT("#comments-start","#comments-end")]},r={begin:"\\$[A-z0-9_]+"},n={className:"string",variants:[{begin:/"/,end:/"/,contains:[{begin:/""/,relevance:0}]},{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]}]},a={variants:[e.BINARY_NUMBER_MODE,e.C_NUMBER_MODE]};return{name:"AutoIt",case_insensitive:!0,illegal:/\/\*/,keywords:{keyword:"ByRef Case Const ContinueCase ContinueLoop Dim Do Else ElseIf EndFunc EndIf EndSelect EndSwitch EndWith Enum Exit ExitLoop For Func Global If In Local Next ReDim Return Select Static Step Switch Then To Until Volatile WEnd While With",built_in:"Abs ACos AdlibRegister AdlibUnRegister Asc AscW ASin Assign ATan AutoItSetOption AutoItWinGetTitle AutoItWinSetTitle Beep Binary BinaryLen BinaryMid BinaryToString BitAND BitNOT BitOR BitRotate BitShift BitXOR BlockInput Break Call CDTray Ceiling Chr ChrW ClipGet ClipPut ConsoleRead ConsoleWrite ConsoleWriteError ControlClick ControlCommand ControlDisable ControlEnable ControlFocus ControlGetFocus ControlGetHandle ControlGetPos ControlGetText ControlHide ControlListView ControlMove ControlSend ControlSetText ControlShow ControlTreeView Cos Dec DirCopy DirCreate DirGetSize DirMove DirRemove DllCall DllCallAddress DllCallbackFree DllCallbackGetPtr DllCallbackRegister DllClose DllOpen DllStructCreate DllStructGetData DllStructGetPtr DllStructGetSize DllStructSetData DriveGetDrive DriveGetFileSystem DriveGetLabel DriveGetSerial DriveGetType DriveMapAdd DriveMapDel DriveMapGet DriveSetLabel DriveSpaceFree DriveSpaceTotal DriveStatus EnvGet EnvSet EnvUpdate Eval Execute Exp FileChangeDir FileClose FileCopy FileCreateNTFSLink FileCreateShortcut FileDelete FileExists FileFindFirstFile FileFindNextFile FileFlush FileGetAttrib FileGetEncoding FileGetLongName FileGetPos FileGetShortcut FileGetShortName FileGetSize FileGetTime FileGetVersion FileInstall FileMove FileOpen FileOpenDialog FileRead FileReadLine FileReadToArray FileRecycle FileRecycleEmpty FileSaveDialog FileSelectFolder FileSetAttrib FileSetEnd FileSetPos FileSetTime FileWrite FileWriteLine Floor FtpSetProxy FuncName GUICreate GUICtrlCreateAvi GUICtrlCreateButton GUICtrlCreateCheckbox GUICtrlCreateCombo GUICtrlCreateContextMenu GUICtrlCreateDate GUICtrlCreateDummy GUICtrlCreateEdit GUICtrlCreateGraphic GUICtrlCreateGroup GUICtrlCreateIcon GUICtrlCreateInput GUICtrlCreateLabel GUICtrlCreateList GUICtrlCreateListView GUICtrlCreateListViewItem GUICtrlCreateMenu GUICtrlCreateMenuItem GUICtrlCreateMonthCal GUICtrlCreateObj GUICtrlCreatePic GUICtrlCreateProgress GUICtrlCreateRadio GUICtrlCreateSlider GUICtrlCreateTab GUICtrlCreateTabItem GUICtrlCreateTreeView GUICtrlCreateTreeViewItem GUICtrlCreateUpdown GUICtrlDelete GUICtrlGetHandle GUICtrlGetState GUICtrlRead GUICtrlRecvMsg GUICtrlRegisterListViewSort GUICtrlSendMsg GUICtrlSendToDummy GUICtrlSetBkColor GUICtrlSetColor GUICtrlSetCursor GUICtrlSetData GUICtrlSetDefBkColor GUICtrlSetDefColor GUICtrlSetFont GUICtrlSetGraphic GUICtrlSetImage GUICtrlSetLimit GUICtrlSetOnEvent GUICtrlSetPos GUICtrlSetResizing GUICtrlSetState GUICtrlSetStyle GUICtrlSetTip GUIDelete GUIGetCursorInfo GUIGetMsg GUIGetStyle GUIRegisterMsg GUISetAccelerators GUISetBkColor GUISetCoord GUISetCursor GUISetFont GUISetHelp GUISetIcon GUISetOnEvent GUISetState GUISetStyle GUIStartGroup GUISwitch Hex HotKeySet HttpSetProxy HttpSetUserAgent HWnd InetClose InetGet InetGetInfo InetGetSize InetRead IniDelete IniRead IniReadSection IniReadSectionNames IniRenameSection IniWrite IniWriteSection InputBox Int IsAdmin IsArray IsBinary IsBool IsDeclared IsDllStruct IsFloat IsFunc IsHWnd IsInt IsKeyword IsNumber IsObj IsPtr IsString Log MemGetStats Mod MouseClick MouseClickDrag MouseDown MouseGetCursor MouseGetPos MouseMove MouseUp MouseWheel MsgBox Number ObjCreate ObjCreateInterface ObjEvent ObjGet ObjName OnAutoItExitRegister OnAutoItExitUnRegister Ping PixelChecksum PixelGetColor PixelSearch ProcessClose ProcessExists ProcessGetStats ProcessList ProcessSetPriority ProcessWait ProcessWaitClose ProgressOff ProgressOn ProgressSet Ptr Random RegDelete RegEnumKey RegEnumVal RegRead RegWrite Round Run RunAs RunAsWait RunWait Send SendKeepActive SetError SetExtended ShellExecute ShellExecuteWait Shutdown Sin Sleep SoundPlay SoundSetWaveVolume SplashImageOn SplashOff SplashTextOn Sqrt SRandom StatusbarGetText StderrRead StdinWrite StdioClose StdoutRead String StringAddCR StringCompare StringFormat StringFromASCIIArray StringInStr StringIsAlNum StringIsAlpha StringIsASCII StringIsDigit StringIsFloat StringIsInt StringIsLower StringIsSpace StringIsUpper StringIsXDigit StringLeft StringLen StringLower StringMid StringRegExp StringRegExpReplace StringReplace StringReverse StringRight StringSplit StringStripCR StringStripWS StringToASCIIArray StringToBinary StringTrimLeft StringTrimRight StringUpper Tan TCPAccept TCPCloseSocket TCPConnect TCPListen TCPNameToIP TCPRecv TCPSend TCPShutdown, UDPShutdown TCPStartup, UDPStartup TimerDiff TimerInit ToolTip TrayCreateItem TrayCreateMenu TrayGetMsg TrayItemDelete TrayItemGetHandle TrayItemGetState TrayItemGetText TrayItemSetOnEvent TrayItemSetState TrayItemSetText TraySetClick TraySetIcon TraySetOnEvent TraySetPauseIcon TraySetState TraySetToolTip TrayTip UBound UDPBind UDPCloseSocket UDPOpen UDPRecv UDPSend VarGetType WinActivate WinActive WinClose WinExists WinFlash WinGetCaretPos WinGetClassList WinGetClientSize WinGetHandle WinGetPos WinGetProcess WinGetState WinGetText WinGetTitle WinKill WinList WinMenuSelectItem WinMinimizeAll WinMinimizeAllUndo WinMove WinSetOnTop WinSetState WinSetTitle WinSetTrans WinWait WinWaitActive WinWaitClose WinWaitNotActive",literal:"True False And Null Not Or Default"},contains:[t,r,n,a,{className:"meta",begin:"#",end:"$",keywords:{keyword:["EndRegion","forcedef","forceref","ignorefunc","include","include-once","NoTrayIcon","OnAutoItStartRegister","pragma","Region","RequireAdmin","Tidy_Off","Tidy_On","Tidy_Parameters"]},contains:[{begin:/\\\n/,relevance:0},{beginKeywords:"include",keywords:{keyword:"include"},end:"$",contains:[n,{className:"string",variants:[{begin:"<",end:">"},{begin:/"/,end:/"/,contains:[{begin:/""/,relevance:0}]},{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]}]}]},n,t]},{className:"symbol",begin:"@[A-z0-9_]+"},{beginKeywords:"Func",end:"$",illegal:"\\$|\\[|%",contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{className:"title.function"}),{className:"params",begin:"\\(",end:"\\)",contains:[r,n,a]}]}]}}),cu)),zf.registerLanguage("avrasm",(pu||(pu=1,uu=function(e){return{name:"AVR Assembly",case_insensitive:!0,keywords:{$pattern:"\\.?"+e.IDENT_RE,keyword:"adc add adiw and andi asr bclr bld brbc brbs brcc brcs break breq brge brhc brhs brid brie brlo brlt brmi brne brpl brsh brtc brts brvc brvs bset bst call cbi cbr clc clh cli cln clr cls clt clv clz com cp cpc cpi cpse dec eicall eijmp elpm eor fmul fmuls fmulsu icall ijmp in inc jmp ld ldd ldi lds lpm lsl lsr mov movw mul muls mulsu neg nop or ori out pop push rcall ret reti rjmp rol ror sbc sbr sbrc sbrs sec seh sbi sbci sbic sbis sbiw sei sen ser ses set sev sez sleep spm st std sts sub subi swap tst wdr",built_in:"r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 x|0 xh xl y|0 yh yl z|0 zh zl ucsr1c udr1 ucsr1a ucsr1b ubrr1l ubrr1h ucsr0c ubrr0h tccr3c tccr3a tccr3b tcnt3h tcnt3l ocr3ah ocr3al ocr3bh ocr3bl ocr3ch ocr3cl icr3h icr3l etimsk etifr tccr1c ocr1ch ocr1cl twcr twdr twar twsr twbr osccal xmcra xmcrb eicra spmcsr spmcr portg ddrg ping portf ddrf sreg sph spl xdiv rampz eicrb eimsk gimsk gicr eifr gifr timsk tifr mcucr mcucsr tccr0 tcnt0 ocr0 assr tccr1a tccr1b tcnt1h tcnt1l ocr1ah ocr1al ocr1bh ocr1bl icr1h icr1l tccr2 tcnt2 ocr2 ocdr wdtcr sfior eearh eearl eedr eecr porta ddra pina portb ddrb pinb portc ddrc pinc portd ddrd pind spdr spsr spcr udr0 ucsr0a ucsr0b ubrr0l acsr admux adcsr adch adcl porte ddre pine pinf",meta:".byte .cseg .db .def .device .dseg .dw .endmacro .equ .eseg .exit .include .list .listmac .macro .nolist .org .set"},contains:[e.C_BLOCK_COMMENT_MODE,e.COMMENT(";","$",{relevance:0}),e.C_NUMBER_MODE,e.BINARY_NUMBER_MODE,{className:"number",begin:"\\b(\\$[a-zA-Z0-9]+|0o[0-7]+)"},e.QUOTE_STRING_MODE,{className:"string",begin:"'",end:"[^\\\\]'",illegal:"[^\\\\][^']"},{className:"symbol",begin:"^[A-Za-z0-9_.$]+:"},{className:"meta",begin:"#",end:"$"},{className:"subst",begin:"@[0-9]+"}]}}),uu)),zf.registerLanguage("awk",(mu||(mu=1,_u=function(e){return{name:"Awk",keywords:{keyword:"BEGIN END if else while do for in break continue delete next nextfile function func exit|10"},contains:[{className:"variable",variants:[{begin:/\$[\w\d#@][\w\d_]*/},{begin:/\$\{(.*?)\}/}]},{className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/(u|b)?r?'''/,end:/'''/,relevance:10},{begin:/(u|b)?r?"""/,end:/"""/,relevance:10},{begin:/(u|r|ur)'/,end:/'/,relevance:10},{begin:/(u|r|ur)"/,end:/"/,relevance:10},{begin:/(b|br)'/,end:/'/},{begin:/(b|br)"/,end:/"/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},e.REGEXP_MODE,e.HASH_COMMENT_MODE,e.NUMBER_MODE]}}),_u)),zf.registerLanguage("axapta",(hu||(hu=1,gu=function(e){const t=e.UNDERSCORE_IDENT_RE,r={keyword:["abstract","as","asc","avg","break","breakpoint","by","byref","case","catch","changecompany","class","client","client","common","const","continue","count","crosscompany","delegate","delete_from","desc","display","div","do","edit","else","eventhandler","exists","extends","final","finally","firstfast","firstonly","firstonly1","firstonly10","firstonly100","firstonly1000","flush","for","forceliterals","forcenestedloop","forceplaceholders","forceselectorder","forupdate","from","generateonly","group","hint","if","implements","in","index","insert_recordset","interface","internal","is","join","like","maxof","minof","mod","namespace","new","next","nofetch","notexists","optimisticlock","order","outer","pessimisticlock","print","private","protected","public","readonly","repeatableread","retry","return","reverse","select","server","setting","static","sum","super","switch","this","throw","try","ttsabort","ttsbegin","ttscommit","unchecked","update_recordset","using","validtimestate","void","where","while"],built_in:["anytype","boolean","byte","char","container","date","double","enum","guid","int","int64","long","real","short","str","utcdatetime","var"],literal:["default","false","null","true"]},n={variants:[{match:[/(class|interface)\s+/,t,/\s+(extends|implements)\s+/,t]},{match:[/class\s+/,t]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:r};return{name:"X++",aliases:["x++"],keywords:r,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,{className:"meta",begin:"#",end:"$"},n]}}),gu)),zf.registerLanguage("bash",(Eu||(Eu=1,fu=function(e){const t=e.regex,r={},n={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[r]}]};Object.assign(r,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},n]});const a={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},i=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},s={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,r,a]};a.contains.push(s);const l={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,r]},c=e.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),d={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],literal:["true","false"],built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"]},contains:[c,e.SHEBANG(),d,l,i,o,{match:/(\/[a-z._-]+)+/},s,{match:/\\"/},{className:"string",begin:/'/,end:/'/},{match:/\\'/},r]}}),fu)),zf.registerLanguage("basic",(Su||(Su=1,bu=function(e){return{name:"BASIC",case_insensitive:!0,illegal:"^.",keywords:{$pattern:"[a-zA-Z][a-zA-Z0-9_$%!#]*",keyword:["ABS","ASC","AND","ATN","AUTO|0","BEEP","BLOAD|10","BSAVE|10","CALL","CALLS","CDBL","CHAIN","CHDIR","CHR$|10","CINT","CIRCLE","CLEAR","CLOSE","CLS","COLOR","COM","COMMON","CONT","COS","CSNG","CSRLIN","CVD","CVI","CVS","DATA","DATE$","DEFDBL","DEFINT","DEFSNG","DEFSTR","DEF|0","SEG","USR","DELETE","DIM","DRAW","EDIT","END","ENVIRON","ENVIRON$","EOF","EQV","ERASE","ERDEV","ERDEV$","ERL","ERR","ERROR","EXP","FIELD","FILES","FIX","FOR|0","FRE","GET","GOSUB|10","GOTO","HEX$","IF","THEN","ELSE|0","INKEY$","INP","INPUT","INPUT#","INPUT$","INSTR","IMP","INT","IOCTL","IOCTL$","KEY","ON","OFF","LIST","KILL","LEFT$","LEN","LET","LINE","LLIST","LOAD","LOC","LOCATE","LOF","LOG","LPRINT","USING","LSET","MERGE","MID$","MKDIR","MKD$","MKI$","MKS$","MOD","NAME","NEW","NEXT","NOISE","NOT","OCT$","ON","OR","PEN","PLAY","STRIG","OPEN","OPTION","BASE","OUT","PAINT","PALETTE","PCOPY","PEEK","PMAP","POINT","POKE","POS","PRINT","PRINT]","PSET","PRESET","PUT","RANDOMIZE","READ","REM","RENUM","RESET|0","RESTORE","RESUME","RETURN|0","RIGHT$","RMDIR","RND","RSET","RUN","SAVE","SCREEN","SGN","SHELL","SIN","SOUND","SPACE$","SPC","SQR","STEP","STICK","STOP","STR$","STRING$","SWAP","SYSTEM","TAB","TAN","TIME$","TIMER","TROFF","TRON","TO","USR","VAL","VARPTR","VARPTR$","VIEW","WAIT","WHILE","WEND","WIDTH","WINDOW","WRITE","XOR"]},contains:[{scope:"string",begin:/"/,end:/"|$/,contains:[e.BACKSLASH_ESCAPE]},e.COMMENT("REM","$",{relevance:10}),e.COMMENT("'","$",{relevance:0}),{className:"symbol",begin:"^[0-9]+ ",relevance:10},{className:"number",begin:"\\b\\d+(\\.\\d+)?([edED]\\d+)?[#!]?",relevance:0},{className:"number",begin:"(&[hH][0-9a-fA-F]{1,4})"},{className:"number",begin:"(&[oO][0-7]{1,6})"}]}}),bu)),zf.registerLanguage("bnf",(Tu||(Tu=1,vu=function(e){return{name:"Backus–Naur Form",contains:[{className:"attribute",begin:/</,end:/>/},{begin:/::=/,end:/$/,contains:[{begin:/</,end:/>/},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]}]}}),vu)),zf.registerLanguage("brainfuck",(Cu||(Cu=1,yu=function(e){const t={className:"literal",begin:/[+-]+/,relevance:0};return{name:"Brainfuck",aliases:["bf"],contains:[e.COMMENT(/[^\[\]\.,\+\-<> \r\n]/,/[\[\]\.,\+\-<> \r\n]/,{contains:[{match:/[ ]+[^\[\]\.,\+\-<> \r\n]/,relevance:0}],returnEnd:!0,relevance:0}),{className:"title",begin:"[\\[\\]]",relevance:0},{className:"string",begin:"[\\.,]",relevance:0},{begin:/(?=\+\+|--)/,contains:[t]},t]}}),yu)),zf.registerLanguage("c",(Ru||(Ru=1,Nu=function(e){const t=e.regex,r=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),n="decltype\\(auto\\)",a="[a-zA-Z_]\\w*::",i="("+n+"|"+t.optional(a)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",o={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:/\batomic_[a-z]{3,6}\b/}]},s={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},c={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(s,{className:"string"}),{className:"string",begin:/<.*?>/},r,e.C_BLOCK_COMMENT_MODE]},d={className:"title",begin:t.optional(a)+e.IDENT_RE,relevance:0},u=t.optional(a)+e.IDENT_RE+"\\s*\\(",p={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},_=[c,o,r,e.C_BLOCK_COMMENT_MODE,l,s],m={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:p,contains:_.concat([{begin:/\(/,end:/\)/,keywords:p,contains:_.concat(["self"]),relevance:0}]),relevance:0},g={begin:"("+i+"[\\*&\\s]+)+"+u,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:p,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:n,keywords:p,relevance:0},{begin:u,returnBegin:!0,contains:[e.inherit(d,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:[r,e.C_BLOCK_COMMENT_MODE,s,l,o,{begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:["self",r,e.C_BLOCK_COMMENT_MODE,s,l,o]}]},o,r,e.C_BLOCK_COMMENT_MODE,c]};return{name:"C",aliases:["h"],keywords:p,disableAutodetect:!0,illegal:"</",contains:[].concat(m,g,_,[c,{begin:e.IDENT_RE+"::",keywords:p},{className:"class",beginKeywords:"enum class struct union",end:/[{;:<>=]/,contains:[{beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:c,strings:s,keywords:p}}}),Nu)),zf.registerLanguage("cal",(Ou||(Ou=1,Au=function(e){const t=e.regex,r=["div","mod","in","and","or","not","xor","asserterror","begin","case","do","downto","else","end","exit","for","local","if","of","repeat","then","to","until","while","with","var"],n=[e.C_LINE_COMMENT_MODE,e.COMMENT(/\{/,/\}/,{relevance:0}),e.COMMENT(/\(\*/,/\*\)/,{relevance:10})],a={className:"string",begin:/'/,end:/'/,contains:[{begin:/''/}]},i={className:"string",begin:/(#\d+)+/},o={match:[/procedure/,/\s+/,/[a-zA-Z_][\w@]*/,/\s*/],scope:{1:"keyword",3:"title.function"},contains:[{className:"params",begin:/\(/,end:/\)/,keywords:r,contains:[a,i,e.NUMBER_MODE]},...n]},s={match:[/OBJECT/,/\s+/,t.either("Table","Form","Report","Dataport","Codeunit","XMLport","MenuSuite","Page","Query"),/\s+/,/\d+/,/\s+(?=[^\s])/,/.*/,/$/],relevance:3,scope:{1:"keyword",3:"type",5:"number",7:"title"}};return{name:"C/AL",case_insensitive:!0,keywords:{keyword:r,literal:"false true"},illegal:/\/\*/,contains:[{match:/[\w]+(?=\=)/,scope:"attribute",relevance:0},a,i,{className:"number",begin:"\\b\\d+(\\.\\d+)?(DT|D|T)",relevance:0},{className:"string",begin:'"',end:'"'},e.NUMBER_MODE,s,o]}}),Au)),zf.registerLanguage("capnproto",(xu||(xu=1,Iu=function(e){const t={variants:[{match:[/(struct|enum|interface)/,/\s+/,e.IDENT_RE]},{match:[/extends/,/\s*\(/,e.IDENT_RE,/\s*\)/]}],scope:{1:"keyword",3:"title.class"}};return{name:"Cap’n Proto",aliases:["capnp"],keywords:{keyword:["struct","enum","interface","union","group","import","using","const","annotation","extends","in","of","on","as","with","from","fixed"],type:["Void","Bool","Int8","Int16","Int32","Int64","UInt8","UInt16","UInt32","UInt64","Float32","Float64","Text","Data","AnyPointer","AnyStruct","Capability","List"],literal:["true","false"]},contains:[e.QUOTE_STRING_MODE,e.NUMBER_MODE,e.HASH_COMMENT_MODE,{className:"meta",begin:/@0x[\w\d]{16};/,illegal:/\n/},{className:"symbol",begin:/@\d+\b/},t]}}),Iu)),zf.registerLanguage("ceylon",(Du||(Du=1,wu=function(e){const t=["assembly","module","package","import","alias","class","interface","object","given","value","assign","void","function","new","of","extends","satisfies","abstracts","in","out","return","break","continue","throw","assert","dynamic","if","else","switch","case","for","while","try","catch","finally","then","let","this","outer","super","is","exists","nonempty"],r={className:"subst",excludeBegin:!0,excludeEnd:!0,begin:/``/,end:/``/,keywords:t,relevance:10},n=[{className:"string",begin:'"""',end:'"""',relevance:10},{className:"string",begin:'"',end:'"',contains:[r]},{className:"string",begin:"'",end:"'"},{className:"number",begin:"#[0-9a-fA-F_]+|\\$[01_]+|[0-9_]+(?:\\.[0-9_](?:[eE][+-]?\\d+)?)?[kMGTPmunpf]?",relevance:0}];return r.contains=n,{name:"Ceylon",keywords:{keyword:t.concat(["shared","abstract","formal","default","actual","variable","late","native","deprecated","final","sealed","annotation","suppressWarnings","small"]),meta:["doc","by","license","see","throws","tagged"]},illegal:"\\$[^01]|#[^0-9a-fA-F]",contains:[e.C_LINE_COMMENT_MODE,e.COMMENT("/\\*","\\*/",{contains:["self"]}),{className:"meta",begin:'@[a-z]\\w*(?::"[^"]*")?'}].concat(n)}}),wu)),zf.registerLanguage("clean",(ku||(ku=1,Mu=function(e){return{name:"Clean",aliases:["icl","dcl"],keywords:{keyword:["if","let","in","with","where","case","of","class","instance","otherwise","implementation","definition","system","module","from","import","qualified","as","special","code","inline","foreign","export","ccall","stdcall","generic","derive","infix","infixl","infixr"],built_in:"Int Real Char Bool",literal:"True False"},contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,{begin:"->|<-[|:]?|#!?|>>=|\\{\\||\\|\\}|:==|=:|<>"}]}}),Mu)),zf.registerLanguage("clojure",(Pu||(Pu=1,Lu=function(e){const t="a-zA-Z_\\-!.?+*=<>&'",r="[#]?["+t+"]["+t+"0-9/;:$#]*",n="def defonce defprotocol defstruct defmulti defmethod defn- defn defmacro deftype defrecord",a={$pattern:r,built_in:n+" cond apply if-not if-let if not not= =|0 <|0 >|0 <=|0 >=|0 ==|0 +|0 /|0 *|0 -|0 rem quot neg? pos? delay? symbol? keyword? true? false? integer? empty? coll? list? set? ifn? fn? associative? sequential? sorted? counted? reversible? number? decimal? class? distinct? isa? float? rational? reduced? ratio? odd? even? char? seq? vector? string? map? nil? contains? zero? instance? not-every? not-any? libspec? -> ->> .. . inc compare do dotimes mapcat take remove take-while drop letfn drop-last take-last drop-while while intern condp case reduced cycle split-at split-with repeat replicate iterate range merge zipmap declare line-seq sort comparator sort-by dorun doall nthnext nthrest partition eval doseq await await-for let agent atom send send-off release-pending-sends add-watch mapv filterv remove-watch agent-error restart-agent set-error-handler error-handler set-error-mode! error-mode shutdown-agents quote var fn loop recur throw try monitor-enter monitor-exit macroexpand macroexpand-1 for dosync and or when when-not when-let comp juxt partial sequence memoize constantly complement identity assert peek pop doto proxy first rest cons cast coll last butlast sigs reify second ffirst fnext nfirst nnext meta with-meta ns in-ns create-ns import refer keys select-keys vals key val rseq name namespace promise into transient persistent! conj! assoc! dissoc! pop! disj! use class type num float double short byte boolean bigint biginteger bigdec print-method print-dup throw-if printf format load compile get-in update-in pr pr-on newline flush read slurp read-line subvec with-open memfn time re-find re-groups rand-int rand mod locking assert-valid-fdecl alias resolve ref deref refset swap! reset! set-validator! compare-and-set! alter-meta! reset-meta! commute get-validator alter ref-set ref-history-count ref-min-history ref-max-history ensure sync io! new next conj set! to-array future future-call into-array aset gen-class reduce map filter find empty hash-map hash-set sorted-map sorted-map-by sorted-set sorted-set-by vec vector seq flatten reverse assoc dissoc list disj get union difference intersection extend extend-type extend-protocol int nth delay count concat chunk chunk-buffer chunk-append chunk-first chunk-rest max min dec unchecked-inc-int unchecked-inc unchecked-dec-inc unchecked-dec unchecked-negate unchecked-add-int unchecked-add unchecked-subtract-int unchecked-subtract chunk-next chunk-cons chunked-seq? prn vary-meta lazy-seq spread list* str find-keyword keyword symbol gensym force rationalize"},i={begin:r,relevance:0},o={scope:"number",relevance:0,variants:[{match:/[-+]?0[xX][0-9a-fA-F]+N?/},{match:/[-+]?0[0-7]+N?/},{match:/[-+]?[1-9][0-9]?[rR][0-9a-zA-Z]+N?/},{match:/[-+]?[0-9]+\/[0-9]+N?/},{match:/[-+]?[0-9]+((\.[0-9]*([eE][+-]?[0-9]+)?M?)|([eE][+-]?[0-9]+M?|M))/},{match:/[-+]?([1-9][0-9]*|0)N?/}]},s={scope:"character",variants:[{match:/\\o[0-3]?[0-7]{1,2}/},{match:/\\u[0-9a-fA-F]{4}/},{match:/\\(newline|space|tab|formfeed|backspace|return)/},{match:/\\\S/,relevance:0}]},l={scope:"regex",begin:/#"/,end:/"/,contains:[e.BACKSLASH_ESCAPE]},c=e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),d={scope:"punctuation",match:/,/,relevance:0},u=e.COMMENT(";","$",{relevance:0}),p={className:"literal",begin:/\b(true|false|nil)\b/},_={begin:"\\[|(#::?"+r+")?\\{",end:"[\\]\\}]",relevance:0},m={className:"symbol",begin:"[:]{1,2}"+r},g={begin:"\\(",end:"\\)"},h={endsWithParent:!0,relevance:0},f={keywords:a,className:"name",begin:r,relevance:0,starts:h},E=[d,g,s,l,c,u,m,_,o,p,i],b={beginKeywords:n,keywords:{$pattern:r,keyword:n},end:'(\\[|#|\\d|"|:|\\{|\\)|\\(|$)',contains:[{className:"title",begin:r,relevance:0,excludeEnd:!0,endsParent:!0}].concat(E)};return g.contains=[b,f,h],h.contains=E,_.contains=E,{name:"Clojure",aliases:["clj","edn"],illegal:/\S/,contains:[d,g,s,l,c,u,m,_,o,p]}}),Lu)),zf.registerLanguage("clojure-repl",Bu?Fu:(Bu=1,Fu=function(e){return{name:"Clojure REPL",contains:[{className:"meta.prompt",begin:/^([\w.-]+|\s*#_)?=>/,starts:{end:/$/,subLanguage:"clojure"}}]}})),zf.registerLanguage("cmake",(Gu||(Gu=1,Uu=function(e){return{name:"CMake",aliases:["cmake.in"],case_insensitive:!0,keywords:{keyword:"break cmake_host_system_information cmake_minimum_required cmake_parse_arguments cmake_policy configure_file continue elseif else endforeach endfunction endif endmacro endwhile execute_process file find_file find_library find_package find_path find_program foreach function get_cmake_property get_directory_property get_filename_component get_property if include include_guard list macro mark_as_advanced math message option return separate_arguments set_directory_properties set_property set site_name string unset variable_watch while add_compile_definitions add_compile_options add_custom_command add_custom_target add_definitions add_dependencies add_executable add_library add_link_options add_subdirectory add_test aux_source_directory build_command create_test_sourcelist define_property enable_language enable_testing export fltk_wrap_ui get_source_file_property get_target_property get_test_property include_directories include_external_msproject include_regular_expression install link_directories link_libraries load_cache project qt_wrap_cpp qt_wrap_ui remove_definitions set_source_files_properties set_target_properties set_tests_properties source_group target_compile_definitions target_compile_features target_compile_options target_include_directories target_link_directories target_link_libraries target_link_options target_sources try_compile try_run ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_submit ctest_test ctest_update ctest_upload build_name exec_program export_library_dependencies install_files install_programs install_targets load_command make_directory output_required_files remove subdir_depends subdirs use_mangled_mesa utility_source variable_requires write_file qt5_use_modules qt5_use_package qt5_wrap_cpp on off true false and or not command policy target test exists is_newer_than is_directory is_symlink is_absolute matches less greater equal less_equal greater_equal strless strgreater strequal strless_equal strgreater_equal version_less version_greater version_equal version_less_equal version_greater_equal in_list defined"},contains:[{className:"variable",begin:/\$\{/,end:/\}/},e.COMMENT(/#\[\[/,/]]/),e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE]}}),Uu)),zf.registerLanguage("coffeescript",function(){if(Yu)return zu;Yu=1;const e=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],t=["true","false","null","undefined","NaN","Infinity"],r=[].concat(["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]);return zu=function(n){const a={keyword:e.concat(["then","unless","until","loop","by","when","and","or","is","isnt","not"]).filter((e=>t=>!e.includes(t))(["var","const","let","function","static"])),literal:t.concat(["yes","no","on","off"]),built_in:r.concat(["npm","print"])},i="[A-Za-z$_][0-9A-Za-z$_]*",o={className:"subst",begin:/#\{/,end:/\}/,keywords:a},s=[n.BINARY_NUMBER_MODE,n.inherit(n.C_NUMBER_MODE,{starts:{end:"(\\s*/)?",relevance:0}}),{className:"string",variants:[{begin:/'''/,end:/'''/,contains:[n.BACKSLASH_ESCAPE]},{begin:/'/,end:/'/,contains:[n.BACKSLASH_ESCAPE]},{begin:/"""/,end:/"""/,contains:[n.BACKSLASH_ESCAPE,o]},{begin:/"/,end:/"/,contains:[n.BACKSLASH_ESCAPE,o]}]},{className:"regexp",variants:[{begin:"///",end:"///",contains:[o,n.HASH_COMMENT_MODE]},{begin:"//[gim]{0,3}(?=\\W)",relevance:0},{begin:/\/(?![ *]).*?(?![\\]).\/[gim]{0,3}(?=\W)/}]},{begin:"@"+i},{subLanguage:"javascript",excludeBegin:!0,excludeEnd:!0,variants:[{begin:"```",end:"```"},{begin:"`",end:"`"}]}];o.contains=s;const l=n.inherit(n.TITLE_MODE,{begin:i}),c="(\\(.*\\)\\s*)?\\B[-=]>",d={className:"params",begin:"\\([^\\(]",returnBegin:!0,contains:[{begin:/\(/,end:/\)/,keywords:a,contains:["self"].concat(s)}]},u={variants:[{match:[/class\s+/,i,/\s+extends\s+/,i]},{match:[/class\s+/,i]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:a};return{name:"CoffeeScript",aliases:["coffee","cson","iced"],keywords:a,illegal:/\/\*/,contains:[...s,n.COMMENT("###","###"),n.HASH_COMMENT_MODE,{className:"function",begin:"^\\s*"+i+"\\s*=\\s*"+c,end:"[-=]>",returnBegin:!0,contains:[l,d]},{begin:/[:\(,=]\s*/,relevance:0,contains:[{className:"function",begin:c,end:"[-=]>",returnBegin:!0,contains:[d]}]},u,{begin:i+":",end:":",returnBegin:!0,returnEnd:!0,relevance:0}]}},zu}()),zf.registerLanguage("coq",(Hu||(Hu=1,qu=function(e){return{name:"Coq",keywords:{keyword:["_|0","as","at","cofix","else","end","exists","exists2","fix","for","forall","fun","if","IF","in","let","match","mod","Prop","return","Set","then","Type","using","where","with","Abort","About","Add","Admit","Admitted","All","Arguments","Assumptions","Axiom","Back","BackTo","Backtrack","Bind","Blacklist","Canonical","Cd","Check","Class","Classes","Close","Coercion","Coercions","CoFixpoint","CoInductive","Collection","Combined","Compute","Conjecture","Conjectures","Constant","constr","Constraint","Constructors","Context","Corollary","CreateHintDb","Cut","Declare","Defined","Definition","Delimit","Dependencies","Dependent","Derive","Drop","eauto","End","Equality","Eval","Example","Existential","Existentials","Existing","Export","exporting","Extern","Extract","Extraction","Fact","Field","Fields","File","Fixpoint","Focus","for","From","Function","Functional","Generalizable","Global","Goal","Grab","Grammar","Graph","Guarded","Heap","Hint","HintDb","Hints","Hypotheses","Hypothesis","ident","Identity","If","Immediate","Implicit","Import","Include","Inductive","Infix","Info","Initial","Inline","Inspect","Instance","Instances","Intro","Intros","Inversion","Inversion_clear","Language","Left","Lemma","Let","Libraries","Library","Load","LoadPath","Local","Locate","Ltac","ML","Mode","Module","Modules","Monomorphic","Morphism","Next","NoInline","Notation","Obligation","Obligations","Opaque","Open","Optimize","Options","Parameter","Parameters","Parametric","Path","Paths","pattern","Polymorphic","Preterm","Print","Printing","Program","Projections","Proof","Proposition","Pwd","Qed","Quit","Rec","Record","Recursive","Redirect","Relation","Remark","Remove","Require","Reserved","Reset","Resolve","Restart","Rewrite","Right","Ring","Rings","Save","Scheme","Scope","Scopes","Script","Search","SearchAbout","SearchHead","SearchPattern","SearchRewrite","Section","Separate","Set","Setoid","Show","Solve","Sorted","Step","Strategies","Strategy","Structure","SubClass","Table","Tables","Tactic","Term","Test","Theorem","Time","Timeout","Transparent","Type","Typeclasses","Types","Undelimit","Undo","Unfocus","Unfocused","Unfold","Universe","Universes","Unset","Unshelve","using","Variable","Variables","Variant","Verbose","Visibility","where","with"],built_in:["abstract","absurd","admit","after","apply","as","assert","assumption","at","auto","autorewrite","autounfold","before","bottom","btauto","by","case","case_eq","cbn","cbv","change","classical_left","classical_right","clear","clearbody","cofix","compare","compute","congruence","constr_eq","constructor","contradict","contradiction","cut","cutrewrite","cycle","decide","decompose","dependent","destruct","destruction","dintuition","discriminate","discrR","do","double","dtauto","eapply","eassumption","eauto","ecase","econstructor","edestruct","ediscriminate","eelim","eexact","eexists","einduction","einjection","eleft","elim","elimtype","enough","equality","erewrite","eright","esimplify_eq","esplit","evar","exact","exactly_once","exfalso","exists","f_equal","fail","field","field_simplify","field_simplify_eq","first","firstorder","fix","fold","fourier","functional","generalize","generalizing","gfail","give_up","has_evar","hnf","idtac","in","induction","injection","instantiate","intro","intro_pattern","intros","intuition","inversion","inversion_clear","is_evar","is_var","lapply","lazy","left","lia","lra","move","native_compute","nia","nsatz","omega","once","pattern","pose","progress","proof","psatz","quote","record","red","refine","reflexivity","remember","rename","repeat","replace","revert","revgoals","rewrite","rewrite_strat","right","ring","ring_simplify","rtauto","set","setoid_reflexivity","setoid_replace","setoid_rewrite","setoid_symmetry","setoid_transitivity","shelve","shelve_unifiable","simpl","simple","simplify_eq","solve","specialize","split","split_Rabs","split_Rmult","stepl","stepr","subst","sum","swap","symmetry","tactic","tauto","time","timeout","top","transitivity","trivial","try","tryif","unfold","unify","until","using","vm_compute","with"]},contains:[e.QUOTE_STRING_MODE,e.COMMENT("\\(\\*","\\*\\)"),e.C_NUMBER_MODE,{className:"type",excludeBegin:!0,begin:"\\|\\s*",end:"\\w+"},{begin:/[-=]>/}]}}),qu)),zf.registerLanguage("cos",($u||($u=1,Vu=function(e){return{name:"Caché Object Script",case_insensitive:!0,aliases:["cls"],keywords:"property parameter class classmethod clientmethod extends as break catch close continue do d|0 else elseif for goto halt hang h|0 if job j|0 kill k|0 lock l|0 merge new open quit q|0 read r|0 return set s|0 tcommit throw trollback try tstart use view while write w|0 xecute x|0 zkill znspace zn ztrap zwrite zw zzdump zzwrite print zbreak zinsert zload zprint zremove zsave zzprint mv mvcall mvcrt mvdim mvprint zquit zsync ascii",contains:[{className:"number",begin:"\\b(\\d+(\\.\\d*)?|\\.\\d+)",relevance:0},{className:"string",variants:[{begin:'"',end:'"',contains:[{begin:'""',relevance:0}]}]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"comment",begin:/;/,end:"$",relevance:0},{className:"built_in",begin:/(?:\$\$?|\.\.)\^?[a-zA-Z]+/},{className:"built_in",begin:/\$\$\$[a-zA-Z]+/},{className:"built_in",begin:/%[a-z]+(?:\.[a-z]+)*/},{className:"symbol",begin:/\^%?[a-zA-Z][\w]*/},{className:"keyword",begin:/##class|##super|#define|#dim/},{begin:/&sql\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,subLanguage:"sql"},{begin:/&(js|jscript|javascript)</,end:/>/,excludeBegin:!0,excludeEnd:!0,subLanguage:"javascript"},{begin:/&html<\s*</,end:/>\s*>/,subLanguage:"xml"}]}}),Vu)),zf.registerLanguage("cpp",(ju||(ju=1,Wu=function(e){const t=e.regex,r=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),n="decltype\\(auto\\)",a="[a-zA-Z_]\\w*::",i="(?!struct)("+n+"|"+t.optional(a)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",o={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},s={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},c={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(s,{className:"string"}),{className:"string",begin:/<.*?>/},r,e.C_BLOCK_COMMENT_MODE]},d={className:"title",begin:t.optional(a)+e.IDENT_RE,relevance:0},u=t.optional(a)+e.IDENT_RE+"\\s*\\(",p={type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],keyword:["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"]},_={className:"function.dispatch",relevance:0,keywords:{_hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"]},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},m=[_,c,o,r,e.C_BLOCK_COMMENT_MODE,l,s],g={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:p,contains:m.concat([{begin:/\(/,end:/\)/,keywords:p,contains:m.concat(["self"]),relevance:0}]),relevance:0},h={className:"function",begin:"("+i+"[\\*&\\s]+)+"+u,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:p,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:n,keywords:p,relevance:0},{begin:u,returnBegin:!0,contains:[d],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[s,l]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:[r,e.C_BLOCK_COMMENT_MODE,s,l,o,{begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:["self",r,e.C_BLOCK_COMMENT_MODE,s,l,o]}]},o,r,e.C_BLOCK_COMMENT_MODE,c]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:p,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(g,h,_,m,[c,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:p,contains:["self",o]},{begin:e.IDENT_RE+"::",keywords:p},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}),Wu)),zf.registerLanguage("crmsh",(Ku||(Ku=1,Qu=function(e){const t="group clone ms master location colocation order fencing_topology rsc_ticket acl_target acl_group user role tag xml";return{name:"crmsh",aliases:["crm","pcmk"],case_insensitive:!0,keywords:{keyword:"params meta operations op rule attributes utilization read write deny defined not_defined in_range date spec in ref reference attribute type xpath version and or lt gt tag lte gte eq ne \\ number string",literal:"Master Started Slave Stopped start promote demote stop monitor true false"},contains:[e.HASH_COMMENT_MODE,{beginKeywords:"node",starts:{end:"\\s*([\\w_-]+:)?",starts:{className:"title",end:"\\s*[\\$\\w_][\\w_-]*"}}},{beginKeywords:"primitive rsc_template",starts:{className:"title",end:"\\s*[\\$\\w_][\\w_-]*",starts:{end:"\\s*@?[\\w_][\\w_\\.:-]*"}}},{begin:"\\b("+t.split(" ").join("|")+")\\s+",keywords:t,starts:{className:"title",end:"[\\$\\w_][\\w_-]*"}},{beginKeywords:"property rsc_defaults op_defaults",starts:{className:"title",end:"\\s*([\\w_-]+:)?"}},e.QUOTE_STRING_MODE,{className:"meta",begin:"(ocf|systemd|service|lsb):[\\w_:-]+",relevance:0},{className:"number",begin:"\\b\\d+(\\.\\d+)?(ms|s|h|m)?",relevance:0},{className:"literal",begin:"[-]?(infinity|inf)",relevance:0},{className:"attr",begin:/([A-Za-z$_#][\w_-]+)=/,relevance:0},{className:"tag",begin:"</?",end:"/?>",relevance:0}]}}),Qu)),zf.registerLanguage("crystal",(Zu||(Zu=1,Xu=function(e){const t="(_?[ui](8|16|32|64|128))?",r="[a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|[=!]~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~|]|//|//=|&[-+*]=?|&\\*\\*|\\[\\][=?]?",n="[A-Za-z_]\\w*(::\\w+)*(\\?|!)?",a={$pattern:"[a-zA-Z_]\\w*[!?=]?",keyword:"abstract alias annotation as as? asm begin break case class def do else elsif end ensure enum extend for fun if include instance_sizeof is_a? lib macro module next nil? of out pointerof private protected rescue responds_to? return require select self sizeof struct super then type typeof union uninitialized unless until verbatim when while with yield __DIR__ __END_LINE__ __FILE__ __LINE__",literal:"false nil true"},i={className:"subst",begin:/#\{/,end:/\}/,keywords:a},o={className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},s={className:"template-variable",variants:[{begin:"\\{\\{",end:"\\}\\}"},{begin:"\\{%",end:"%\\}"}],keywords:a};function l(e,t){const r=[{begin:e,end:t}];return r[0].contains=r,r}const c={className:"string",contains:[e.BACKSLASH_ESCAPE,i],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:"%[Qwi]?\\(",end:"\\)",contains:l("\\(","\\)")},{begin:"%[Qwi]?\\[",end:"\\]",contains:l("\\[","\\]")},{begin:"%[Qwi]?\\{",end:/\}/,contains:l(/\{/,/\}/)},{begin:"%[Qwi]?<",end:">",contains:l("<",">")},{begin:"%[Qwi]?\\|",end:"\\|"},{begin:/<<-\w+$/,end:/^\s*\w+$/}],relevance:0},d={className:"string",variants:[{begin:"%q\\(",end:"\\)",contains:l("\\(","\\)")},{begin:"%q\\[",end:"\\]",contains:l("\\[","\\]")},{begin:"%q\\{",end:/\}/,contains:l(/\{/,/\}/)},{begin:"%q<",end:">",contains:l("<",">")},{begin:"%q\\|",end:"\\|"},{begin:/<<-'\w+'$/,end:/^\s*\w+$/}],relevance:0},u={begin:"(?!%\\})("+e.RE_STARTERS_RE+"|\\n|\\b(case|if|select|unless|until|when|while)\\b)\\s*",keywords:"case if select unless until when while",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,i],variants:[{begin:"//[a-z]*",relevance:0},{begin:"/(?!\\/)",end:"/[a-z]*"}]}],relevance:0},p=[s,c,d,{className:"regexp",contains:[e.BACKSLASH_ESCAPE,i],variants:[{begin:"%r\\(",end:"\\)",contains:l("\\(","\\)")},{begin:"%r\\[",end:"\\]",contains:l("\\[","\\]")},{begin:"%r\\{",end:/\}/,contains:l(/\{/,/\}/)},{begin:"%r<",end:">",contains:l("<",">")},{begin:"%r\\|",end:"\\|"}],relevance:0},u,{className:"meta",begin:"@\\[",end:"\\]",contains:[e.inherit(e.QUOTE_STRING_MODE,{className:"string"})]},o,e.HASH_COMMENT_MODE,{className:"class",beginKeywords:"class module struct",end:"$|;",illegal:/=/,contains:[e.HASH_COMMENT_MODE,e.inherit(e.TITLE_MODE,{begin:n}),{begin:"<"}]},{className:"class",beginKeywords:"lib enum union",end:"$|;",illegal:/=/,contains:[e.HASH_COMMENT_MODE,e.inherit(e.TITLE_MODE,{begin:n})]},{beginKeywords:"annotation",end:"$|;",illegal:/=/,contains:[e.HASH_COMMENT_MODE,e.inherit(e.TITLE_MODE,{begin:n})],relevance:2},{className:"function",beginKeywords:"def",end:/\B\b/,contains:[e.inherit(e.TITLE_MODE,{begin:r,endsParent:!0})]},{className:"function",beginKeywords:"fun macro",end:/\B\b/,contains:[e.inherit(e.TITLE_MODE,{begin:r,endsParent:!0})],relevance:2},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":",contains:[c,{begin:r}],relevance:0},{className:"number",variants:[{begin:"\\b0b([01_]+)"+t},{begin:"\\b0o([0-7_]+)"+t},{begin:"\\b0x([A-Fa-f0-9_]+)"+t},{begin:"\\b([1-9][0-9_]*[0-9]|[0-9])(\\.[0-9][0-9_]*)?([eE]_?[-+]?[0-9_]*)?(_?f(32|64))?(?!_)"},{begin:"\\b([1-9][0-9_]*|0)"+t}],relevance:0}];return i.contains=p,s.contains=p.slice(1),{name:"Crystal",aliases:["cr"],keywords:a,contains:p}}),Xu)),zf.registerLanguage("csharp",(ep||(ep=1,Ju=function(e){const t={keyword:["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"].concat(["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"]),built_in:["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],literal:["default","false","null","true"]},r=e.inherit(e.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),n={className:"number",variants:[{begin:"\\b(0b[01']+)"},{begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],relevance:0},a={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},i=e.inherit(a,{illegal:/\n/}),o={className:"subst",begin:/\{/,end:/\}/,keywords:t},s=e.inherit(o,{illegal:/\n/}),l={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},e.BACKSLASH_ESCAPE,s]},c={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},o]},d=e.inherit(c,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},s]});o.contains=[c,l,a,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,n,e.C_BLOCK_COMMENT_MODE],s.contains=[d,l,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,n,e.inherit(e.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];const u={variants:[{className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},c,l,a,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},p={begin:"<",end:">",contains:[{beginKeywords:"in out"},r]},_=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",m={begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:t,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:"\x3c!--|--\x3e"},{begin:"</?",end:">"}]}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},u,n,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},r,p,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[r,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[r,p,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+_+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:t,contains:[{beginKeywords:["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"].join(" "),relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[e.TITLE_MODE,p],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:t,relevance:0,contains:[u,n,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},m]}}),Ju)),zf.registerLanguage("csp",rp?tp:(rp=1,tp=function(e){return{name:"CSP",case_insensitive:!1,keywords:{$pattern:"[a-zA-Z][a-zA-Z0-9_-]*",keyword:["base-uri","child-src","connect-src","default-src","font-src","form-action","frame-ancestors","frame-src","img-src","manifest-src","media-src","object-src","plugin-types","report-uri","sandbox","script-src","style-src","trusted-types","unsafe-hashes","worker-src"]},contains:[{className:"string",begin:"'",end:"'"},{className:"attribute",begin:"^Content",end:":",excludeEnd:!0}]}})),zf.registerLanguage("css",function(){if(ap)return np;ap=1;const e=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],t=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),r=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),n=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),a=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();return np=function(i){const o=i.regex,s=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(i),l=[i.APOS_STRING_MODE,i.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[s.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/},s.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},s.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+r.join("|")+")"},{begin:":(:)?("+n.join("|")+")"}]},s.CSS_VARIABLE,{className:"attribute",begin:"\\b("+a.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[s.BLOCK_COMMENT,s.HEXCOLOR,s.IMPORTANT,s.CSS_NUMBER_MODE,...l,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...l,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},s.FUNCTION_DISPATCH]},{begin:o.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:t.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...l,s.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+e.join("|")+")\\b"}]}},np}()),zf.registerLanguage("d",(op||(op=1,ip=function(e){const t={$pattern:e.UNDERSCORE_IDENT_RE,keyword:"abstract alias align asm assert auto body break byte case cast catch class const continue debug default delete deprecated do else enum export extern final finally for foreach foreach_reverse|10 goto if immutable import in inout int interface invariant is lazy macro mixin module new nothrow out override package pragma private protected public pure ref return scope shared static struct super switch synchronized template this throw try typedef typeid typeof union unittest version void volatile while with __FILE__ __LINE__ __gshared|10 __thread __traits __DATE__ __EOF__ __TIME__ __TIMESTAMP__ __VENDOR__ __VERSION__",built_in:"bool cdouble cent cfloat char creal dchar delegate double dstring float function idouble ifloat ireal long real short string ubyte ucent uint ulong ushort wchar wstring",literal:"false null true"},r="(0|[1-9][\\d_]*)",n="(0|[1-9][\\d_]*|\\d[\\d_]*|[\\d_]+?\\d)",a="([\\da-fA-F][\\da-fA-F_]*|_[\\da-fA-F][\\da-fA-F_]*)",i="([eE][+-]?"+n+")",o="("+r+"|0[bB][01_]+|0[xX]"+a+")",s="\\\\(['\"\\?\\\\abfnrtv]|u[\\dA-Fa-f]{4}|[0-7]{1,3}|x[\\dA-Fa-f]{2}|U[\\dA-Fa-f]{8})|&[a-zA-Z\\d]{2,};",l={className:"number",begin:"\\b"+o+"(L|u|U|Lu|LU|uL|UL)?",relevance:0},c={className:"number",begin:"\\b(((0[xX]("+a+"\\."+a+"|\\.?"+a+")[pP][+-]?"+n+")|("+n+"(\\.\\d*|"+i+")|\\d+\\."+n+"|\\."+r+i+"?))([fF]|L|i|[fF]i|Li)?|"+o+"(i|[fF]i|Li))",relevance:0},d={className:"string",begin:"'("+s+"|.)",end:"'",illegal:"."},u={className:"string",begin:'"',contains:[{begin:s,relevance:0}],end:'"[cwd]?'},p=e.COMMENT("\\/\\+","\\+\\/",{contains:["self"],relevance:10});return{name:"D",keywords:t,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,p,{className:"string",begin:'x"[\\da-fA-F\\s\\n\\r]*"[cwd]?',relevance:10},u,{className:"string",begin:'[rq]"',end:'"[cwd]?',relevance:5},{className:"string",begin:"`",end:"`[cwd]?"},{className:"string",begin:'q"\\{',end:'\\}"'},c,l,d,{className:"meta",begin:"^#!",end:"$",relevance:5},{className:"meta",begin:"#(line)",end:"$",relevance:5},{className:"keyword",begin:"@[a-zA-Z_][a-zA-Z_\\d]*"}]}}),ip)),zf.registerLanguage("markdown",(lp||(lp=1,sp=function(e){const t={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},r={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:e.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},n={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},a={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},i=e.inherit(n,{contains:[]}),o=e.inherit(a,{contains:[]});n.contains.push(o),a.contains.push(i);let s=[t,r];return[n,a,i,o].forEach(e=>{e.contains=e.contains.concat(s)}),s=s.concat(n,a),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:s},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:s}]}]},t,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},n,a,{className:"quote",begin:"^>\\s+",contains:s,end:"$"},{className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{begin:"^[-\\*]{3,}",end:"$"},r,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}),sp)),zf.registerLanguage("dart",(dp||(dp=1,cp=function(e){const t={className:"subst",variants:[{begin:"\\$[A-Za-z0-9_]+"}]},r={className:"subst",variants:[{begin:/\$\{/,end:/\}/}],keywords:"true false null this is new super"},n={className:"number",relevance:0,variants:[{match:/\b[0-9][0-9_]*(\.[0-9][0-9_]*)?([eE][+-]?[0-9][0-9_]*)?\b/},{match:/\b0[xX][0-9A-Fa-f][0-9A-Fa-f_]*\b/}]},a={className:"string",variants:[{begin:"r'''",end:"'''"},{begin:'r"""',end:'"""'},{begin:"r'",end:"'",illegal:"\\n"},{begin:'r"',end:'"',illegal:"\\n"},{begin:"'''",end:"'''",contains:[e.BACKSLASH_ESCAPE,t,r]},{begin:'"""',end:'"""',contains:[e.BACKSLASH_ESCAPE,t,r]},{begin:"'",end:"'",illegal:"\\n",contains:[e.BACKSLASH_ESCAPE,t,r]},{begin:'"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE,t,r]}]};r.contains=[n,a];const i=["Comparable","DateTime","Duration","Function","Iterable","Iterator","List","Map","Match","Object","Pattern","RegExp","Set","Stopwatch","String","StringBuffer","StringSink","Symbol","Type","Uri","bool","double","int","num","Element","ElementList"],o=i.map(e=>`${e}?`);return{name:"Dart",keywords:{keyword:["abstract","as","assert","async","await","base","break","case","catch","class","const","continue","covariant","default","deferred","do","dynamic","else","enum","export","extends","extension","external","factory","false","final","finally","for","Function","get","hide","if","implements","import","in","interface","is","late","library","mixin","new","null","on","operator","part","required","rethrow","return","sealed","set","show","static","super","switch","sync","this","throw","true","try","typedef","var","void","when","while","with","yield"],built_in:i.concat(o).concat(["Never","Null","dynamic","print","document","querySelector","querySelectorAll","window"]),$pattern:/[A-Za-z][A-Za-z0-9_]*\??/},contains:[a,e.COMMENT(/\/\*\*(?!\/)/,/\*\//,{subLanguage:"markdown",relevance:0}),e.COMMENT(/\/{3,} ?/,/$/,{contains:[{subLanguage:"markdown",begin:".",end:"$",relevance:0}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"class",beginKeywords:"class interface",end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},n,{className:"meta",begin:"@[A-Za-z]+"},{begin:"=>"}]}}),cp)),zf.registerLanguage("delphi",(pp||(pp=1,up=function(e){const t=["exports","register","file","shl","array","record","property","for","mod","while","set","ally","label","uses","raise","not","stored","class","safecall","var","interface","or","private","static","exit","index","inherited","to","else","stdcall","override","shr","asm","far","resourcestring","finalization","packed","virtual","out","and","protected","library","do","xorwrite","goto","near","function","end","div","overload","object","unit","begin","string","on","inline","repeat","until","destructor","write","message","program","with","read","initialization","except","default","nil","if","case","cdecl","in","downto","threadvar","of","try","pascal","const","external","constructor","type","public","then","implementation","finally","published","procedure","absolute","reintroduce","operator","as","is","abstract","alias","assembler","bitpacked","break","continue","cppdecl","cvar","enumerator","experimental","platform","deprecated","unimplemented","dynamic","export","far16","forward","generic","helper","implements","interrupt","iochecks","local","name","nodefault","noreturn","nostackframe","oldfpccall","otherwise","saveregisters","softfloat","specialize","strict","unaligned","varargs"],r=[e.C_LINE_COMMENT_MODE,e.COMMENT(/\{/,/\}/,{relevance:0}),e.COMMENT(/\(\*/,/\*\)/,{relevance:10})],n={className:"meta",variants:[{begin:/\{\$/,end:/\}/},{begin:/\(\*\$/,end:/\*\)/}]},a={className:"string",begin:/'/,end:/'/,contains:[{begin:/''/}]},i={className:"string",variants:[{match:/#\d[\d_]*/},{match:/#\$[\dA-Fa-f][\dA-Fa-f_]*/},{match:/#&[0-7][0-7_]*/},{match:/#%[01][01_]*/}]},o={begin:e.IDENT_RE+"\\s*=\\s*class\\s*\\(",returnBegin:!0,contains:[e.TITLE_MODE]},s={className:"function",beginKeywords:"function constructor destructor procedure",end:/[:;]/,keywords:"function constructor|10 destructor|10 procedure|10",contains:[e.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,keywords:t,contains:[a,i,n].concat(r)},n].concat(r)};return{name:"Delphi",aliases:["dpr","dfm","pas","pascal"],case_insensitive:!0,keywords:t,illegal:/"|\$[G-Zg-z]|\/\*|<\/|\|/,contains:[a,i,{className:"number",relevance:0,variants:[{match:/\b\d[\d_]*(\.\d[\d_]*)?/},{match:/\$[\dA-Fa-f_]+/},{match:/\$/,relevance:0},{match:/&[0-7][0-7_]*/},{match:/%[01_]+/},{match:/%/,relevance:0}]},o,s,n].concat(r)}}),up)),zf.registerLanguage("diff",(mp||(mp=1,_p=function(e){const t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}}),_p)),zf.registerLanguage("django",(hp||(hp=1,gp=function(e){const t={begin:/\|[A-Za-z]+:?/,keywords:{name:"truncatewords removetags linebreaksbr yesno get_digit timesince random striptags filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort dictsortreversed default_if_none pluralize lower join center default truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize localtime utc timezone"},contains:[e.QUOTE_STRING_MODE,e.APOS_STRING_MODE]};return{name:"Django",aliases:["jinja"],case_insensitive:!0,subLanguage:"xml",contains:[e.COMMENT(/\{%\s*comment\s*%\}/,/\{%\s*endcomment\s*%\}/),e.COMMENT(/\{#/,/#\}/),{className:"template-tag",begin:/\{%/,end:/%\}/,contains:[{className:"name",begin:/\w+/,keywords:{name:"comment endcomment load templatetag ifchanged endifchanged if endif firstof for endfor ifnotequal endifnotequal widthratio extends include spaceless endspaceless regroup ifequal endifequal ssi now with cycle url filter endfilter debug block endblock else autoescape endautoescape csrf_token empty elif endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix plural get_current_language language get_available_languages get_current_language_bidi get_language_info get_language_info_list localize endlocalize localtime endlocaltime timezone endtimezone get_current_timezone verbatim"},starts:{endsWithParent:!0,keywords:"in by as",contains:[t],relevance:0}}]},{className:"template-variable",begin:/\{\{/,end:/\}\}/,contains:[t]}]}}),gp)),zf.registerLanguage("dns",(Ep||(Ep=1,fp=function(e){return{name:"DNS Zone",aliases:["bind","zone"],keywords:["IN","A","AAAA","AFSDB","APL","CAA","CDNSKEY","CDS","CERT","CNAME","DHCID","DLV","DNAME","DNSKEY","DS","HIP","IPSECKEY","KEY","KX","LOC","MX","NAPTR","NS","NSEC","NSEC3","NSEC3PARAM","PTR","RRSIG","RP","SIG","SOA","SRV","SSHFP","TA","TKEY","TLSA","TSIG","TXT"],contains:[e.COMMENT(";","$",{relevance:0}),{className:"meta",begin:/^\$(TTL|GENERATE|INCLUDE|ORIGIN)\b/},{className:"number",begin:"((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))\\b"},{className:"number",begin:"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\b"},e.inherit(e.NUMBER_MODE,{begin:/\b\d+[dhwm]?/})]}}),fp)),zf.registerLanguage("dockerfile",(Sp||(Sp=1,bp=function(e){return{name:"Dockerfile",aliases:["docker"],case_insensitive:!0,keywords:["from","maintainer","expose","env","arg","user","onbuild","stopsignal"],contains:[e.HASH_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{beginKeywords:"run cmd entrypoint volume add copy workdir label healthcheck shell",starts:{end:/[^\\]$/,subLanguage:"bash"}}],illegal:"</"}}),bp)),zf.registerLanguage("dos",(Tp||(Tp=1,vp=function(e){const t=e.COMMENT(/^\s*@?rem\b/,/$/,{relevance:10});return{name:"Batch file (DOS)",aliases:["bat","cmd"],case_insensitive:!0,illegal:/\/\*/,keywords:{keyword:["if","else","goto","for","in","do","call","exit","not","exist","errorlevel","defined","equ","neq","lss","leq","gtr","geq"],built_in:["prn","nul","lpt3","lpt2","lpt1","con","com4","com3","com2","com1","aux","shift","cd","dir","echo","setlocal","endlocal","set","pause","copy","append","assoc","at","attrib","break","cacls","cd","chcp","chdir","chkdsk","chkntfs","cls","cmd","color","comp","compact","convert","date","dir","diskcomp","diskcopy","doskey","erase","fs","find","findstr","format","ftype","graftabl","help","keyb","label","md","mkdir","mode","more","move","path","pause","print","popd","pushd","promt","rd","recover","rem","rename","replace","restore","rmdir","shift","sort","start","subst","time","title","tree","type","ver","verify","vol","ping","net","ipconfig","taskkill","xcopy","ren","del"]},contains:[{className:"variable",begin:/%%[^ ]|%[^ ]+?%|![^ ]+?!/},{className:"function",begin:"^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)",end:"goto:eof",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),t]},{className:"number",begin:"\\b\\d+",relevance:0},t]}}),vp)),zf.registerLanguage("dsconfig",(Cp||(Cp=1,yp=function(e){return{keywords:"dsconfig",contains:[{className:"keyword",begin:"^dsconfig",end:/\s/,excludeEnd:!0,relevance:10},{className:"built_in",begin:/(list|create|get|set|delete)-(\w+)/,end:/\s/,excludeEnd:!0,illegal:"!@#$%^&*()",relevance:10},{className:"built_in",begin:/--(\w+)/,end:/\s/,excludeEnd:!0},{className:"string",begin:/"/,end:/"/},{className:"string",begin:/'/,end:/'/},{className:"string",begin:/[\w\-?]+:\w+/,end:/\W/,relevance:0},{className:"string",begin:/\w+(\-\w+)*/,end:/(?=\W)/,relevance:0},e.HASH_COMMENT_MODE]}}),yp)),zf.registerLanguage("dts",(Rp||(Rp=1,Np=function(e){const t={className:"string",variants:[e.inherit(e.QUOTE_STRING_MODE,{begin:'((u8?|U)|L)?"'}),{begin:'(u8?|U)?R"',end:'"',contains:[e.BACKSLASH_ESCAPE]},{begin:"'\\\\?.",end:"'",illegal:"."}]},r={className:"number",variants:[{begin:"\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)"},{begin:e.C_NUMBER_RE}],relevance:0},n={className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef ifdef ifndef"},contains:[{begin:/\\\n/,relevance:0},{beginKeywords:"include",end:"$",keywords:{keyword:"include"},contains:[e.inherit(t,{className:"string"}),{className:"string",begin:"<",end:">",illegal:"\\n"}]},t,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},a={className:"variable",begin:/&[a-z\d_]*\b/};return{name:"Device Tree",contains:[{className:"title.class",begin:/^\/(?=\s*\{)/,relevance:10},a,{className:"keyword",begin:"/[a-z][a-z\\d-]*/"},{className:"symbol",begin:"^\\s*[a-zA-Z_][a-zA-Z\\d_]*:"},{className:"title.class",begin:/[a-zA-Z_][a-zA-Z\d_@-]*(?=\s\{)/,relevance:.2},{relevance:0,match:[/[a-z][a-z-,]+/,/\s*/,/=/],scope:{1:"attr",3:"operator"}},{match:/[a-z][a-z-,]+(?=;)/,relevance:0,scope:"attr"},{className:"params",relevance:0,begin:"<",end:">",contains:[r,a]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,r,t,n,{scope:"punctuation",relevance:0,match:/\};|[;{}]/},{begin:e.IDENT_RE+"::",keywords:""}]}}),Np)),zf.registerLanguage("dust",(Op||(Op=1,Ap=function(e){return{name:"Dust",aliases:["dst"],case_insensitive:!0,subLanguage:"xml",contains:[{className:"template-tag",begin:/\{[#\/]/,end:/\}/,illegal:/;/,contains:[{className:"name",begin:/[a-zA-Z\.-]+/,starts:{endsWithParent:!0,relevance:0,contains:[e.QUOTE_STRING_MODE]}}]},{className:"template-variable",begin:/\{/,end:/\}/,illegal:/;/,keywords:"if eq ne lt lte gt gte select default math sep"}]}}),Ap)),zf.registerLanguage("ebnf",(xp||(xp=1,Ip=function(e){const t=e.COMMENT(/\(\*/,/\*\)/);return{name:"Extended Backus-Naur Form",illegal:/\S/,contains:[t,{className:"attribute",begin:/^[ ]*[a-zA-Z]+([\s_-]+[a-zA-Z]+)*/},{begin:/=/,end:/[.;]/,contains:[t,{className:"meta",begin:/\?.*\?/},{className:"string",variants:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{begin:"`",end:"`"}]}]}]}}),Ip)),zf.registerLanguage("elixir",(Dp||(Dp=1,wp=function(e){const t=e.regex,r="[a-zA-Z_][a-zA-Z0-9_.]*(!|\\?)?",n={$pattern:r,keyword:["after","alias","and","case","catch","cond","defstruct","defguard","do","else","end","fn","for","if","import","in","not","or","quote","raise","receive","require","reraise","rescue","try","unless","unquote","unquote_splicing","use","when","with|0"],literal:["false","nil","true"]},a={className:"subst",begin:/#\{/,end:/\}/,keywords:n},i={match:/\\[\s\S]/,scope:"char.escape",relevance:0},o="[/|([{<\"']",s=[{begin:/"/,end:/"/},{begin:/'/,end:/'/},{begin:/\//,end:/\//},{begin:/\|/,end:/\|/},{begin:/\(/,end:/\)/},{begin:/\[/,end:/\]/},{begin:/\{/,end:/\}/},{begin:/</,end:/>/}],l=e=>({scope:"char.escape",begin:t.concat(/\\/,e),relevance:0}),c={className:"string",begin:"~[a-z](?="+o+")",contains:s.map(t=>e.inherit(t,{contains:[l(t.end),i,a]}))},d={className:"string",begin:"~[A-Z](?="+o+")",contains:s.map(t=>e.inherit(t,{contains:[l(t.end)]}))},u={className:"regex",variants:[{begin:"~r(?="+o+")",contains:s.map(r=>e.inherit(r,{end:t.concat(r.end,/[uismxfU]{0,7}/),contains:[l(r.end),i,a]}))},{begin:"~R(?="+o+")",contains:s.map(r=>e.inherit(r,{end:t.concat(r.end,/[uismxfU]{0,7}/),contains:[l(r.end)]}))}]},p={className:"string",contains:[e.BACKSLASH_ESCAPE,a],variants:[{begin:/"""/,end:/"""/},{begin:/'''/,end:/'''/},{begin:/~S"""/,end:/"""/,contains:[]},{begin:/~S"/,end:/"/,contains:[]},{begin:/~S'''/,end:/'''/,contains:[]},{begin:/~S'/,end:/'/,contains:[]},{begin:/'/,end:/'/},{begin:/"/,end:/"/}]},_={className:"function",beginKeywords:"def defp defmacro defmacrop",end:/\B\b/,contains:[e.inherit(e.TITLE_MODE,{begin:r,endsParent:!0})]},m=e.inherit(_,{className:"class",beginKeywords:"defimpl defmodule defprotocol defrecord",end:/\bdo\b|$|;/}),g=[p,u,d,c,e.HASH_COMMENT_MODE,m,_,{begin:"::"},{className:"symbol",begin:":(?![\\s:])",contains:[p,{begin:"[a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?"}],relevance:0},{className:"symbol",begin:r+":(?!:)",relevance:0},{className:"title.class",begin:/(\b[A-Z][a-zA-Z0-9_]+)/,relevance:0},{className:"number",begin:"(\\b0o[0-7_]+)|(\\b0b[01_]+)|(\\b0x[0-9a-fA-F_]+)|(-?\\b[0-9][0-9_]*(\\.[0-9_]+([eE][-+]?[0-9]+)?)?)",relevance:0},{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))"}];return a.contains=g,{name:"Elixir",aliases:["ex","exs"],keywords:n,contains:g}}),wp)),zf.registerLanguage("elm",(kp||(kp=1,Mp=function(e){const t={variants:[e.COMMENT("--","$"),e.COMMENT(/\{-/,/-\}/,{contains:["self"]})]},r={className:"type",begin:"\\b[A-Z][\\w']*",relevance:0},n={begin:"\\(",end:"\\)",illegal:'"',contains:[{className:"type",begin:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},t]};return{name:"Elm",keywords:["let","in","if","then","else","case","of","where","module","import","exposing","type","alias","as","infix","infixl","infixr","port","effect","command","subscription"],contains:[{beginKeywords:"port effect module",end:"exposing",keywords:"port effect module where command subscription exposing",contains:[n,t],illegal:"\\W\\.|;"},{begin:"import",end:"$",keywords:"import as exposing",contains:[n,t],illegal:"\\W\\.|;"},{begin:"type",end:"$",keywords:"type alias",contains:[r,n,{begin:/\{/,end:/\}/,contains:n.contains},t]},{beginKeywords:"infix infixl infixr",end:"$",contains:[e.C_NUMBER_MODE,t]},{begin:"port",end:"$",keywords:"port",contains:[t]},{className:"string",begin:"'\\\\?.",end:"'",illegal:"."},e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,r,e.inherit(e.TITLE_MODE,{begin:"^[_a-z][\\w']*"}),t,{begin:"->|<-"}],illegal:/;/}}),Mp)),zf.registerLanguage("ruby",(Pp||(Pp=1,Lp=function(e){const t=e.regex,r="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",n=t.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),a=t.concat(n,/(::\w+)*/),i={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield","include","extend","prepend","public","private","protected","raise","throw"],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},o={className:"doctag",begin:"@[A-Za-z]+"},s={begin:"#<",end:">"},l=[e.COMMENT("#","$",{contains:[o]}),e.COMMENT("^=begin","^=end",{contains:[o],relevance:10}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],c={className:"subst",begin:/#\{/,end:/\}/,keywords:i},d={className:"string",contains:[e.BACKSLASH_ESCAPE,c],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?</,end:/>/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:t.concat(/<<[-~]?'?/,t.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,c]})]}]},u="[0-9](_?[0-9])*",p={className:"number",relevance:0,variants:[{begin:`\\b([1-9](_?[0-9])*|0)(\\.(${u}))?([eE][+-]?(${u})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},_={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:i}]},m=[d,{variants:[{match:[/class\s+/,a,/\s+<\s+/,a]},{match:[/\b(class|module)\s+/,a]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:i},{match:[/(include|extend)\s+/,a],scope:{2:"title.class"},keywords:i},{relevance:0,match:[a,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:n,scope:"title.class"},{match:[/def/,/\s+/,r],scope:{1:"keyword",3:"title.function"},contains:[_]},{begin:e.IDENT_RE+"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[d,{begin:r}],relevance:0},p,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:i},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,c],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(s,l),relevance:0}].concat(s,l);c.contains=m,_.contains=m;const g=[{begin:/^\s*=>/,starts:{end:"$",contains:m}},{className:"meta.prompt",begin:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]|(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>)(?=[ ])",starts:{end:"$",keywords:i,contains:m}}];return l.unshift(s),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:i,illegal:/\/\*/,contains:[e.SHEBANG({binary:"ruby"})].concat(g).concat(l).concat(m)}}),Lp)),zf.registerLanguage("erb",(Bp||(Bp=1,Fp=function(e){return{name:"ERB",subLanguage:"xml",contains:[e.COMMENT("<%#","%>"),{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0}]}}),Fp)),zf.registerLanguage("erlang-repl",(Gp||(Gp=1,Up=function(e){const t=e.regex;return{name:"Erlang REPL",keywords:{built_in:"spawn spawn_link self",keyword:"after and andalso|10 band begin bnot bor bsl bsr bxor case catch cond div end fun if let not of or orelse|10 query receive rem try when xor"},contains:[{className:"meta.prompt",begin:"^[0-9]+> ",relevance:10},e.COMMENT("%","$"),{className:"number",begin:"\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)",relevance:0},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{begin:t.concat(/\?(::)?/,/([A-Z]\w*)/,/((::)[A-Z]\w*)*/)},{begin:"->"},{begin:"ok"},{begin:"!"},{begin:"(\\b[a-z'][a-zA-Z0-9_']*:[a-z'][a-zA-Z0-9_']*)|(\\b[a-z'][a-zA-Z0-9_']*)",relevance:0},{begin:"[A-Z][a-zA-Z0-9_']*",relevance:0}]}}),Up)),zf.registerLanguage("erlang",(Yp||(Yp=1,zp=function(e){const t="[a-z'][a-zA-Z0-9_']*",r="("+t+":"+t+"|"+t+")",n={keyword:"after and andalso|10 band begin bnot bor bsl bzr bxor case catch cond div end fun if let not of orelse|10 query receive rem try when xor maybe else",literal:"false true"},a=e.COMMENT("%","$"),i={className:"number",begin:"\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)",relevance:0},o={begin:"fun\\s+"+t+"/\\d+"},s={begin:r+"\\(",end:"\\)",returnBegin:!0,relevance:0,contains:[{begin:r,relevance:0},{begin:"\\(",end:"\\)",endsWithParent:!0,returnEnd:!0,relevance:0}]},l={begin:/\{/,end:/\}/,relevance:0},c={begin:"\\b_([A-Z][A-Za-z0-9_]*)?",relevance:0},d={begin:"[A-Z][a-zA-Z0-9_]*",relevance:0},u={begin:"#"+e.UNDERSCORE_IDENT_RE,relevance:0,returnBegin:!0,contains:[{begin:"#"+e.UNDERSCORE_IDENT_RE,relevance:0},{begin:/\{/,end:/\}/,relevance:0}]},p={scope:"string",match:/\$(\\([^0-9]|[0-9]{1,3}|)|.)/},_={scope:"string",match:/"""("*)(?!")[\s\S]*?"""\1/},m={scope:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{match:/~\w?"""("*)(?!")[\s\S]*?"""\1/},{begin:/~\w?\(/,end:/\)/},{begin:/~\w?\[/,end:/\]/},{begin:/~\w?{/,end:/}/},{begin:/~\w?</,end:/>/},{begin:/~\w?\//,end:/\//},{begin:/~\w?\|/,end:/\|/},{begin:/~\w?'/,end:/'/},{begin:/~\w?"/,end:/"/},{begin:/~\w?`/,end:/`/},{begin:/~\w?#/,end:/#/}]},g={beginKeywords:"fun receive if try case maybe",end:"end",keywords:n};g.contains=[a,o,e.inherit(e.APOS_STRING_MODE,{className:""}),g,s,m,_,e.QUOTE_STRING_MODE,i,l,c,d,u,p];const h=[a,o,g,s,m,_,e.QUOTE_STRING_MODE,i,l,c,d,u,p];s.contains[1].contains=h,l.contains=h,u.contains[1].contains=h;const f={className:"params",begin:"\\(",end:"\\)",contains:h};return{name:"Erlang",aliases:["erl"],keywords:n,illegal:"(</|\\*=|\\+=|-=|/\\*|\\*/|\\(\\*|\\*\\))",contains:[{className:"function",begin:"^"+t+"\\s*\\(",end:"->",returnBegin:!0,illegal:"\\(|#|//|/\\*|\\\\|:|;",contains:[f,e.inherit(e.TITLE_MODE,{begin:t})],starts:{end:";|\\.",keywords:n,contains:h}},a,{begin:"^-",end:"\\.",relevance:0,excludeEnd:!0,returnBegin:!0,keywords:{$pattern:"-"+e.IDENT_RE,keyword:["-module","-record","-undef","-export","-ifdef","-ifndef","-author","-copyright","-doc","-moduledoc","-vsn","-import","-include","-include_lib","-compile","-define","-else","-endif","-file","-behaviour","-behavior","-spec","-on_load","-nifs"].map(e=>`${e}|1.5`).join(" ")},contains:[f,m,_,e.QUOTE_STRING_MODE]},i,m,_,e.QUOTE_STRING_MODE,u,c,d,l,p,{begin:/\.$/}]}}),zp)),zf.registerLanguage("excel",(Hp||(Hp=1,qp=function(e){return{name:"Excel formulae",aliases:["xlsx","xls"],case_insensitive:!0,keywords:{$pattern:/[a-zA-Z][\w\.]*/,built_in:["ABS","ACCRINT","ACCRINTM","ACOS","ACOSH","ACOT","ACOTH","AGGREGATE","ADDRESS","AMORDEGRC","AMORLINC","AND","ARABIC","AREAS","ARRAYTOTEXT","ASC","ASIN","ASINH","ATAN","ATAN2","ATANH","AVEDEV","AVERAGE","AVERAGEA","AVERAGEIF","AVERAGEIFS","BAHTTEXT","BASE","BESSELI","BESSELJ","BESSELK","BESSELY","BETADIST","BETA.DIST","BETAINV","BETA.INV","BIN2DEC","BIN2HEX","BIN2OCT","BINOMDIST","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","BYCOL","BYROW","CALL","CEILING","CEILING.MATH","CEILING.PRECISE","CELL","CHAR","CHIDIST","CHIINV","CHITEST","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","CHOOSE","CHOOSECOLS","CHOOSEROWS","CLEAN","CODE","COLUMN","COLUMNS","COMBIN","COMBINA","COMPLEX","CONCAT","CONCATENATE","CONFIDENCE","CONFIDENCE.NORM","CONFIDENCE.T","CONVERT","CORREL","COS","COSH","COT","COTH","COUNT","COUNTA","COUNTBLANK","COUNTIF","COUNTIFS","COUPDAYBS","COUPDAYS","COUPDAYSNC","COUPNCD","COUPNUM","COUPPCD","COVAR","COVARIANCE.P","COVARIANCE.S","CRITBINOM","CSC","CSCH","CUBEKPIMEMBER","CUBEMEMBER","CUBEMEMBERPROPERTY","CUBERANKEDMEMBER","CUBESET","CUBESETCOUNT","CUBEVALUE","CUMIPMT","CUMPRINC","DATE","DATEDIF","DATEVALUE","DAVERAGE","DAY","DAYS","DAYS360","DB","DBCS","DCOUNT","DCOUNTA","DDB","DEC2BIN","DEC2HEX","DEC2OCT","DECIMAL","DEGREES","DELTA","DEVSQ","DGET","DISC","DMAX","DMIN","DOLLAR","DOLLARDE","DOLLARFR","DPRODUCT","DROP","DSTDEV","DSTDEVP","DSUM","DURATION","DVAR","DVARP","EDATE","EFFECT","ENCODEURL","EOMONTH","ERF","ERF.PRECISE","ERFC","ERFC.PRECISE","ERROR.TYPE","EUROCONVERT","EVEN","EXACT","EXP","EXPAND","EXPON.DIST","EXPONDIST","FACT","FACTDOUBLE","FALSE","F.DIST","FDIST","F.DIST.RT","FILTER","FILTERXML","FIND","FINDB","F.INV","F.INV.RT","FINV","FISHER","FISHERINV","FIXED","FLOOR","FLOOR.MATH","FLOOR.PRECISE","FORECAST","FORECAST.ETS","FORECAST.ETS.CONFINT","FORECAST.ETS.SEASONALITY","FORECAST.ETS.STAT","FORECAST.LINEAR","FORMULATEXT","FREQUENCY","F.TEST","FTEST","FV","FVSCHEDULE","GAMMA","GAMMA.DIST","GAMMADIST","GAMMA.INV","GAMMAINV","GAMMALN","GAMMALN.PRECISE","GAUSS","GCD","GEOMEAN","GESTEP","GETPIVOTDATA","GROWTH","HARMEAN","HEX2BIN","HEX2DEC","HEX2OCT","HLOOKUP","HOUR","HSTACK","HYPERLINK","HYPGEOM.DIST","HYPGEOMDIST","IF","IFERROR","IFNA","IFS","IMABS","IMAGE","IMAGINARY","IMARGUMENT","IMCONJUGATE","IMCOS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMDIV","IMEXP","IMLN","IMLOG10","IMLOG2","IMPOWER","IMPRODUCT","IMREAL","IMSEC","IMSECH","IMSIN","IMSINH","IMSQRT","IMSUB","IMSUM","IMTAN","INDEX","INDIRECT","INFO","INT","INTERCEPT","INTRATE","IPMT","IRR","ISBLANK","ISERR","ISERROR","ISEVEN","ISFORMULA","ISLOGICAL","ISNA","ISNONTEXT","ISNUMBER","ISODD","ISOMITTED","ISREF","ISTEXT","ISO.CEILING","ISOWEEKNUM","ISPMT","JIS","KURT","LAMBDA","LARGE","LCM","LEFT","LEFTB","LEN","LENB","LET","LINEST","LN","LOG","LOG10","LOGEST","LOGINV","LOGNORM.DIST","LOGNORMDIST","LOGNORM.INV","LOOKUP","LOWER","MAKEARRAY","MAP","MATCH","MAX","MAXA","MAXIFS","MDETERM","MDURATION","MEDIAN","MID","MIDB","MIN","MINIFS","MINA","MINUTE","MINVERSE","MIRR","MMULT","MOD","MODE","MODE.MULT","MODE.SNGL","MONTH","MROUND","MULTINOMIAL","MUNIT","N","NA","NEGBINOM.DIST","NEGBINOMDIST","NETWORKDAYS","NETWORKDAYS.INTL","NOMINAL","NORM.DIST","NORMDIST","NORMINV","NORM.INV","NORM.S.DIST","NORMSDIST","NORM.S.INV","NORMSINV","NOT","NOW","NPER","NPV","NUMBERVALUE","OCT2BIN","OCT2DEC","OCT2HEX","ODD","ODDFPRICE","ODDFYIELD","ODDLPRICE","ODDLYIELD","OFFSET","OR","PDURATION","PEARSON","PERCENTILE.EXC","PERCENTILE.INC","PERCENTILE","PERCENTRANK.EXC","PERCENTRANK.INC","PERCENTRANK","PERMUT","PERMUTATIONA","PHI","PHONETIC","PI","PMT","POISSON.DIST","POISSON","POWER","PPMT","PRICE","PRICEDISC","PRICEMAT","PROB","PRODUCT","PROPER","PV","QUARTILE","QUARTILE.EXC","QUARTILE.INC","QUOTIENT","RADIANS","RAND","RANDARRAY","RANDBETWEEN","RANK.AVG","RANK.EQ","RANK","RATE","RECEIVED","REDUCE","REGISTER.ID","REPLACE","REPLACEB","REPT","RIGHT","RIGHTB","ROMAN","ROUND","ROUNDDOWN","ROUNDUP","ROW","ROWS","RRI","RSQ","RTD","SCAN","SEARCH","SEARCHB","SEC","SECH","SECOND","SEQUENCE","SERIESSUM","SHEET","SHEETS","SIGN","SIN","SINH","SKEW","SKEW.P","SLN","SLOPE","SMALL","SORT","SORTBY","SQRT","SQRTPI","SQL.REQUEST","STANDARDIZE","STOCKHISTORY","STDEV","STDEV.P","STDEV.S","STDEVA","STDEVP","STDEVPA","STEYX","SUBSTITUTE","SUBTOTAL","SUM","SUMIF","SUMIFS","SUMPRODUCT","SUMSQ","SUMX2MY2","SUMX2PY2","SUMXMY2","SWITCH","SYD","T","TAN","TANH","TAKE","TBILLEQ","TBILLPRICE","TBILLYIELD","T.DIST","T.DIST.2T","T.DIST.RT","TDIST","TEXT","TEXTAFTER","TEXTBEFORE","TEXTJOIN","TEXTSPLIT","TIME","TIMEVALUE","T.INV","T.INV.2T","TINV","TOCOL","TOROW","TODAY","TRANSPOSE","TREND","TRIM","TRIMMEAN","TRUE","TRUNC","T.TEST","TTEST","TYPE","UNICHAR","UNICODE","UNIQUE","UPPER","VALUE","VALUETOTEXT","VAR","VAR.P","VAR.S","VARA","VARP","VARPA","VDB","VLOOKUP","VSTACK","WEBSERVICE","WEEKDAY","WEEKNUM","WEIBULL","WEIBULL.DIST","WORKDAY","WORKDAY.INTL","WRAPCOLS","WRAPROWS","XIRR","XLOOKUP","XMATCH","XNPV","XOR","YEAR","YEARFRAC","YIELD","YIELDDISC","YIELDMAT","Z.TEST","ZTEST"]},contains:[{begin:/^=/,end:/[^=]/,returnEnd:!0,illegal:/=/,relevance:10},{className:"symbol",begin:/\b[A-Z]{1,2}\d+\b/,end:/[^\d]/,excludeEnd:!0,relevance:0},{className:"symbol",begin:/[A-Z]{0,2}\d*:[A-Z]{0,2}\d*/,relevance:0},e.BACKSLASH_ESCAPE,e.QUOTE_STRING_MODE,{className:"number",begin:e.NUMBER_RE+"(%)?",relevance:0},e.COMMENT(/\bN\(/,/\)/,{excludeBegin:!0,excludeEnd:!0,illegal:/\n/})]}}),qp)),zf.registerLanguage("fix",$p?Vp:($p=1,Vp=function(e){return{name:"FIX",contains:[{begin:/[^\u2401\u0001]+/,end:/[\u2401\u0001]/,excludeEnd:!0,returnBegin:!0,returnEnd:!1,contains:[{begin:/([^\u2401\u0001=]+)/,end:/=([^\u2401\u0001=]+)/,returnEnd:!0,returnBegin:!1,className:"attr"},{begin:/=/,end:/([\u2401\u0001])/,excludeEnd:!0,excludeBegin:!0,className:"string"}]}],case_insensitive:!0}})),zf.registerLanguage("flix",(jp||(jp=1,Wp=function(e){const t={className:"function",beginKeywords:"def",end:/[:={\[(\n;]/,excludeEnd:!0,contains:[{className:"title",relevance:0,begin:/[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/}]};return{name:"Flix",keywords:{keyword:["case","class","def","else","enum","if","impl","import","in","lat","rel","index","let","match","namespace","switch","type","yield","with"],literal:["true","false"]},contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"string",begin:/'(.|\\[xXuU][a-zA-Z0-9]+)'/},{className:"string",variants:[{begin:'"',end:'"'}]},t,e.C_NUMBER_MODE]}}),Wp)),zf.registerLanguage("fortran",(Kp||(Kp=1,Qp=function(e){const t=e.regex,r={variants:[e.COMMENT("!","$",{relevance:0}),e.COMMENT("^C[ ]","$",{relevance:0}),e.COMMENT("^C$","$",{relevance:0})]},n=/(_[a-z_\d]+)?/,a=/([de][+-]?\d+)?/,i={className:"number",variants:[{begin:t.concat(/\b\d+/,/\.(\d*)/,a,n)},{begin:t.concat(/\b\d+/,a,n)},{begin:t.concat(/\.\d+/,a,n)}],relevance:0},o={className:"function",beginKeywords:"subroutine function program",illegal:"[${=\\n]",contains:[e.UNDERSCORE_TITLE_MODE,{className:"params",begin:"\\(",end:"\\)"}]};return{name:"Fortran",case_insensitive:!0,aliases:["f90","f95"],keywords:{$pattern:/\b[a-z][a-z0-9_]+\b|\.[a-z][a-z0-9_]+\./,keyword:["kind","do","concurrent","local","shared","while","private","call","intrinsic","where","elsewhere","type","endtype","endmodule","endselect","endinterface","end","enddo","endif","if","forall","endforall","only","contains","default","return","stop","then","block","endblock","endassociate","public","subroutine|10","function","program",".and.",".or.",".not.",".le.",".eq.",".ge.",".gt.",".lt.","goto","save","else","use","module","select","case","access","blank","direct","exist","file","fmt","form","formatted","iostat","name","named","nextrec","number","opened","rec","recl","sequential","status","unformatted","unit","continue","format","pause","cycle","exit","c_null_char","c_alert","c_backspace","c_form_feed","flush","wait","decimal","round","iomsg","synchronous","nopass","non_overridable","pass","protected","volatile","abstract","extends","import","non_intrinsic","value","deferred","generic","final","enumerator","class","associate","bind","enum","c_int","c_short","c_long","c_long_long","c_signed_char","c_size_t","c_int8_t","c_int16_t","c_int32_t","c_int64_t","c_int_least8_t","c_int_least16_t","c_int_least32_t","c_int_least64_t","c_int_fast8_t","c_int_fast16_t","c_int_fast32_t","c_int_fast64_t","c_intmax_t","C_intptr_t","c_float","c_double","c_long_double","c_float_complex","c_double_complex","c_long_double_complex","c_bool","c_char","c_null_ptr","c_null_funptr","c_new_line","c_carriage_return","c_horizontal_tab","c_vertical_tab","iso_c_binding","c_loc","c_funloc","c_associated","c_f_pointer","c_ptr","c_funptr","iso_fortran_env","character_storage_size","error_unit","file_storage_size","input_unit","iostat_end","iostat_eor","numeric_storage_size","output_unit","c_f_procpointer","ieee_arithmetic","ieee_support_underflow_control","ieee_get_underflow_mode","ieee_set_underflow_mode","newunit","contiguous","recursive","pad","position","action","delim","readwrite","eor","advance","nml","interface","procedure","namelist","include","sequence","elemental","pure","impure","integer","real","character","complex","logical","codimension","dimension","allocatable|10","parameter","external","implicit|10","none","double","precision","assign","intent","optional","pointer","target","in","out","common","equivalence","data"],literal:[".False.",".True."],built_in:["alog","alog10","amax0","amax1","amin0","amin1","amod","cabs","ccos","cexp","clog","csin","csqrt","dabs","dacos","dasin","datan","datan2","dcos","dcosh","ddim","dexp","dint","dlog","dlog10","dmax1","dmin1","dmod","dnint","dsign","dsin","dsinh","dsqrt","dtan","dtanh","float","iabs","idim","idint","idnint","ifix","isign","max0","max1","min0","min1","sngl","algama","cdabs","cdcos","cdexp","cdlog","cdsin","cdsqrt","cqabs","cqcos","cqexp","cqlog","cqsin","cqsqrt","dcmplx","dconjg","derf","derfc","dfloat","dgamma","dimag","dlgama","iqint","qabs","qacos","qasin","qatan","qatan2","qcmplx","qconjg","qcos","qcosh","qdim","qerf","qerfc","qexp","qgamma","qimag","qlgama","qlog","qlog10","qmax1","qmin1","qmod","qnint","qsign","qsin","qsinh","qsqrt","qtan","qtanh","abs","acos","aimag","aint","anint","asin","atan","atan2","char","cmplx","conjg","cos","cosh","exp","ichar","index","int","log","log10","max","min","nint","sign","sin","sinh","sqrt","tan","tanh","print","write","dim","lge","lgt","lle","llt","mod","nullify","allocate","deallocate","adjustl","adjustr","all","allocated","any","associated","bit_size","btest","ceiling","count","cshift","date_and_time","digits","dot_product","eoshift","epsilon","exponent","floor","fraction","huge","iand","ibclr","ibits","ibset","ieor","ior","ishft","ishftc","lbound","len_trim","matmul","maxexponent","maxloc","maxval","merge","minexponent","minloc","minval","modulo","mvbits","nearest","pack","present","product","radix","random_number","random_seed","range","repeat","reshape","rrspacing","scale","scan","selected_int_kind","selected_real_kind","set_exponent","shape","size","spacing","spread","sum","system_clock","tiny","transpose","trim","ubound","unpack","verify","achar","iachar","transfer","dble","entry","dprod","cpu_time","command_argument_count","get_command","get_command_argument","get_environment_variable","is_iostat_end","ieee_arithmetic","ieee_support_underflow_control","ieee_get_underflow_mode","ieee_set_underflow_mode","is_iostat_eor","move_alloc","new_line","selected_char_kind","same_type_as","extends_type_of","acosh","asinh","atanh","bessel_j0","bessel_j1","bessel_jn","bessel_y0","bessel_y1","bessel_yn","erf","erfc","erfc_scaled","gamma","log_gamma","hypot","norm2","atomic_define","atomic_ref","execute_command_line","leadz","trailz","storage_size","merge_bits","bge","bgt","ble","blt","dshiftl","dshiftr","findloc","iall","iany","iparity","image_index","lcobound","ucobound","maskl","maskr","num_images","parity","popcnt","poppar","shifta","shiftl","shiftr","this_image","sync","change","team","co_broadcast","co_max","co_min","co_sum","co_reduce"]},illegal:/\/\*/,contains:[{className:"string",relevance:0,variants:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},o,{begin:/^C\s*=(?!=)/,relevance:0},r,i]}}),Qp)),zf.registerLanguage("fsharp",function(){if(Zp)return Xp;function e(e){return new RegExp(e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}function t(e){return e?"string"==typeof e?e:e.source:null}function r(e){return n("(?=",e,")")}function n(...e){return e.map(e=>t(e)).join("")}function a(...e){const r=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(r.capture?"":"?:")+e.map(e=>t(e)).join("|")+")"}return Zp=1,Xp=function(t){const i={scope:"keyword",match:/\b(yield|return|let|do|match|use)!/},o=["bool","byte","sbyte","int8","int16","int32","uint8","uint16","uint32","int","uint","int64","uint64","nativeint","unativeint","decimal","float","double","float32","single","char","string","unit","bigint","option","voption","list","array","seq","byref","exn","inref","nativeptr","obj","outref","voidptr","Result"],s={keyword:["abstract","and","as","assert","base","begin","class","default","delegate","do","done","downcast","downto","elif","else","end","exception","extern","finally","fixed","for","fun","function","global","if","in","inherit","inline","interface","internal","lazy","let","match","member","module","mutable","namespace","new","of","open","or","override","private","public","rec","return","static","struct","then","to","try","type","upcast","use","val","void","when","while","with","yield"],literal:["true","false","null","Some","None","Ok","Error","infinity","infinityf","nan","nanf"],built_in:["not","ref","raise","reraise","dict","readOnlyDict","set","get","enum","sizeof","typeof","typedefof","nameof","nullArg","invalidArg","invalidOp","id","fst","snd","ignore","lock","using","box","unbox","tryUnbox","printf","printfn","sprintf","eprintf","eprintfn","fprintf","fprintfn","failwith","failwithf"],"variable.constant":["__LINE__","__SOURCE_DIRECTORY__","__SOURCE_FILE__"]},l={variants:[t.COMMENT(/\(\*(?!\))/,/\*\)/,{contains:["self"]}),t.C_LINE_COMMENT_MODE]},c={scope:"variable",begin:/``/,end:/``/},d=/\B('|\^)/,u={scope:"symbol",variants:[{match:n(d,/``.*?``/)},{match:n(d,t.UNDERSCORE_IDENT_RE)}],relevance:0},p=function({includeEqual:t}){let i;i=t?"!%&*+-/<=>@^|~?":"!%&*+-/<>@^|~?";const o=n("[",...Array.from(i).map(e),"]"),s=a(o,/\./),l=n(s,r(s)),c=a(n(l,s,"*"),n(o,"+"));return{scope:"operator",match:a(c,/:\?>/,/:\?/,/:>/,/:=/,/::?/,/\$/),relevance:0}},_=p({includeEqual:!0}),m=p({includeEqual:!1}),g=function(e,i){return{begin:n(e,r(n(/\s*/,a(/\w/,/'/,/\^/,/#/,/``/,/\(/,/{\|/)))),beginScope:i,end:r(a(/\n/,/=/)),relevance:0,keywords:t.inherit(s,{type:o}),contains:[l,u,t.inherit(c,{scope:null}),m]}},h=g(/:/,"operator"),f=g(/\bof\b/,"keyword"),E={begin:[/(^|\s+)/,/type/,/\s+/,/[a-zA-Z_](\w|')*/],beginScope:{2:"keyword",4:"title.class"},end:r(/\(|=|$/),keywords:s,contains:[l,t.inherit(c,{scope:null}),u,{scope:"operator",match:/<|>/},h]},b={scope:"computation-expression",match:/\b[_a-z]\w*(?=\s*\{)/},S={begin:[/^\s*/,n(/#/,a("if","else","endif","line","nowarn","light","r","i","I","load","time","help","quit")),/\b/],beginScope:{2:"meta"},end:r(/\s|$/)},v={variants:[t.BINARY_NUMBER_MODE,t.C_NUMBER_MODE]},T={scope:"string",begin:/"/,end:/"/,contains:[t.BACKSLASH_ESCAPE]},y={scope:"string",begin:/@"/,end:/"/,contains:[{match:/""/},t.BACKSLASH_ESCAPE]},C={scope:"string",begin:/"""/,end:/"""/,relevance:2},N={scope:"subst",begin:/\{/,end:/\}/,keywords:s},R={scope:"string",begin:/\$"/,end:/"/,contains:[{match:/\{\{/},{match:/\}\}/},t.BACKSLASH_ESCAPE,N]},A={scope:"string",begin:/(\$@|@\$)"/,end:/"/,contains:[{match:/\{\{/},{match:/\}\}/},{match:/""/},t.BACKSLASH_ESCAPE,N]},O={scope:"string",begin:/\$"""/,end:/"""/,contains:[{match:/\{\{/},{match:/\}\}/},N],relevance:2},I={scope:"string",match:n(/'/,a(/[^\\']/,/\\(?:.|\d{3}|x[a-fA-F\d]{2}|u[a-fA-F\d]{4}|U[a-fA-F\d]{8})/),/'/)};return N.contains=[A,R,y,T,I,i,l,c,h,b,S,v,u,_],{name:"F#",aliases:["fs","f#"],keywords:s,illegal:/\/\*/,classNameAliases:{"computation-expression":"keyword"},contains:[i,{variants:[O,A,R,C,y,T,I]},l,c,E,{scope:"meta",begin:/\[</,end:/>\]/,relevance:2,contains:[c,C,y,T,I,v]},f,h,b,S,v,u,_]}},Xp}()),zf.registerLanguage("gams",(e_||(e_=1,Jp=function(e){const t=e.regex,r={keyword:"abort acronym acronyms alias all and assign binary card diag display else eq file files for free ge gt if integer le loop lt maximizing minimizing model models ne negative no not option options or ord positive prod put putpage puttl repeat sameas semicont semiint smax smin solve sos1 sos2 sum system table then until using while xor yes",literal:"eps inf na",built_in:"abs arccos arcsin arctan arctan2 Beta betaReg binomial ceil centropy cos cosh cvPower div div0 eDist entropy errorf execSeed exp fact floor frac gamma gammaReg log logBeta logGamma log10 log2 mapVal max min mod ncpCM ncpF ncpVUpow ncpVUsin normal pi poly power randBinomial randLinear randTriangle round rPower sigmoid sign signPower sin sinh slexp sllog10 slrec sqexp sqlog10 sqr sqrec sqrt tan tanh trunc uniform uniformInt vcPower bool_and bool_eqv bool_imp bool_not bool_or bool_xor ifThen rel_eq rel_ge rel_gt rel_le rel_lt rel_ne gday gdow ghour gleap gmillisec gminute gmonth gsecond gyear jdate jnow jstart jtime errorLevel execError gamsRelease gamsVersion handleCollect handleDelete handleStatus handleSubmit heapFree heapLimit heapSize jobHandle jobKill jobStatus jobTerminate licenseLevel licenseStatus maxExecError sleep timeClose timeComp timeElapsed timeExec timeStart"},n={className:"symbol",variants:[{begin:/=[lgenxc]=/},{begin:/\$/}]},a={className:"comment",variants:[{begin:"'",end:"'"},{begin:'"',end:'"'}],illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},i={begin:"/",end:"/",keywords:r,contains:[a,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,e.C_NUMBER_MODE]},o=/[a-z0-9&#*=?@\\><:,()$[\]_.{}!+%^-]+/,s={begin:/[a-z][a-z0-9_]*(\([a-z0-9_, ]*\))?[ \t]+/,excludeBegin:!0,end:"$",endsWithParent:!0,contains:[a,i,{className:"comment",begin:t.concat(o,t.anyNumberOfTimes(t.concat(/[ ]+/,o))),relevance:0}]};return{name:"GAMS",aliases:["gms"],case_insensitive:!0,keywords:r,contains:[e.COMMENT(/^\$ontext/,/^\$offtext/),{className:"meta",begin:"^\\$[a-z0-9]+",end:"$",returnBegin:!0,contains:[{className:"keyword",begin:"^\\$[a-z0-9]+"}]},e.COMMENT("^\\*","$"),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{beginKeywords:"set sets parameter parameters variable variables scalar scalars equation equations",end:";",contains:[e.COMMENT("^\\*","$"),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,i,s]},{beginKeywords:"table",end:";",returnBegin:!0,contains:[{beginKeywords:"table",end:"$",contains:[s]},e.COMMENT("^\\*","$"),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,e.C_NUMBER_MODE]},{className:"function",begin:/^[a-z][a-z0-9_,\-+' ()$]+\.{2}/,returnBegin:!0,contains:[{className:"title",begin:/^[a-z0-9_]+/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0},n]},e.C_NUMBER_MODE,n]}}),Jp)),zf.registerLanguage("gauss",(r_||(r_=1,t_=function(e){const t={keyword:"bool break call callexe checkinterrupt clear clearg closeall cls comlog compile continue create debug declare delete disable dlibrary dllcall do dos ed edit else elseif enable end endfor endif endp endo errorlog errorlogat expr external fn for format goto gosub graph if keyword let lib library line load loadarray loadexe loadf loadk loadm loadp loads loadx local locate loopnextindex lprint lpwidth lshow matrix msym ndpclex new open output outwidth plot plotsym pop prcsn print printdos proc push retp return rndcon rndmod rndmult rndseed run save saveall screen scroll setarray show sparse stop string struct system trace trap threadfor threadendfor threadbegin threadjoin threadstat threadend until use while winprint ne ge le gt lt and xor or not eq eqv",built_in:"abs acf aconcat aeye amax amean AmericanBinomCall AmericanBinomCall_Greeks AmericanBinomCall_ImpVol AmericanBinomPut AmericanBinomPut_Greeks AmericanBinomPut_ImpVol AmericanBSCall AmericanBSCall_Greeks AmericanBSCall_ImpVol AmericanBSPut AmericanBSPut_Greeks AmericanBSPut_ImpVol amin amult annotationGetDefaults annotationSetBkd annotationSetFont annotationSetLineColor annotationSetLineStyle annotationSetLineThickness annualTradingDays arccos arcsin areshape arrayalloc arrayindex arrayinit arraytomat asciiload asclabel astd astds asum atan atan2 atranspose axmargin balance band bandchol bandcholsol bandltsol bandrv bandsolpd bar base10 begwind besselj bessely beta box boxcox cdfBeta cdfBetaInv cdfBinomial cdfBinomialInv cdfBvn cdfBvn2 cdfBvn2e cdfCauchy cdfCauchyInv cdfChic cdfChii cdfChinc cdfChincInv cdfExp cdfExpInv cdfFc cdfFnc cdfFncInv cdfGam cdfGenPareto cdfHyperGeo cdfLaplace cdfLaplaceInv cdfLogistic cdfLogisticInv cdfmControlCreate cdfMvn cdfMvn2e cdfMvnce cdfMvne cdfMvt2e cdfMvtce cdfMvte cdfN cdfN2 cdfNc cdfNegBinomial cdfNegBinomialInv cdfNi cdfPoisson cdfPoissonInv cdfRayleigh cdfRayleighInv cdfTc cdfTci cdfTnc cdfTvn cdfWeibull cdfWeibullInv cdir ceil ChangeDir chdir chiBarSquare chol choldn cholsol cholup chrs close code cols colsf combinate combinated complex con cond conj cons ConScore contour conv convertsatostr convertstrtosa corrm corrms corrvc corrx corrxs cos cosh counts countwts crossprd crout croutp csrcol csrlin csvReadM csvReadSA cumprodc cumsumc curve cvtos datacreate datacreatecomplex datalist dataload dataloop dataopen datasave date datestr datestring datestrymd dayinyr dayofweek dbAddDatabase dbClose dbCommit dbCreateQuery dbExecQuery dbGetConnectOptions dbGetDatabaseName dbGetDriverName dbGetDrivers dbGetHostName dbGetLastErrorNum dbGetLastErrorText dbGetNumericalPrecPolicy dbGetPassword dbGetPort dbGetTableHeaders dbGetTables dbGetUserName dbHasFeature dbIsDriverAvailable dbIsOpen dbIsOpenError dbOpen dbQueryBindValue dbQueryClear dbQueryCols dbQueryExecPrepared dbQueryFetchAllM dbQueryFetchAllSA dbQueryFetchOneM dbQueryFetchOneSA dbQueryFinish dbQueryGetBoundValue dbQueryGetBoundValues dbQueryGetField dbQueryGetLastErrorNum dbQueryGetLastErrorText dbQueryGetLastInsertID dbQueryGetLastQuery dbQueryGetPosition dbQueryIsActive dbQueryIsForwardOnly dbQueryIsNull dbQueryIsSelect dbQueryIsValid dbQueryPrepare dbQueryRows dbQuerySeek dbQuerySeekFirst dbQuerySeekLast dbQuerySeekNext dbQuerySeekPrevious dbQuerySetForwardOnly dbRemoveDatabase dbRollback dbSetConnectOptions dbSetDatabaseName dbSetHostName dbSetNumericalPrecPolicy dbSetPort dbSetUserName dbTransaction DeleteFile delif delrows denseToSp denseToSpRE denToZero design det detl dfft dffti diag diagrv digamma doswin DOSWinCloseall DOSWinOpen dotfeq dotfeqmt dotfge dotfgemt dotfgt dotfgtmt dotfle dotflemt dotflt dotfltmt dotfne dotfnemt draw drop dsCreate dstat dstatmt dstatmtControlCreate dtdate dtday dttime dttodtv dttostr dttoutc dtvnormal dtvtodt dtvtoutc dummy dummybr dummydn eig eigh eighv eigv elapsedTradingDays endwind envget eof eqSolve eqSolvemt eqSolvemtControlCreate eqSolvemtOutCreate eqSolveset erf erfc erfccplx erfcplx error etdays ethsec etstr EuropeanBinomCall EuropeanBinomCall_Greeks EuropeanBinomCall_ImpVol EuropeanBinomPut EuropeanBinomPut_Greeks EuropeanBinomPut_ImpVol EuropeanBSCall EuropeanBSCall_Greeks EuropeanBSCall_ImpVol EuropeanBSPut EuropeanBSPut_Greeks EuropeanBSPut_ImpVol exctsmpl exec execbg exp extern eye fcheckerr fclearerr feq feqmt fflush fft ffti fftm fftmi fftn fge fgemt fgets fgetsa fgetsat fgetst fgt fgtmt fileinfo filesa fle flemt floor flt fltmt fmod fne fnemt fonts fopen formatcv formatnv fputs fputst fseek fstrerror ftell ftocv ftos ftostrC gamma gammacplx gammaii gausset gdaAppend gdaCreate gdaDStat gdaDStatMat gdaGetIndex gdaGetName gdaGetNames gdaGetOrders gdaGetType gdaGetTypes gdaGetVarInfo gdaIsCplx gdaLoad gdaPack gdaRead gdaReadByIndex gdaReadSome gdaReadSparse gdaReadStruct gdaReportVarInfo gdaSave gdaUpdate gdaUpdateAndPack gdaVars gdaWrite gdaWrite32 gdaWriteSome getarray getdims getf getGAUSShome getmatrix getmatrix4D getname getnamef getNextTradingDay getNextWeekDay getnr getorders getpath getPreviousTradingDay getPreviousWeekDay getRow getscalar3D getscalar4D getTrRow getwind glm gradcplx gradMT gradMTm gradMTT gradMTTm gradp graphprt graphset hasimag header headermt hess hessMT hessMTg hessMTgw hessMTm hessMTmw hessMTT hessMTTg hessMTTgw hessMTTm hessMTw hessp hist histf histp hsec imag indcv indexcat indices indices2 indicesf indicesfn indnv indsav integrate1d integrateControlCreate intgrat2 intgrat3 inthp1 inthp2 inthp3 inthp4 inthpControlCreate intquad1 intquad2 intquad3 intrleav intrleavsa intrsect intsimp inv invpd invswp iscplx iscplxf isden isinfnanmiss ismiss key keyav keyw lag lag1 lagn lapEighb lapEighi lapEighvb lapEighvi lapgEig lapgEigh lapgEighv lapgEigv lapgSchur lapgSvdcst lapgSvds lapgSvdst lapSvdcusv lapSvds lapSvdusv ldlp ldlsol linSolve listwise ln lncdfbvn lncdfbvn2 lncdfmvn lncdfn lncdfn2 lncdfnc lnfact lngammacplx lnpdfmvn lnpdfmvt lnpdfn lnpdft loadd loadstruct loadwind loess loessmt loessmtControlCreate log loglog logx logy lower lowmat lowmat1 ltrisol lu lusol machEpsilon make makevars makewind margin matalloc matinit mattoarray maxbytes maxc maxindc maxv maxvec mbesselei mbesselei0 mbesselei1 mbesseli mbesseli0 mbesseli1 meanc median mergeby mergevar minc minindc minv miss missex missrv moment momentd movingave movingaveExpwgt movingaveWgt nextindex nextn nextnevn nextwind ntos null null1 numCombinations ols olsmt olsmtControlCreate olsqr olsqr2 olsqrmt ones optn optnevn orth outtyp pacf packedToSp packr parse pause pdfCauchy pdfChi pdfExp pdfGenPareto pdfHyperGeo pdfLaplace pdfLogistic pdfn pdfPoisson pdfRayleigh pdfWeibull pi pinv pinvmt plotAddArrow plotAddBar plotAddBox plotAddHist plotAddHistF plotAddHistP plotAddPolar plotAddScatter plotAddShape plotAddTextbox plotAddTS plotAddXY plotArea plotBar plotBox plotClearLayout plotContour plotCustomLayout plotGetDefaults plotHist plotHistF plotHistP plotLayout plotLogLog plotLogX plotLogY plotOpenWindow plotPolar plotSave plotScatter plotSetAxesPen plotSetBar plotSetBarFill plotSetBarStacked plotSetBkdColor plotSetFill plotSetGrid plotSetLegend plotSetLineColor plotSetLineStyle plotSetLineSymbol plotSetLineThickness plotSetNewWindow plotSetTitle plotSetWhichYAxis plotSetXAxisShow plotSetXLabel plotSetXRange plotSetXTicInterval plotSetXTicLabel plotSetYAxisShow plotSetYLabel plotSetYRange plotSetZAxisShow plotSetZLabel plotSurface plotTS plotXY polar polychar polyeval polygamma polyint polymake polymat polymroot polymult polyroot pqgwin previousindex princomp printfm printfmt prodc psi putarray putf putvals pvCreate pvGetIndex pvGetParNames pvGetParVector pvLength pvList pvPack pvPacki pvPackm pvPackmi pvPacks pvPacksi pvPacksm pvPacksmi pvPutParVector pvTest pvUnpack QNewton QNewtonmt QNewtonmtControlCreate QNewtonmtOutCreate QNewtonSet QProg QProgmt QProgmtInCreate qqr qqre qqrep qr qre qrep qrsol qrtsol qtyr qtyre qtyrep quantile quantiled qyr qyre qyrep qz rank rankindx readr real reclassify reclassifyCuts recode recserar recsercp recserrc rerun rescale reshape rets rev rfft rffti rfftip rfftn rfftnp rfftp rndBernoulli rndBeta rndBinomial rndCauchy rndChiSquare rndCon rndCreateState rndExp rndGamma rndGeo rndGumbel rndHyperGeo rndi rndKMbeta rndKMgam rndKMi rndKMn rndKMnb rndKMp rndKMu rndKMvm rndLaplace rndLCbeta rndLCgam rndLCi rndLCn rndLCnb rndLCp rndLCu rndLCvm rndLogNorm rndMTu rndMVn rndMVt rndn rndnb rndNegBinomial rndp rndPoisson rndRayleigh rndStateSkip rndu rndvm rndWeibull rndWishart rotater round rows rowsf rref sampleData satostrC saved saveStruct savewind scale scale3d scalerr scalinfnanmiss scalmiss schtoc schur searchsourcepath seekr select selif seqa seqm setdif setdifsa setvars setvwrmode setwind shell shiftr sin singleindex sinh sleep solpd sortc sortcc sortd sorthc sorthcc sortind sortindc sortmc sortr sortrc spBiconjGradSol spChol spConjGradSol spCreate spDenseSubmat spDiagRvMat spEigv spEye spLDL spline spLU spNumNZE spOnes spreadSheetReadM spreadSheetReadSA spreadSheetWrite spScale spSubmat spToDense spTrTDense spTScalar spZeros sqpSolve sqpSolveMT sqpSolveMTControlCreate sqpSolveMTlagrangeCreate sqpSolveMToutCreate sqpSolveSet sqrt statements stdc stdsc stocv stof strcombine strindx strlen strput strrindx strsect strsplit strsplitPad strtodt strtof strtofcplx strtriml strtrimr strtrunc strtruncl strtruncpad strtruncr submat subscat substute subvec sumc sumr surface svd svd1 svd2 svdcusv svds svdusv sysstate tab tan tanh tempname time timedt timestr timeutc title tkf2eps tkf2ps tocart todaydt toeplitz token topolar trapchk trigamma trimr trunc type typecv typef union unionsa uniqindx uniqindxsa unique uniquesa upmat upmat1 upper utctodt utctodtv utrisol vals varCovMS varCovXS varget vargetl varmall varmares varput varputl vartypef vcm vcms vcx vcxs vec vech vecr vector vget view viewxyz vlist vnamecv volume vput vread vtypecv wait waitc walkindex where window writer xlabel xlsGetSheetCount xlsGetSheetSize xlsGetSheetTypes xlsMakeRange xlsReadM xlsReadSA xlsWrite xlsWriteM xlsWriteSA xpnd xtics xy xyz ylabel ytics zeros zeta zlabel ztics cdfEmpirical dot h5create h5open h5read h5readAttribute h5write h5writeAttribute ldl plotAddErrorBar plotAddSurface plotCDFEmpirical plotSetColormap plotSetContourLabels plotSetLegendFont plotSetTextInterpreter plotSetXTicCount plotSetYTicCount plotSetZLevels powerm strjoin sylvester strtrim",literal:"DB_AFTER_LAST_ROW DB_ALL_TABLES DB_BATCH_OPERATIONS DB_BEFORE_FIRST_ROW DB_BLOB DB_EVENT_NOTIFICATIONS DB_FINISH_QUERY DB_HIGH_PRECISION DB_LAST_INSERT_ID DB_LOW_PRECISION_DOUBLE DB_LOW_PRECISION_INT32 DB_LOW_PRECISION_INT64 DB_LOW_PRECISION_NUMBERS DB_MULTIPLE_RESULT_SETS DB_NAMED_PLACEHOLDERS DB_POSITIONAL_PLACEHOLDERS DB_PREPARED_QUERIES DB_QUERY_SIZE DB_SIMPLE_LOCKING DB_SYSTEM_TABLES DB_TABLES DB_TRANSACTIONS DB_UNICODE DB_VIEWS __STDIN __STDOUT __STDERR __FILE_DIR"},r=e.COMMENT("@","@"),n={className:"meta",begin:"#",end:"$",keywords:{keyword:"define definecs|10 undef ifdef ifndef iflight ifdllcall ifmac ifos2win ifunix else endif lineson linesoff srcfile srcline"},contains:[{begin:/\\\n/,relevance:0},{beginKeywords:"include",end:"$",keywords:{keyword:"include"},contains:[{className:"string",begin:'"',end:'"',illegal:"\\n"}]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,r]},a={begin:/\bstruct\s+/,end:/\s/,keywords:"struct",contains:[{className:"type",begin:e.UNDERSCORE_IDENT_RE,relevance:0}]},i=[{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,endsWithParent:!0,relevance:0,contains:[{className:"literal",begin:/\.\.\./},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,r,a]}],o={className:"title",begin:e.UNDERSCORE_IDENT_RE,relevance:0},s=function(t,n,a){const s=e.inherit({className:"function",beginKeywords:t,end:n,excludeEnd:!0,contains:[].concat(i)},{});return s.contains.push(o),s.contains.push(e.C_NUMBER_MODE),s.contains.push(e.C_BLOCK_COMMENT_MODE),s.contains.push(r),s},l={className:"built_in",begin:"\\b("+t.built_in.split(" ").join("|")+")\\b"},c={className:"string",begin:'"',end:'"',contains:[e.BACKSLASH_ESCAPE],relevance:0},d={begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,keywords:t,relevance:0,contains:[{beginKeywords:t.keyword},l,{className:"built_in",begin:e.UNDERSCORE_IDENT_RE,relevance:0}]},u={begin:/\(/,end:/\)/,relevance:0,keywords:{built_in:t.built_in,literal:t.literal},contains:[e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,r,l,d,c,"self"]};return d.contains.push(u),{name:"GAUSS",aliases:["gss"],case_insensitive:!0,keywords:t,illegal:/(\{[%#]|[%#]\}| <- )/,contains:[e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,r,c,n,{className:"keyword",begin:/\bexternal (matrix|string|array|sparse matrix|struct|proc|keyword|fn)/},s("proc keyword",";"),s("fn","="),{beginKeywords:"for threadfor",end:/;/,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE,r,u]},{variants:[{begin:e.UNDERSCORE_IDENT_RE+"\\."+e.UNDERSCORE_IDENT_RE},{begin:e.UNDERSCORE_IDENT_RE+"\\s*="}],relevance:0},d,a]}}),t_)),zf.registerLanguage("gcode",(a_||(a_=1,n_=function(e){const t=e.regex,r=/\b/;function n(e,t){if(0===e.index)return;const r=e.input[e.index-1];r>="0"&&r<="9"||"_"!==r&&t.ignoreMatch()}const a=/[+-]?((\.\d+)|(\d+)(\.\d*)?)/,i=/[GM]\s*\d+(\.\d+)?/,o=/T\s*\d+/,s=/O\s*\d+/,l=/O<.+>/,c=/[ABCUVWXYZ]\s*/,d=/[FHIJKPQRS]\s*/;return{name:"G-code (ISO 6983)",aliases:["nc"],case_insensitive:!0,disableAutodetect:!0,keywords:{$pattern:/[A-Z]+|%/,keyword:["THEN","ELSE","ENDIF","IF","GOTO","DO","WHILE","WH","END","CALL","SUB","ENDSUB","EQ","NE","LT","GT","LE","GE","AND","OR","XOR","%"],built_in:["ATAN","ABS","ACOS","ASIN","COS","EXP","FIX","FUP","ROUND","LN","SIN","SQRT","TAN","EXISTS"]},contains:[e.COMMENT(/\(/,/\)/),e.COMMENT(/;/,/$/),e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,{scope:"title.function",variants:[{match:t.concat(r,i)},{begin:i,"on:begin":n},{match:t.concat(r,o)},{begin:o,"on:begin":n}]},{scope:"symbol",variants:[{match:t.concat(r,s)},{begin:s,"on:begin":n},{match:t.concat(r,l)},{begin:l,"on:begin":n},{match:/\*\s*\d+\s*$/}]},{scope:"operator",match:/^N\s*\d+/},{scope:"variable",match:/-?#\s*\d+/},{scope:"property",variants:[{match:t.concat(r,c,a)},{begin:t.concat(c,a),"on:begin":n}]},{scope:"params",variants:[{match:t.concat(r,d,a)},{begin:t.concat(d,a),"on:begin":n}]}]}}),n_)),zf.registerLanguage("gherkin",(o_||(o_=1,i_=function(e){return{name:"Gherkin",aliases:["feature"],keywords:"Feature Background Ability Business Need Scenario Scenarios Scenario Outline Scenario Template Examples Given And Then But When",contains:[{className:"symbol",begin:"\\*",relevance:0},{className:"meta",begin:"@[^@\\s]+"},{begin:"\\|",end:"\\|\\w*$",contains:[{className:"string",begin:"[^|]+"}]},{className:"variable",begin:"<",end:">"},e.HASH_COMMENT_MODE,{className:"string",begin:'"""',end:'"""'},e.QUOTE_STRING_MODE]}}),i_)),zf.registerLanguage("glsl",(l_||(l_=1,s_=function(e){return{name:"GLSL",keywords:{keyword:"break continue discard do else for if return while switch case default attribute binding buffer ccw centroid centroid varying coherent column_major const cw depth_any depth_greater depth_less depth_unchanged early_fragment_tests equal_spacing flat fractional_even_spacing fractional_odd_spacing highp in index inout invariant invocations isolines layout line_strip lines lines_adjacency local_size_x local_size_y local_size_z location lowp max_vertices mediump noperspective offset origin_upper_left out packed patch pixel_center_integer point_mode points precise precision quads r11f_g11f_b10f r16 r16_snorm r16f r16i r16ui r32f r32i r32ui r8 r8_snorm r8i r8ui readonly restrict rg16 rg16_snorm rg16f rg16i rg16ui rg32f rg32i rg32ui rg8 rg8_snorm rg8i rg8ui rgb10_a2 rgb10_a2ui rgba16 rgba16_snorm rgba16f rgba16i rgba16ui rgba32f rgba32i rgba32ui rgba8 rgba8_snorm rgba8i rgba8ui row_major sample shared smooth std140 std430 stream triangle_strip triangles triangles_adjacency uniform varying vertices volatile writeonly",type:"atomic_uint bool bvec2 bvec3 bvec4 dmat2 dmat2x2 dmat2x3 dmat2x4 dmat3 dmat3x2 dmat3x3 dmat3x4 dmat4 dmat4x2 dmat4x3 dmat4x4 double dvec2 dvec3 dvec4 float iimage1D iimage1DArray iimage2D iimage2DArray iimage2DMS iimage2DMSArray iimage2DRect iimage3D iimageBuffer iimageCube iimageCubeArray image1D image1DArray image2D image2DArray image2DMS image2DMSArray image2DRect image3D imageBuffer imageCube imageCubeArray int isampler1D isampler1DArray isampler2D isampler2DArray isampler2DMS isampler2DMSArray isampler2DRect isampler3D isamplerBuffer isamplerCube isamplerCubeArray ivec2 ivec3 ivec4 mat2 mat2x2 mat2x3 mat2x4 mat3 mat3x2 mat3x3 mat3x4 mat4 mat4x2 mat4x3 mat4x4 sampler1D sampler1DArray sampler1DArrayShadow sampler1DShadow sampler2D sampler2DArray sampler2DArrayShadow sampler2DMS sampler2DMSArray sampler2DRect sampler2DRectShadow sampler2DShadow sampler3D samplerBuffer samplerCube samplerCubeArray samplerCubeArrayShadow samplerCubeShadow image1D uimage1DArray uimage2D uimage2DArray uimage2DMS uimage2DMSArray uimage2DRect uimage3D uimageBuffer uimageCube uimageCubeArray uint usampler1D usampler1DArray usampler2D usampler2DArray usampler2DMS usampler2DMSArray usampler2DRect usampler3D samplerBuffer usamplerCube usamplerCubeArray uvec2 uvec3 uvec4 vec2 vec3 vec4 void",built_in:"gl_MaxAtomicCounterBindings gl_MaxAtomicCounterBufferSize gl_MaxClipDistances gl_MaxClipPlanes gl_MaxCombinedAtomicCounterBuffers gl_MaxCombinedAtomicCounters gl_MaxCombinedImageUniforms gl_MaxCombinedImageUnitsAndFragmentOutputs gl_MaxCombinedTextureImageUnits gl_MaxComputeAtomicCounterBuffers gl_MaxComputeAtomicCounters gl_MaxComputeImageUniforms gl_MaxComputeTextureImageUnits gl_MaxComputeUniformComponents gl_MaxComputeWorkGroupCount gl_MaxComputeWorkGroupSize gl_MaxDrawBuffers gl_MaxFragmentAtomicCounterBuffers gl_MaxFragmentAtomicCounters gl_MaxFragmentImageUniforms gl_MaxFragmentInputComponents gl_MaxFragmentInputVectors gl_MaxFragmentUniformComponents gl_MaxFragmentUniformVectors gl_MaxGeometryAtomicCounterBuffers gl_MaxGeometryAtomicCounters gl_MaxGeometryImageUniforms gl_MaxGeometryInputComponents gl_MaxGeometryOutputComponents gl_MaxGeometryOutputVertices gl_MaxGeometryTextureImageUnits gl_MaxGeometryTotalOutputComponents gl_MaxGeometryUniformComponents gl_MaxGeometryVaryingComponents gl_MaxImageSamples gl_MaxImageUnits gl_MaxLights gl_MaxPatchVertices gl_MaxProgramTexelOffset gl_MaxTessControlAtomicCounterBuffers gl_MaxTessControlAtomicCounters gl_MaxTessControlImageUniforms gl_MaxTessControlInputComponents gl_MaxTessControlOutputComponents gl_MaxTessControlTextureImageUnits gl_MaxTessControlTotalOutputComponents gl_MaxTessControlUniformComponents gl_MaxTessEvaluationAtomicCounterBuffers gl_MaxTessEvaluationAtomicCounters gl_MaxTessEvaluationImageUniforms gl_MaxTessEvaluationInputComponents gl_MaxTessEvaluationOutputComponents gl_MaxTessEvaluationTextureImageUnits gl_MaxTessEvaluationUniformComponents gl_MaxTessGenLevel gl_MaxTessPatchComponents gl_MaxTextureCoords gl_MaxTextureImageUnits gl_MaxTextureUnits gl_MaxVaryingComponents gl_MaxVaryingFloats gl_MaxVaryingVectors gl_MaxVertexAtomicCounterBuffers gl_MaxVertexAtomicCounters gl_MaxVertexAttribs gl_MaxVertexImageUniforms gl_MaxVertexOutputComponents gl_MaxVertexOutputVectors gl_MaxVertexTextureImageUnits gl_MaxVertexUniformComponents gl_MaxVertexUniformVectors gl_MaxViewports gl_MinProgramTexelOffset gl_BackColor gl_BackLightModelProduct gl_BackLightProduct gl_BackMaterial gl_BackSecondaryColor gl_ClipDistance gl_ClipPlane gl_ClipVertex gl_Color gl_DepthRange gl_EyePlaneQ gl_EyePlaneR gl_EyePlaneS gl_EyePlaneT gl_Fog gl_FogCoord gl_FogFragCoord gl_FragColor gl_FragCoord gl_FragData gl_FragDepth gl_FrontColor gl_FrontFacing gl_FrontLightModelProduct gl_FrontLightProduct gl_FrontMaterial gl_FrontSecondaryColor gl_GlobalInvocationID gl_InstanceID gl_InvocationID gl_Layer gl_LightModel gl_LightSource gl_LocalInvocationID gl_LocalInvocationIndex gl_ModelViewMatrix gl_ModelViewMatrixInverse gl_ModelViewMatrixInverseTranspose gl_ModelViewMatrixTranspose gl_ModelViewProjectionMatrix gl_ModelViewProjectionMatrixInverse gl_ModelViewProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixTranspose gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_Normal gl_NormalMatrix gl_NormalScale gl_NumSamples gl_NumWorkGroups gl_ObjectPlaneQ gl_ObjectPlaneR gl_ObjectPlaneS gl_ObjectPlaneT gl_PatchVerticesIn gl_Point gl_PointCoord gl_PointSize gl_Position gl_PrimitiveID gl_PrimitiveIDIn gl_ProjectionMatrix gl_ProjectionMatrixInverse gl_ProjectionMatrixInverseTranspose gl_ProjectionMatrixTranspose gl_SampleID gl_SampleMask gl_SampleMaskIn gl_SamplePosition gl_SecondaryColor gl_TessCoord gl_TessLevelInner gl_TessLevelOuter gl_TexCoord gl_TextureEnvColor gl_TextureMatrix gl_TextureMatrixInverse gl_TextureMatrixInverseTranspose gl_TextureMatrixTranspose gl_Vertex gl_VertexID gl_ViewportIndex gl_WorkGroupID gl_WorkGroupSize gl_in gl_out EmitStreamVertex EmitVertex EndPrimitive EndStreamPrimitive abs acos acosh all any asin asinh atan atanh atomicAdd atomicAnd atomicCompSwap atomicCounter atomicCounterDecrement atomicCounterIncrement atomicExchange atomicMax atomicMin atomicOr atomicXor barrier bitCount bitfieldExtract bitfieldInsert bitfieldReverse ceil clamp cos cosh cross dFdx dFdy degrees determinant distance dot equal exp exp2 faceforward findLSB findMSB floatBitsToInt floatBitsToUint floor fma fract frexp ftransform fwidth greaterThan greaterThanEqual groupMemoryBarrier imageAtomicAdd imageAtomicAnd imageAtomicCompSwap imageAtomicExchange imageAtomicMax imageAtomicMin imageAtomicOr imageAtomicXor imageLoad imageSize imageStore imulExtended intBitsToFloat interpolateAtCentroid interpolateAtOffset interpolateAtSample inverse inversesqrt isinf isnan ldexp length lessThan lessThanEqual log log2 matrixCompMult max memoryBarrier memoryBarrierAtomicCounter memoryBarrierBuffer memoryBarrierImage memoryBarrierShared min mix mod modf noise1 noise2 noise3 noise4 normalize not notEqual outerProduct packDouble2x32 packHalf2x16 packSnorm2x16 packSnorm4x8 packUnorm2x16 packUnorm4x8 pow radians reflect refract round roundEven shadow1D shadow1DLod shadow1DProj shadow1DProjLod shadow2D shadow2DLod shadow2DProj shadow2DProjLod sign sin sinh smoothstep sqrt step tan tanh texelFetch texelFetchOffset texture texture1D texture1DLod texture1DProj texture1DProjLod texture2D texture2DLod texture2DProj texture2DProjLod texture3D texture3DLod texture3DProj texture3DProjLod textureCube textureCubeLod textureGather textureGatherOffset textureGatherOffsets textureGrad textureGradOffset textureLod textureLodOffset textureOffset textureProj textureProjGrad textureProjGradOffset textureProjLod textureProjLodOffset textureProjOffset textureQueryLevels textureQueryLod textureSize transpose trunc uaddCarry uintBitsToFloat umulExtended unpackDouble2x32 unpackHalf2x16 unpackSnorm2x16 unpackSnorm4x8 unpackUnorm2x16 unpackUnorm4x8 usubBorrow",literal:"true false"},illegal:'"',contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.C_NUMBER_MODE,{className:"meta",begin:"#",end:"$"}]}}),s_)),zf.registerLanguage("gml",(d_||(d_=1,c_=function(e){return{name:"GML",case_insensitive:!1,keywords:{keyword:["#endregion","#macro","#region","and","begin","break","case","constructor","continue","default","delete","div","do","else","end","enum","exit","for","function","globalvar","if","mod","new","not","or","repeat","return","static","switch","then","until","var","while","with","xor"],built_in:["abs","alarm_get","alarm_set","angle_difference","animcurve_channel_evaluate","animcurve_channel_new","animcurve_create","animcurve_destroy","animcurve_exists","animcurve_get","animcurve_get_channel","animcurve_get_channel_index","animcurve_point_new","ansi_char","application_get_position","application_surface_draw_enable","application_surface_enable","application_surface_is_enabled","arccos","arcsin","arctan","arctan2","array_all","array_any","array_concat","array_contains","array_contains_ext","array_copy","array_copy_while","array_create","array_create_ext","array_delete","array_equals","array_filter","array_filter_ext","array_find_index","array_first","array_foreach","array_get","array_get_index","array_insert","array_intersection","array_last","array_length","array_map","array_map_ext","array_pop","array_push","array_reduce","array_resize","array_reverse","array_reverse_ext","array_set","array_shuffle","array_shuffle_ext","array_sort","array_union","array_unique","array_unique_ext","asset_add_tags","asset_clear_tags","asset_get_ids","asset_get_index","asset_get_tags","asset_get_type","asset_has_any_tag","asset_has_tags","asset_remove_tags","audio_bus_clear_emitters","audio_bus_create","audio_bus_get_emitters","audio_channel_num","audio_create_buffer_sound","audio_create_play_queue","audio_create_stream","audio_create_sync_group","audio_debug","audio_destroy_stream","audio_destroy_sync_group","audio_effect_create","audio_emitter_bus","audio_emitter_create","audio_emitter_exists","audio_emitter_falloff","audio_emitter_free","audio_emitter_gain","audio_emitter_get_bus","audio_emitter_get_gain","audio_emitter_get_listener_mask","audio_emitter_get_pitch","audio_emitter_get_vx","audio_emitter_get_vy","audio_emitter_get_vz","audio_emitter_get_x","audio_emitter_get_y","audio_emitter_get_z","audio_emitter_pitch","audio_emitter_position","audio_emitter_set_listener_mask","audio_emitter_velocity","audio_exists","audio_falloff_set_model","audio_free_buffer_sound","audio_free_play_queue","audio_get_listener_count","audio_get_listener_info","audio_get_listener_mask","audio_get_master_gain","audio_get_name","audio_get_recorder_count","audio_get_recorder_info","audio_get_type","audio_group_get_assets","audio_group_get_gain","audio_group_is_loaded","audio_group_load","audio_group_load_progress","audio_group_name","audio_group_set_gain","audio_group_stop_all","audio_group_unload","audio_is_paused","audio_is_playing","audio_listener_get_data","audio_listener_orientation","audio_listener_position","audio_listener_set_orientation","audio_listener_set_position","audio_listener_set_velocity","audio_listener_velocity","audio_master_gain","audio_pause_all","audio_pause_sound","audio_pause_sync_group","audio_play_in_sync_group","audio_play_sound","audio_play_sound_at","audio_play_sound_ext","audio_play_sound_on","audio_queue_sound","audio_resume_all","audio_resume_sound","audio_resume_sync_group","audio_set_listener_mask","audio_set_master_gain","audio_sound_gain","audio_sound_get_audio_group","audio_sound_get_gain","audio_sound_get_listener_mask","audio_sound_get_loop","audio_sound_get_loop_end","audio_sound_get_loop_start","audio_sound_get_pitch","audio_sound_get_track_position","audio_sound_is_playable","audio_sound_length","audio_sound_loop","audio_sound_loop_end","audio_sound_loop_start","audio_sound_pitch","audio_sound_set_listener_mask","audio_sound_set_track_position","audio_start_recording","audio_start_sync_group","audio_stop_all","audio_stop_recording","audio_stop_sound","audio_stop_sync_group","audio_sync_group_debug","audio_sync_group_get_track_pos","audio_sync_group_is_paused","audio_sync_group_is_playing","audio_system_is_available","audio_system_is_initialised","base64_decode","base64_encode","bool","browser_input_capture","buffer_async_group_begin","buffer_async_group_end","buffer_async_group_option","buffer_base64_decode","buffer_base64_decode_ext","buffer_base64_encode","buffer_compress","buffer_copy","buffer_copy_from_vertex_buffer","buffer_copy_stride","buffer_crc32","buffer_create","buffer_create_from_vertex_buffer","buffer_create_from_vertex_buffer_ext","buffer_decompress","buffer_delete","buffer_exists","buffer_fill","buffer_get_address","buffer_get_alignment","buffer_get_size","buffer_get_surface","buffer_get_type","buffer_load","buffer_load_async","buffer_load_ext","buffer_load_partial","buffer_md5","buffer_peek","buffer_poke","buffer_read","buffer_resize","buffer_save","buffer_save_async","buffer_save_ext","buffer_seek","buffer_set_surface","buffer_set_used_size","buffer_sha1","buffer_sizeof","buffer_tell","buffer_write","call_cancel","call_later","camera_apply","camera_copy_transforms","camera_create","camera_create_view","camera_destroy","camera_get_active","camera_get_begin_script","camera_get_default","camera_get_end_script","camera_get_proj_mat","camera_get_update_script","camera_get_view_angle","camera_get_view_border_x","camera_get_view_border_y","camera_get_view_height","camera_get_view_mat","camera_get_view_speed_x","camera_get_view_speed_y","camera_get_view_target","camera_get_view_width","camera_get_view_x","camera_get_view_y","camera_set_begin_script","camera_set_default","camera_set_end_script","camera_set_proj_mat","camera_set_update_script","camera_set_view_angle","camera_set_view_border","camera_set_view_mat","camera_set_view_pos","camera_set_view_size","camera_set_view_speed","camera_set_view_target","ceil","choose","chr","clamp","clickable_add","clickable_add_ext","clickable_change","clickable_change_ext","clickable_delete","clickable_exists","clickable_set_style","clipboard_get_text","clipboard_has_text","clipboard_set_text","cloud_file_save","cloud_string_save","cloud_synchronise","code_is_compiled","collision_circle","collision_circle_list","collision_ellipse","collision_ellipse_list","collision_line","collision_line_list","collision_point","collision_point_list","collision_rectangle","collision_rectangle_list","color_get_blue","color_get_green","color_get_hue","color_get_red","color_get_saturation","color_get_value","colour_get_blue","colour_get_green","colour_get_hue","colour_get_red","colour_get_saturation","colour_get_value","cos","darccos","darcsin","darctan","darctan2","date_compare_date","date_compare_datetime","date_compare_time","date_create_datetime","date_current_datetime","date_date_of","date_date_string","date_datetime_string","date_day_span","date_days_in_month","date_days_in_year","date_get_day","date_get_day_of_year","date_get_hour","date_get_hour_of_year","date_get_minute","date_get_minute_of_year","date_get_month","date_get_second","date_get_second_of_year","date_get_timezone","date_get_week","date_get_weekday","date_get_year","date_hour_span","date_inc_day","date_inc_hour","date_inc_minute","date_inc_month","date_inc_second","date_inc_week","date_inc_year","date_is_today","date_leap_year","date_minute_span","date_month_span","date_second_span","date_set_timezone","date_time_of","date_time_string","date_valid_datetime","date_week_span","date_year_span","db_to_lin","dbg_add_font_glyphs","dbg_button","dbg_checkbox","dbg_color","dbg_colour","dbg_drop_down","dbg_same_line","dbg_section","dbg_section_delete","dbg_section_exists","dbg_slider","dbg_slider_int","dbg_sprite","dbg_text","dbg_text_input","dbg_view","dbg_view_delete","dbg_view_exists","dbg_watch","dcos","debug_event","debug_get_callstack","degtorad","device_get_tilt_x","device_get_tilt_y","device_get_tilt_z","device_is_keypad_open","device_mouse_check_button","device_mouse_check_button_pressed","device_mouse_check_button_released","device_mouse_dbclick_enable","device_mouse_raw_x","device_mouse_raw_y","device_mouse_x","device_mouse_x_to_gui","device_mouse_y","device_mouse_y_to_gui","directory_create","directory_destroy","directory_exists","display_get_dpi_x","display_get_dpi_y","display_get_frequency","display_get_gui_height","display_get_gui_width","display_get_height","display_get_orientation","display_get_sleep_margin","display_get_timing_method","display_get_width","display_mouse_get_x","display_mouse_get_y","display_mouse_set","display_reset","display_set_gui_maximise","display_set_gui_maximize","display_set_gui_size","display_set_sleep_margin","display_set_timing_method","display_set_ui_visibility","distance_to_object","distance_to_point","dot_product","dot_product_3d","dot_product_3d_normalised","dot_product_3d_normalized","dot_product_normalised","dot_product_normalized","draw_arrow","draw_button","draw_circle","draw_circle_color","draw_circle_colour","draw_clear","draw_clear_alpha","draw_ellipse","draw_ellipse_color","draw_ellipse_colour","draw_enable_drawevent","draw_enable_skeleton_blendmodes","draw_enable_swf_aa","draw_flush","draw_get_alpha","draw_get_color","draw_get_colour","draw_get_enable_skeleton_blendmodes","draw_get_font","draw_get_halign","draw_get_lighting","draw_get_swf_aa_level","draw_get_valign","draw_getpixel","draw_getpixel_ext","draw_healthbar","draw_highscore","draw_light_define_ambient","draw_light_define_direction","draw_light_define_point","draw_light_enable","draw_light_get","draw_light_get_ambient","draw_line","draw_line_color","draw_line_colour","draw_line_width","draw_line_width_color","draw_line_width_colour","draw_path","draw_point","draw_point_color","draw_point_colour","draw_primitive_begin","draw_primitive_begin_texture","draw_primitive_end","draw_rectangle","draw_rectangle_color","draw_rectangle_colour","draw_roundrect","draw_roundrect_color","draw_roundrect_color_ext","draw_roundrect_colour","draw_roundrect_colour_ext","draw_roundrect_ext","draw_self","draw_set_alpha","draw_set_circle_precision","draw_set_color","draw_set_colour","draw_set_font","draw_set_halign","draw_set_lighting","draw_set_swf_aa_level","draw_set_valign","draw_skeleton","draw_skeleton_collision","draw_skeleton_instance","draw_skeleton_time","draw_sprite","draw_sprite_ext","draw_sprite_general","draw_sprite_part","draw_sprite_part_ext","draw_sprite_pos","draw_sprite_stretched","draw_sprite_stretched_ext","draw_sprite_tiled","draw_sprite_tiled_ext","draw_surface","draw_surface_ext","draw_surface_general","draw_surface_part","draw_surface_part_ext","draw_surface_stretched","draw_surface_stretched_ext","draw_surface_tiled","draw_surface_tiled_ext","draw_text","draw_text_color","draw_text_colour","draw_text_ext","draw_text_ext_color","draw_text_ext_colour","draw_text_ext_transformed","draw_text_ext_transformed_color","draw_text_ext_transformed_colour","draw_text_transformed","draw_text_transformed_color","draw_text_transformed_colour","draw_texture_flush","draw_tile","draw_tilemap","draw_triangle","draw_triangle_color","draw_triangle_colour","draw_vertex","draw_vertex_color","draw_vertex_colour","draw_vertex_texture","draw_vertex_texture_color","draw_vertex_texture_colour","ds_exists","ds_grid_add","ds_grid_add_disk","ds_grid_add_grid_region","ds_grid_add_region","ds_grid_clear","ds_grid_copy","ds_grid_create","ds_grid_destroy","ds_grid_get","ds_grid_get_disk_max","ds_grid_get_disk_mean","ds_grid_get_disk_min","ds_grid_get_disk_sum","ds_grid_get_max","ds_grid_get_mean","ds_grid_get_min","ds_grid_get_sum","ds_grid_height","ds_grid_multiply","ds_grid_multiply_disk","ds_grid_multiply_grid_region","ds_grid_multiply_region","ds_grid_read","ds_grid_resize","ds_grid_set","ds_grid_set_disk","ds_grid_set_grid_region","ds_grid_set_region","ds_grid_shuffle","ds_grid_sort","ds_grid_to_mp_grid","ds_grid_value_disk_exists","ds_grid_value_disk_x","ds_grid_value_disk_y","ds_grid_value_exists","ds_grid_value_x","ds_grid_value_y","ds_grid_width","ds_grid_write","ds_list_add","ds_list_clear","ds_list_copy","ds_list_create","ds_list_delete","ds_list_destroy","ds_list_empty","ds_list_find_index","ds_list_find_value","ds_list_insert","ds_list_is_list","ds_list_is_map","ds_list_mark_as_list","ds_list_mark_as_map","ds_list_read","ds_list_replace","ds_list_set","ds_list_shuffle","ds_list_size","ds_list_sort","ds_list_write","ds_map_add","ds_map_add_list","ds_map_add_map","ds_map_clear","ds_map_copy","ds_map_create","ds_map_delete","ds_map_destroy","ds_map_empty","ds_map_exists","ds_map_find_first","ds_map_find_last","ds_map_find_next","ds_map_find_previous","ds_map_find_value","ds_map_is_list","ds_map_is_map","ds_map_keys_to_array","ds_map_read","ds_map_replace","ds_map_replace_list","ds_map_replace_map","ds_map_secure_load","ds_map_secure_load_buffer","ds_map_secure_save","ds_map_secure_save_buffer","ds_map_set","ds_map_size","ds_map_values_to_array","ds_map_write","ds_priority_add","ds_priority_change_priority","ds_priority_clear","ds_priority_copy","ds_priority_create","ds_priority_delete_max","ds_priority_delete_min","ds_priority_delete_value","ds_priority_destroy","ds_priority_empty","ds_priority_find_max","ds_priority_find_min","ds_priority_find_priority","ds_priority_read","ds_priority_size","ds_priority_write","ds_queue_clear","ds_queue_copy","ds_queue_create","ds_queue_dequeue","ds_queue_destroy","ds_queue_empty","ds_queue_enqueue","ds_queue_head","ds_queue_read","ds_queue_size","ds_queue_tail","ds_queue_write","ds_set_precision","ds_stack_clear","ds_stack_copy","ds_stack_create","ds_stack_destroy","ds_stack_empty","ds_stack_pop","ds_stack_push","ds_stack_read","ds_stack_size","ds_stack_top","ds_stack_write","dsin","dtan","effect_clear","effect_create_above","effect_create_below","effect_create_depth","effect_create_layer","environment_get_variable","event_inherited","event_perform","event_perform_async","event_perform_object","event_user","exception_unhandled_handler","exp","extension_exists","extension_get_option_count","extension_get_option_names","extension_get_option_value","extension_get_options","extension_get_version","external_call","external_define","external_free","file_attributes","file_bin_close","file_bin_open","file_bin_position","file_bin_read_byte","file_bin_rewrite","file_bin_seek","file_bin_size","file_bin_write_byte","file_copy","file_delete","file_exists","file_find_close","file_find_first","file_find_next","file_rename","file_text_close","file_text_eof","file_text_eoln","file_text_open_append","file_text_open_from_string","file_text_open_read","file_text_open_write","file_text_read_real","file_text_read_string","file_text_readln","file_text_write_real","file_text_write_string","file_text_writeln","filename_change_ext","filename_dir","filename_drive","filename_ext","filename_name","filename_path","floor","font_add","font_add_enable_aa","font_add_get_enable_aa","font_add_sprite","font_add_sprite_ext","font_cache_glyph","font_delete","font_enable_effects","font_enable_sdf","font_exists","font_get_bold","font_get_first","font_get_fontname","font_get_info","font_get_italic","font_get_last","font_get_name","font_get_sdf_enabled","font_get_sdf_spread","font_get_size","font_get_texture","font_get_uvs","font_replace_sprite","font_replace_sprite_ext","font_sdf_spread","font_set_cache_size","frac","fx_create","fx_get_name","fx_get_parameter","fx_get_parameter_names","fx_get_parameters","fx_get_single_layer","fx_set_parameter","fx_set_parameters","fx_set_single_layer","game_change","game_end","game_get_speed","game_load","game_load_buffer","game_restart","game_save","game_save_buffer","game_set_speed","gamepad_axis_count","gamepad_axis_value","gamepad_button_check","gamepad_button_check_pressed","gamepad_button_check_released","gamepad_button_count","gamepad_button_value","gamepad_get_axis_deadzone","gamepad_get_button_threshold","gamepad_get_description","gamepad_get_device_count","gamepad_get_guid","gamepad_get_mapping","gamepad_get_option","gamepad_hat_count","gamepad_hat_value","gamepad_is_connected","gamepad_is_supported","gamepad_remove_mapping","gamepad_set_axis_deadzone","gamepad_set_button_threshold","gamepad_set_color","gamepad_set_colour","gamepad_set_option","gamepad_set_vibration","gamepad_test_mapping","gc_collect","gc_enable","gc_get_stats","gc_get_target_frame_time","gc_is_enabled","gc_target_frame_time","gesture_double_tap_distance","gesture_double_tap_time","gesture_drag_distance","gesture_drag_time","gesture_flick_speed","gesture_get_double_tap_distance","gesture_get_double_tap_time","gesture_get_drag_distance","gesture_get_drag_time","gesture_get_flick_speed","gesture_get_pinch_angle_away","gesture_get_pinch_angle_towards","gesture_get_pinch_distance","gesture_get_rotate_angle","gesture_get_rotate_time","gesture_get_tap_count","gesture_pinch_angle_away","gesture_pinch_angle_towards","gesture_pinch_distance","gesture_rotate_angle","gesture_rotate_time","gesture_tap_count","get_integer","get_integer_async","get_login_async","get_open_filename","get_open_filename_ext","get_save_filename","get_save_filename_ext","get_string","get_string_async","get_timer","gif_add_surface","gif_open","gif_save","gif_save_buffer","gml_pragma","gml_release_mode","gpu_get_alphatestenable","gpu_get_alphatestref","gpu_get_blendenable","gpu_get_blendmode","gpu_get_blendmode_dest","gpu_get_blendmode_destalpha","gpu_get_blendmode_ext","gpu_get_blendmode_ext_sepalpha","gpu_get_blendmode_src","gpu_get_blendmode_srcalpha","gpu_get_colorwriteenable","gpu_get_colourwriteenable","gpu_get_cullmode","gpu_get_depth","gpu_get_fog","gpu_get_state","gpu_get_tex_filter","gpu_get_tex_filter_ext","gpu_get_tex_max_aniso","gpu_get_tex_max_aniso_ext","gpu_get_tex_max_mip","gpu_get_tex_max_mip_ext","gpu_get_tex_min_mip","gpu_get_tex_min_mip_ext","gpu_get_tex_mip_bias","gpu_get_tex_mip_bias_ext","gpu_get_tex_mip_enable","gpu_get_tex_mip_enable_ext","gpu_get_tex_mip_filter","gpu_get_tex_mip_filter_ext","gpu_get_tex_repeat","gpu_get_tex_repeat_ext","gpu_get_texfilter","gpu_get_texfilter_ext","gpu_get_texrepeat","gpu_get_texrepeat_ext","gpu_get_zfunc","gpu_get_ztestenable","gpu_get_zwriteenable","gpu_pop_state","gpu_push_state","gpu_set_alphatestenable","gpu_set_alphatestref","gpu_set_blendenable","gpu_set_blendmode","gpu_set_blendmode_ext","gpu_set_blendmode_ext_sepalpha","gpu_set_colorwriteenable","gpu_set_colourwriteenable","gpu_set_cullmode","gpu_set_depth","gpu_set_fog","gpu_set_state","gpu_set_tex_filter","gpu_set_tex_filter_ext","gpu_set_tex_max_aniso","gpu_set_tex_max_aniso_ext","gpu_set_tex_max_mip","gpu_set_tex_max_mip_ext","gpu_set_tex_min_mip","gpu_set_tex_min_mip_ext","gpu_set_tex_mip_bias","gpu_set_tex_mip_bias_ext","gpu_set_tex_mip_enable","gpu_set_tex_mip_enable_ext","gpu_set_tex_mip_filter","gpu_set_tex_mip_filter_ext","gpu_set_tex_repeat","gpu_set_tex_repeat_ext","gpu_set_texfilter","gpu_set_texfilter_ext","gpu_set_texrepeat","gpu_set_texrepeat_ext","gpu_set_zfunc","gpu_set_ztestenable","gpu_set_zwriteenable","handle_parse","highscore_add","highscore_clear","highscore_name","highscore_value","http_get","http_get_file","http_get_request_crossorigin","http_post_string","http_request","http_set_request_crossorigin","iap_acquire","iap_activate","iap_consume","iap_enumerate_products","iap_product_details","iap_purchase_details","iap_restore_all","iap_status","ini_close","ini_key_delete","ini_key_exists","ini_open","ini_open_from_string","ini_read_real","ini_read_string","ini_section_delete","ini_section_exists","ini_write_real","ini_write_string","instance_activate_all","instance_activate_layer","instance_activate_object","instance_activate_region","instance_change","instance_copy","instance_create_depth","instance_create_layer","instance_deactivate_all","instance_deactivate_layer","instance_deactivate_object","instance_deactivate_region","instance_destroy","instance_exists","instance_find","instance_furthest","instance_id_get","instance_nearest","instance_number","instance_place","instance_place_list","instance_position","instance_position_list","instanceof","int64","io_clear","irandom","irandom_range","is_array","is_bool","is_callable","is_debug_overlay_open","is_handle","is_infinity","is_instanceof","is_int32","is_int64","is_keyboard_used_debug_overlay","is_method","is_mouse_over_debug_overlay","is_nan","is_numeric","is_ptr","is_real","is_string","is_struct","is_undefined","json_decode","json_encode","json_parse","json_stringify","keyboard_check","keyboard_check_direct","keyboard_check_pressed","keyboard_check_released","keyboard_clear","keyboard_get_map","keyboard_get_numlock","keyboard_key_press","keyboard_key_release","keyboard_set_map","keyboard_set_numlock","keyboard_unset_map","keyboard_virtual_height","keyboard_virtual_hide","keyboard_virtual_show","keyboard_virtual_status","layer_add_instance","layer_background_alpha","layer_background_blend","layer_background_change","layer_background_create","layer_background_destroy","layer_background_exists","layer_background_get_alpha","layer_background_get_blend","layer_background_get_htiled","layer_background_get_id","layer_background_get_index","layer_background_get_speed","layer_background_get_sprite","layer_background_get_stretch","layer_background_get_visible","layer_background_get_vtiled","layer_background_get_xscale","layer_background_get_yscale","layer_background_htiled","layer_background_index","layer_background_speed","layer_background_sprite","layer_background_stretch","layer_background_visible","layer_background_vtiled","layer_background_xscale","layer_background_yscale","layer_clear_fx","layer_create","layer_depth","layer_destroy","layer_destroy_instances","layer_element_move","layer_enable_fx","layer_exists","layer_force_draw_depth","layer_fx_is_enabled","layer_get_all","layer_get_all_elements","layer_get_depth","layer_get_element_layer","layer_get_element_type","layer_get_forced_depth","layer_get_fx","layer_get_hspeed","layer_get_id","layer_get_id_at_depth","layer_get_name","layer_get_script_begin","layer_get_script_end","layer_get_shader","layer_get_target_room","layer_get_visible","layer_get_vspeed","layer_get_x","layer_get_y","layer_has_instance","layer_hspeed","layer_instance_get_instance","layer_is_draw_depth_forced","layer_reset_target_room","layer_script_begin","layer_script_end","layer_sequence_angle","layer_sequence_create","layer_sequence_destroy","layer_sequence_exists","layer_sequence_get_angle","layer_sequence_get_headdir","layer_sequence_get_headpos","layer_sequence_get_instance","layer_sequence_get_length","layer_sequence_get_sequence","layer_sequence_get_speedscale","layer_sequence_get_x","layer_sequence_get_xscale","layer_sequence_get_y","layer_sequence_get_yscale","layer_sequence_headdir","layer_sequence_headpos","layer_sequence_is_finished","layer_sequence_is_paused","layer_sequence_pause","layer_sequence_play","layer_sequence_speedscale","layer_sequence_x","layer_sequence_xscale","layer_sequence_y","layer_sequence_yscale","layer_set_fx","layer_set_target_room","layer_set_visible","layer_shader","layer_sprite_alpha","layer_sprite_angle","layer_sprite_blend","layer_sprite_change","layer_sprite_create","layer_sprite_destroy","layer_sprite_exists","layer_sprite_get_alpha","layer_sprite_get_angle","layer_sprite_get_blend","layer_sprite_get_id","layer_sprite_get_index","layer_sprite_get_speed","layer_sprite_get_sprite","layer_sprite_get_x","layer_sprite_get_xscale","layer_sprite_get_y","layer_sprite_get_yscale","layer_sprite_index","layer_sprite_speed","layer_sprite_x","layer_sprite_xscale","layer_sprite_y","layer_sprite_yscale","layer_tile_alpha","layer_tile_blend","layer_tile_change","layer_tile_create","layer_tile_destroy","layer_tile_exists","layer_tile_get_alpha","layer_tile_get_blend","layer_tile_get_region","layer_tile_get_sprite","layer_tile_get_visible","layer_tile_get_x","layer_tile_get_xscale","layer_tile_get_y","layer_tile_get_yscale","layer_tile_region","layer_tile_visible","layer_tile_x","layer_tile_xscale","layer_tile_y","layer_tile_yscale","layer_tilemap_create","layer_tilemap_destroy","layer_tilemap_exists","layer_tilemap_get_id","layer_vspeed","layer_x","layer_y","lengthdir_x","lengthdir_y","lerp","lin_to_db","ln","load_csv","log10","log2","logn","make_color_hsv","make_color_rgb","make_colour_hsv","make_colour_rgb","math_get_epsilon","math_set_epsilon","matrix_build","matrix_build_identity","matrix_build_lookat","matrix_build_projection_ortho","matrix_build_projection_perspective","matrix_build_projection_perspective_fov","matrix_get","matrix_multiply","matrix_set","matrix_stack_clear","matrix_stack_is_empty","matrix_stack_pop","matrix_stack_push","matrix_stack_set","matrix_stack_top","matrix_transform_vertex","max","md5_file","md5_string_unicode","md5_string_utf8","mean","median","merge_color","merge_colour","method","method_call","method_get_index","method_get_self","min","motion_add","motion_set","mouse_check_button","mouse_check_button_pressed","mouse_check_button_released","mouse_clear","mouse_wheel_down","mouse_wheel_up","move_and_collide","move_bounce_all","move_bounce_solid","move_contact_all","move_contact_solid","move_outside_all","move_outside_solid","move_random","move_snap","move_towards_point","move_wrap","mp_grid_add_cell","mp_grid_add_instances","mp_grid_add_rectangle","mp_grid_clear_all","mp_grid_clear_cell","mp_grid_clear_rectangle","mp_grid_create","mp_grid_destroy","mp_grid_draw","mp_grid_get_cell","mp_grid_path","mp_grid_to_ds_grid","mp_linear_path","mp_linear_path_object","mp_linear_step","mp_linear_step_object","mp_potential_path","mp_potential_path_object","mp_potential_settings","mp_potential_step","mp_potential_step_object","nameof","network_connect","network_connect_async","network_connect_raw","network_connect_raw_async","network_create_server","network_create_server_raw","network_create_socket","network_create_socket_ext","network_destroy","network_resolve","network_send_broadcast","network_send_packet","network_send_raw","network_send_udp","network_send_udp_raw","network_set_config","network_set_timeout","object_exists","object_get_mask","object_get_name","object_get_parent","object_get_persistent","object_get_physics","object_get_solid","object_get_sprite","object_get_visible","object_is_ancestor","object_set_mask","object_set_persistent","object_set_solid","object_set_sprite","object_set_visible","ord","os_check_permission","os_get_config","os_get_info","os_get_language","os_get_region","os_is_network_connected","os_is_paused","os_lock_orientation","os_powersave_enable","os_request_permission","os_set_orientation_lock","parameter_count","parameter_string","part_emitter_burst","part_emitter_clear","part_emitter_create","part_emitter_delay","part_emitter_destroy","part_emitter_destroy_all","part_emitter_enable","part_emitter_exists","part_emitter_interval","part_emitter_region","part_emitter_relative","part_emitter_stream","part_particles_burst","part_particles_clear","part_particles_count","part_particles_create","part_particles_create_color","part_particles_create_colour","part_system_angle","part_system_automatic_draw","part_system_automatic_update","part_system_clear","part_system_color","part_system_colour","part_system_create","part_system_create_layer","part_system_depth","part_system_destroy","part_system_draw_order","part_system_drawit","part_system_exists","part_system_get_info","part_system_get_layer","part_system_global_space","part_system_layer","part_system_position","part_system_update","part_type_alpha1","part_type_alpha2","part_type_alpha3","part_type_blend","part_type_clear","part_type_color1","part_type_color2","part_type_color3","part_type_color_hsv","part_type_color_mix","part_type_color_rgb","part_type_colour1","part_type_colour2","part_type_colour3","part_type_colour_hsv","part_type_colour_mix","part_type_colour_rgb","part_type_create","part_type_death","part_type_destroy","part_type_direction","part_type_exists","part_type_gravity","part_type_life","part_type_orientation","part_type_scale","part_type_shape","part_type_size","part_type_size_x","part_type_size_y","part_type_speed","part_type_sprite","part_type_step","part_type_subimage","particle_exists","particle_get_info","path_add","path_add_point","path_append","path_assign","path_change_point","path_clear_points","path_delete","path_delete_point","path_duplicate","path_end","path_exists","path_flip","path_get_closed","path_get_kind","path_get_length","path_get_name","path_get_number","path_get_point_speed","path_get_point_x","path_get_point_y","path_get_precision","path_get_speed","path_get_x","path_get_y","path_insert_point","path_mirror","path_rescale","path_reverse","path_rotate","path_set_closed","path_set_kind","path_set_precision","path_shift","path_start","physics_apply_angular_impulse","physics_apply_force","physics_apply_impulse","physics_apply_local_force","physics_apply_local_impulse","physics_apply_torque","physics_draw_debug","physics_fixture_add_point","physics_fixture_bind","physics_fixture_bind_ext","physics_fixture_create","physics_fixture_delete","physics_fixture_set_angular_damping","physics_fixture_set_awake","physics_fixture_set_box_shape","physics_fixture_set_chain_shape","physics_fixture_set_circle_shape","physics_fixture_set_collision_group","physics_fixture_set_density","physics_fixture_set_edge_shape","physics_fixture_set_friction","physics_fixture_set_kinematic","physics_fixture_set_linear_damping","physics_fixture_set_polygon_shape","physics_fixture_set_restitution","physics_fixture_set_sensor","physics_get_density","physics_get_friction","physics_get_restitution","physics_joint_delete","physics_joint_distance_create","physics_joint_enable_motor","physics_joint_friction_create","physics_joint_gear_create","physics_joint_get_value","physics_joint_prismatic_create","physics_joint_pulley_create","physics_joint_revolute_create","physics_joint_rope_create","physics_joint_set_value","physics_joint_weld_create","physics_joint_wheel_create","physics_mass_properties","physics_particle_count","physics_particle_create","physics_particle_delete","physics_particle_delete_region_box","physics_particle_delete_region_circle","physics_particle_delete_region_poly","physics_particle_draw","physics_particle_draw_ext","physics_particle_get_damping","physics_particle_get_data","physics_particle_get_data_particle","physics_particle_get_density","physics_particle_get_gravity_scale","physics_particle_get_group_flags","physics_particle_get_max_count","physics_particle_get_radius","physics_particle_group_add_point","physics_particle_group_begin","physics_particle_group_box","physics_particle_group_circle","physics_particle_group_count","physics_particle_group_delete","physics_particle_group_end","physics_particle_group_get_ang_vel","physics_particle_group_get_angle","physics_particle_group_get_centre_x","physics_particle_group_get_centre_y","physics_particle_group_get_data","physics_particle_group_get_inertia","physics_particle_group_get_mass","physics_particle_group_get_vel_x","physics_particle_group_get_vel_y","physics_particle_group_get_x","physics_particle_group_get_y","physics_particle_group_join","physics_particle_group_polygon","physics_particle_set_category_flags","physics_particle_set_damping","physics_particle_set_density","physics_particle_set_flags","physics_particle_set_gravity_scale","physics_particle_set_group_flags","physics_particle_set_max_count","physics_particle_set_radius","physics_pause_enable","physics_remove_fixture","physics_set_density","physics_set_friction","physics_set_restitution","physics_test_overlap","physics_world_create","physics_world_draw_debug","physics_world_gravity","physics_world_update_iterations","physics_world_update_speed","place_empty","place_free","place_meeting","place_snapped","point_direction","point_distance","point_distance_3d","point_in_circle","point_in_rectangle","point_in_triangle","position_change","position_destroy","position_empty","position_meeting","power","ptr","radtodeg","random","random_get_seed","random_range","random_set_seed","randomise","randomize","real","rectangle_in_circle","rectangle_in_rectangle","rectangle_in_triangle","ref_create","rollback_chat","rollback_create_game","rollback_define_extra_network_latency","rollback_define_input","rollback_define_input_frame_delay","rollback_define_mock_input","rollback_define_player","rollback_display_events","rollback_get_info","rollback_get_input","rollback_get_player_prefs","rollback_join_game","rollback_leave_game","rollback_set_player_prefs","rollback_start_game","rollback_sync_on_frame","rollback_use_late_join","rollback_use_manual_start","rollback_use_player_prefs","rollback_use_random_input","room_add","room_assign","room_duplicate","room_exists","room_get_camera","room_get_info","room_get_name","room_get_viewport","room_goto","room_goto_next","room_goto_previous","room_instance_add","room_instance_clear","room_next","room_previous","room_restart","room_set_camera","room_set_height","room_set_persistent","room_set_view_enabled","room_set_viewport","room_set_width","round","scheduler_resolution_get","scheduler_resolution_set","screen_save","screen_save_part","script_execute","script_execute_ext","script_exists","script_get_name","sequence_create","sequence_destroy","sequence_exists","sequence_get","sequence_get_objects","sequence_instance_override_object","sequence_keyframe_new","sequence_keyframedata_new","sequence_track_new","sha1_file","sha1_string_unicode","sha1_string_utf8","shader_current","shader_enable_corner_id","shader_get_name","shader_get_sampler_index","shader_get_uniform","shader_is_compiled","shader_reset","shader_set","shader_set_uniform_f","shader_set_uniform_f_array","shader_set_uniform_f_buffer","shader_set_uniform_i","shader_set_uniform_i_array","shader_set_uniform_matrix","shader_set_uniform_matrix_array","shaders_are_supported","shop_leave_rating","show_debug_message","show_debug_message_ext","show_debug_overlay","show_error","show_message","show_message_async","show_question","show_question_async","sign","sin","skeleton_animation_clear","skeleton_animation_get","skeleton_animation_get_duration","skeleton_animation_get_event_frames","skeleton_animation_get_ext","skeleton_animation_get_frame","skeleton_animation_get_frames","skeleton_animation_get_position","skeleton_animation_is_finished","skeleton_animation_is_looping","skeleton_animation_list","skeleton_animation_mix","skeleton_animation_set","skeleton_animation_set_ext","skeleton_animation_set_frame","skeleton_animation_set_position","skeleton_attachment_create","skeleton_attachment_create_color","skeleton_attachment_create_colour","skeleton_attachment_destroy","skeleton_attachment_exists","skeleton_attachment_get","skeleton_attachment_replace","skeleton_attachment_replace_color","skeleton_attachment_replace_colour","skeleton_attachment_set","skeleton_bone_data_get","skeleton_bone_data_set","skeleton_bone_list","skeleton_bone_state_get","skeleton_bone_state_set","skeleton_collision_draw_set","skeleton_find_slot","skeleton_get_bounds","skeleton_get_minmax","skeleton_get_num_bounds","skeleton_skin_create","skeleton_skin_get","skeleton_skin_list","skeleton_skin_set","skeleton_slot_alpha_get","skeleton_slot_color_get","skeleton_slot_color_set","skeleton_slot_colour_get","skeleton_slot_colour_set","skeleton_slot_data","skeleton_slot_data_instance","skeleton_slot_list","sprite_add","sprite_add_ext","sprite_add_from_surface","sprite_assign","sprite_collision_mask","sprite_create_from_surface","sprite_delete","sprite_duplicate","sprite_exists","sprite_flush","sprite_flush_multi","sprite_get_bbox_bottom","sprite_get_bbox_left","sprite_get_bbox_mode","sprite_get_bbox_right","sprite_get_bbox_top","sprite_get_height","sprite_get_info","sprite_get_name","sprite_get_nineslice","sprite_get_number","sprite_get_speed","sprite_get_speed_type","sprite_get_texture","sprite_get_tpe","sprite_get_uvs","sprite_get_width","sprite_get_xoffset","sprite_get_yoffset","sprite_merge","sprite_nineslice_create","sprite_prefetch","sprite_prefetch_multi","sprite_replace","sprite_save","sprite_save_strip","sprite_set_alpha_from_sprite","sprite_set_bbox","sprite_set_bbox_mode","sprite_set_cache_size","sprite_set_cache_size_ext","sprite_set_nineslice","sprite_set_offset","sprite_set_speed","sqr","sqrt","static_get","static_set","string","string_byte_at","string_byte_length","string_char_at","string_concat","string_concat_ext","string_copy","string_count","string_delete","string_digits","string_ends_with","string_ext","string_foreach","string_format","string_hash_to_newline","string_height","string_height_ext","string_insert","string_join","string_join_ext","string_last_pos","string_last_pos_ext","string_length","string_letters","string_lettersdigits","string_lower","string_ord_at","string_pos","string_pos_ext","string_repeat","string_replace","string_replace_all","string_set_byte_at","string_split","string_split_ext","string_starts_with","string_trim","string_trim_end","string_trim_start","string_upper","string_width","string_width_ext","struct_exists","struct_foreach","struct_get","struct_get_from_hash","struct_get_names","struct_names_count","struct_remove","struct_set","struct_set_from_hash","surface_copy","surface_copy_part","surface_create","surface_create_ext","surface_depth_disable","surface_exists","surface_format_is_supported","surface_free","surface_get_depth_disable","surface_get_format","surface_get_height","surface_get_target","surface_get_target_ext","surface_get_texture","surface_get_width","surface_getpixel","surface_getpixel_ext","surface_reset_target","surface_resize","surface_save","surface_save_part","surface_set_target","surface_set_target_ext","tag_get_asset_ids","tag_get_assets","tan","texture_debug_messages","texture_flush","texture_get_height","texture_get_texel_height","texture_get_texel_width","texture_get_uvs","texture_get_width","texture_global_scale","texture_is_ready","texture_prefetch","texture_set_stage","texturegroup_get_fonts","texturegroup_get_names","texturegroup_get_sprites","texturegroup_get_status","texturegroup_get_textures","texturegroup_get_tilesets","texturegroup_load","texturegroup_set_mode","texturegroup_unload","tile_get_empty","tile_get_flip","tile_get_index","tile_get_mirror","tile_get_rotate","tile_set_empty","tile_set_flip","tile_set_index","tile_set_mirror","tile_set_rotate","tilemap_clear","tilemap_get","tilemap_get_at_pixel","tilemap_get_cell_x_at_pixel","tilemap_get_cell_y_at_pixel","tilemap_get_frame","tilemap_get_global_mask","tilemap_get_height","tilemap_get_mask","tilemap_get_tile_height","tilemap_get_tile_width","tilemap_get_tileset","tilemap_get_width","tilemap_get_x","tilemap_get_y","tilemap_set","tilemap_set_at_pixel","tilemap_set_global_mask","tilemap_set_height","tilemap_set_mask","tilemap_set_width","tilemap_tileset","tilemap_x","tilemap_y","tileset_get_info","tileset_get_name","tileset_get_texture","tileset_get_uvs","time_bpm_to_seconds","time_seconds_to_bpm","time_source_create","time_source_destroy","time_source_exists","time_source_get_children","time_source_get_parent","time_source_get_period","time_source_get_reps_completed","time_source_get_reps_remaining","time_source_get_state","time_source_get_time_remaining","time_source_get_units","time_source_pause","time_source_reconfigure","time_source_reset","time_source_resume","time_source_start","time_source_stop","timeline_add","timeline_clear","timeline_delete","timeline_exists","timeline_get_name","timeline_max_moment","timeline_moment_add_script","timeline_moment_clear","timeline_size","typeof","url_get_domain","url_open","url_open_ext","url_open_full","uwp_device_touchscreen_available","uwp_livetile_badge_clear","uwp_livetile_badge_notification","uwp_livetile_notification_begin","uwp_livetile_notification_end","uwp_livetile_notification_expiry","uwp_livetile_notification_image_add","uwp_livetile_notification_secondary_begin","uwp_livetile_notification_tag","uwp_livetile_notification_template_add","uwp_livetile_notification_text_add","uwp_livetile_queue_enable","uwp_livetile_tile_clear","uwp_secondarytile_badge_clear","uwp_secondarytile_badge_notification","uwp_secondarytile_delete","uwp_secondarytile_pin","uwp_secondarytile_tile_clear","variable_clone","variable_get_hash","variable_global_exists","variable_global_get","variable_global_set","variable_instance_exists","variable_instance_get","variable_instance_get_names","variable_instance_names_count","variable_instance_set","variable_struct_exists","variable_struct_get","variable_struct_get_names","variable_struct_names_count","variable_struct_remove","variable_struct_set","vertex_argb","vertex_begin","vertex_color","vertex_colour","vertex_create_buffer","vertex_create_buffer_ext","vertex_create_buffer_from_buffer","vertex_create_buffer_from_buffer_ext","vertex_delete_buffer","vertex_end","vertex_float1","vertex_float2","vertex_float3","vertex_float4","vertex_format_add_color","vertex_format_add_colour","vertex_format_add_custom","vertex_format_add_normal","vertex_format_add_position","vertex_format_add_position_3d","vertex_format_add_texcoord","vertex_format_begin","vertex_format_delete","vertex_format_end","vertex_format_get_info","vertex_freeze","vertex_get_buffer_size","vertex_get_number","vertex_normal","vertex_position","vertex_position_3d","vertex_submit","vertex_submit_ext","vertex_texcoord","vertex_ubyte4","vertex_update_buffer_from_buffer","vertex_update_buffer_from_vertex","video_close","video_draw","video_enable_loop","video_get_duration","video_get_format","video_get_position","video_get_status","video_get_volume","video_is_looping","video_open","video_pause","video_resume","video_seek_to","video_set_volume","view_get_camera","view_get_hport","view_get_surface_id","view_get_visible","view_get_wport","view_get_xport","view_get_yport","view_set_camera","view_set_hport","view_set_surface_id","view_set_visible","view_set_wport","view_set_xport","view_set_yport","virtual_key_add","virtual_key_delete","virtual_key_hide","virtual_key_show","wallpaper_set_config","wallpaper_set_subscriptions","weak_ref_alive","weak_ref_any_alive","weak_ref_create","window_center","window_device","window_enable_borderless_fullscreen","window_get_borderless_fullscreen","window_get_caption","window_get_color","window_get_colour","window_get_cursor","window_get_fullscreen","window_get_height","window_get_showborder","window_get_visible_rects","window_get_width","window_get_x","window_get_y","window_handle","window_has_focus","window_mouse_get_delta_x","window_mouse_get_delta_y","window_mouse_get_locked","window_mouse_get_x","window_mouse_get_y","window_mouse_set","window_mouse_set_locked","window_set_caption","window_set_color","window_set_colour","window_set_cursor","window_set_fullscreen","window_set_max_height","window_set_max_width","window_set_min_height","window_set_min_width","window_set_position","window_set_rectangle","window_set_showborder","window_set_size","window_view_mouse_get_x","window_view_mouse_get_y","window_views_mouse_get_x","window_views_mouse_get_y","winphone_tile_background_color","winphone_tile_background_colour","zip_add_file","zip_create","zip_save","zip_unzip","zip_unzip_async"],symbol:["AudioEffect","AudioEffectType","AudioLFOType","GM_build_date","GM_build_type","GM_is_sandboxed","GM_project_filename","GM_runtime_version","GM_version","NaN","_GMFILE_","_GMFUNCTION_","_GMLINE_","alignmentH","alignmentV","all","animcurvetype_bezier","animcurvetype_catmullrom","animcurvetype_linear","asset_animationcurve","asset_font","asset_object","asset_path","asset_room","asset_script","asset_sequence","asset_shader","asset_sound","asset_sprite","asset_tiles","asset_timeline","asset_unknown","audio_3D","audio_bus_main","audio_falloff_exponent_distance","audio_falloff_exponent_distance_clamped","audio_falloff_exponent_distance_scaled","audio_falloff_inverse_distance","audio_falloff_inverse_distance_clamped","audio_falloff_inverse_distance_scaled","audio_falloff_linear_distance","audio_falloff_linear_distance_clamped","audio_falloff_none","audio_mono","audio_stereo","bboxkind_diamond","bboxkind_ellipse","bboxkind_precise","bboxkind_rectangular","bboxmode_automatic","bboxmode_fullimage","bboxmode_manual","bm_add","bm_dest_alpha","bm_dest_color","bm_dest_colour","bm_inv_dest_alpha","bm_inv_dest_color","bm_inv_dest_colour","bm_inv_src_alpha","bm_inv_src_color","bm_inv_src_colour","bm_max","bm_normal","bm_one","bm_src_alpha","bm_src_alpha_sat","bm_src_color","bm_src_colour","bm_subtract","bm_zero","browser_chrome","browser_edge","browser_firefox","browser_ie","browser_ie_mobile","browser_not_a_browser","browser_opera","browser_safari","browser_safari_mobile","browser_tizen","browser_unknown","browser_windows_store","buffer_bool","buffer_f16","buffer_f32","buffer_f64","buffer_fast","buffer_fixed","buffer_grow","buffer_s16","buffer_s32","buffer_s8","buffer_seek_end","buffer_seek_relative","buffer_seek_start","buffer_string","buffer_text","buffer_u16","buffer_u32","buffer_u64","buffer_u8","buffer_vbuffer","buffer_wrap","c_aqua","c_black","c_blue","c_dkgray","c_dkgrey","c_fuchsia","c_gray","c_green","c_grey","c_lime","c_ltgray","c_ltgrey","c_maroon","c_navy","c_olive","c_orange","c_purple","c_red","c_silver","c_teal","c_white","c_yellow","cache_directory","characterSpacing","cmpfunc_always","cmpfunc_equal","cmpfunc_greater","cmpfunc_greaterequal","cmpfunc_less","cmpfunc_lessequal","cmpfunc_never","cmpfunc_notequal","coreColor","coreColour","cr_appstart","cr_arrow","cr_beam","cr_cross","cr_default","cr_drag","cr_handpoint","cr_hourglass","cr_none","cr_size_all","cr_size_nesw","cr_size_ns","cr_size_nwse","cr_size_we","cr_uparrow","cull_clockwise","cull_counterclockwise","cull_noculling","device_emulator","device_ios_ipad","device_ios_ipad_retina","device_ios_iphone","device_ios_iphone5","device_ios_iphone6","device_ios_iphone6plus","device_ios_iphone_retina","device_ios_unknown","device_tablet","display_landscape","display_landscape_flipped","display_portrait","display_portrait_flipped","dll_cdecl","dll_stdcall","dropShadowEnabled","dropShadowEnabled","ds_type_grid","ds_type_list","ds_type_map","ds_type_priority","ds_type_queue","ds_type_stack","ef_cloud","ef_ellipse","ef_explosion","ef_firework","ef_flare","ef_rain","ef_ring","ef_smoke","ef_smokeup","ef_snow","ef_spark","ef_star","effectsEnabled","effectsEnabled","ev_alarm","ev_animation_end","ev_animation_event","ev_animation_update","ev_async_audio_playback","ev_async_audio_playback_ended","ev_async_audio_recording","ev_async_dialog","ev_async_push_notification","ev_async_save_load","ev_async_save_load","ev_async_social","ev_async_system_event","ev_async_web","ev_async_web_cloud","ev_async_web_iap","ev_async_web_image_load","ev_async_web_networking","ev_async_web_steam","ev_audio_playback","ev_audio_playback_ended","ev_audio_recording","ev_boundary","ev_boundary_view0","ev_boundary_view1","ev_boundary_view2","ev_boundary_view3","ev_boundary_view4","ev_boundary_view5","ev_boundary_view6","ev_boundary_view7","ev_broadcast_message","ev_cleanup","ev_collision","ev_create","ev_destroy","ev_dialog_async","ev_draw","ev_draw_begin","ev_draw_end","ev_draw_normal","ev_draw_post","ev_draw_pre","ev_end_of_path","ev_game_end","ev_game_start","ev_gesture","ev_gesture_double_tap","ev_gesture_drag_end","ev_gesture_drag_start","ev_gesture_dragging","ev_gesture_flick","ev_gesture_pinch_end","ev_gesture_pinch_in","ev_gesture_pinch_out","ev_gesture_pinch_start","ev_gesture_rotate_end","ev_gesture_rotate_start","ev_gesture_rotating","ev_gesture_tap","ev_global_gesture_double_tap","ev_global_gesture_drag_end","ev_global_gesture_drag_start","ev_global_gesture_dragging","ev_global_gesture_flick","ev_global_gesture_pinch_end","ev_global_gesture_pinch_in","ev_global_gesture_pinch_out","ev_global_gesture_pinch_start","ev_global_gesture_rotate_end","ev_global_gesture_rotate_start","ev_global_gesture_rotating","ev_global_gesture_tap","ev_global_left_button","ev_global_left_press","ev_global_left_release","ev_global_middle_button","ev_global_middle_press","ev_global_middle_release","ev_global_right_button","ev_global_right_press","ev_global_right_release","ev_gui","ev_gui_begin","ev_gui_end","ev_joystick1_button1","ev_joystick1_button2","ev_joystick1_button3","ev_joystick1_button4","ev_joystick1_button5","ev_joystick1_button6","ev_joystick1_button7","ev_joystick1_button8","ev_joystick1_down","ev_joystick1_left","ev_joystick1_right","ev_joystick1_up","ev_joystick2_button1","ev_joystick2_button2","ev_joystick2_button3","ev_joystick2_button4","ev_joystick2_button5","ev_joystick2_button6","ev_joystick2_button7","ev_joystick2_button8","ev_joystick2_down","ev_joystick2_left","ev_joystick2_right","ev_joystick2_up","ev_keyboard","ev_keypress","ev_keyrelease","ev_left_button","ev_left_press","ev_left_release","ev_middle_button","ev_middle_press","ev_middle_release","ev_mouse","ev_mouse_enter","ev_mouse_leave","ev_mouse_wheel_down","ev_mouse_wheel_up","ev_no_button","ev_no_more_health","ev_no_more_lives","ev_other","ev_outside","ev_outside_view0","ev_outside_view1","ev_outside_view2","ev_outside_view3","ev_outside_view4","ev_outside_view5","ev_outside_view6","ev_outside_view7","ev_pre_create","ev_push_notification","ev_right_button","ev_right_press","ev_right_release","ev_room_end","ev_room_start","ev_social","ev_step","ev_step_begin","ev_step_end","ev_step_normal","ev_system_event","ev_trigger","ev_user0","ev_user1","ev_user10","ev_user11","ev_user12","ev_user13","ev_user14","ev_user15","ev_user2","ev_user3","ev_user4","ev_user5","ev_user6","ev_user7","ev_user8","ev_user9","ev_web_async","ev_web_cloud","ev_web_iap","ev_web_image_load","ev_web_networking","ev_web_sound_load","ev_web_steam","fa_archive","fa_bottom","fa_center","fa_directory","fa_hidden","fa_left","fa_middle","fa_none","fa_readonly","fa_right","fa_sysfile","fa_top","fa_volumeid","false","frameSizeX","frameSizeY","gamespeed_fps","gamespeed_microseconds","global","glowColor","glowColour","glowEnabled","glowEnabled","glowEnd","glowStart","gp_axis_acceleration_x","gp_axis_acceleration_y","gp_axis_acceleration_z","gp_axis_angular_velocity_x","gp_axis_angular_velocity_y","gp_axis_angular_velocity_z","gp_axis_orientation_w","gp_axis_orientation_x","gp_axis_orientation_y","gp_axis_orientation_z","gp_axislh","gp_axislv","gp_axisrh","gp_axisrv","gp_face1","gp_face2","gp_face3","gp_face4","gp_padd","gp_padl","gp_padr","gp_padu","gp_select","gp_shoulderl","gp_shoulderlb","gp_shoulderr","gp_shoulderrb","gp_start","gp_stickl","gp_stickr","iap_available","iap_canceled","iap_ev_consume","iap_ev_product","iap_ev_purchase","iap_ev_restore","iap_ev_storeload","iap_failed","iap_purchased","iap_refunded","iap_status_available","iap_status_loading","iap_status_processing","iap_status_restoring","iap_status_unavailable","iap_status_uninitialised","iap_storeload_failed","iap_storeload_ok","iap_unavailable","infinity","kbv_autocapitalize_characters","kbv_autocapitalize_none","kbv_autocapitalize_sentences","kbv_autocapitalize_words","kbv_returnkey_continue","kbv_returnkey_default","kbv_returnkey_done","kbv_returnkey_emergency","kbv_returnkey_go","kbv_returnkey_google","kbv_returnkey_join","kbv_returnkey_next","kbv_returnkey_route","kbv_returnkey_search","kbv_returnkey_send","kbv_returnkey_yahoo","kbv_type_ascii","kbv_type_default","kbv_type_email","kbv_type_numbers","kbv_type_phone","kbv_type_phone_name","kbv_type_url","layerelementtype_background","layerelementtype_instance","layerelementtype_oldtilemap","layerelementtype_particlesystem","layerelementtype_sequence","layerelementtype_sprite","layerelementtype_tile","layerelementtype_tilemap","layerelementtype_undefined","leaderboard_type_number","leaderboard_type_time_mins_secs","lighttype_dir","lighttype_point","lineSpacing","m_axisx","m_axisx_gui","m_axisy","m_axisy_gui","m_scroll_down","m_scroll_up","matrix_projection","matrix_view","matrix_world","mb_any","mb_left","mb_middle","mb_none","mb_right","mb_side1","mb_side2","mip_markedonly","mip_off","mip_on","network_config_avoid_time_wait","network_config_connect_timeout","network_config_disable_multicast","network_config_disable_reliable_udp","network_config_enable_multicast","network_config_enable_reliable_udp","network_config_use_non_blocking_socket","network_config_websocket_protocol","network_connect_active","network_connect_blocking","network_connect_nonblocking","network_connect_none","network_connect_passive","network_send_binary","network_send_text","network_socket_bluetooth","network_socket_tcp","network_socket_udp","network_socket_ws","network_socket_wss","network_type_connect","network_type_data","network_type_disconnect","network_type_down","network_type_non_blocking_connect","network_type_up","network_type_up_failed","nineslice_blank","nineslice_bottom","nineslice_center","nineslice_centre","nineslice_hide","nineslice_left","nineslice_mirror","nineslice_repeat","nineslice_right","nineslice_stretch","nineslice_top","noone","of_challenge_lose","of_challenge_tie","of_challenge_win","os_android","os_gdk","os_gxgames","os_ios","os_linux","os_macosx","os_operagx","os_permission_denied","os_permission_denied_dont_request","os_permission_granted","os_ps3","os_ps4","os_ps5","os_psvita","os_switch","os_tvos","os_unknown","os_uwp","os_win8native","os_windows","os_winphone","os_xboxone","os_xboxseriesxs","other","outlineColor","outlineColour","outlineDist","outlineEnabled","outlineEnabled","paragraphSpacing","path_action_continue","path_action_restart","path_action_reverse","path_action_stop","phy_debug_render_aabb","phy_debug_render_collision_pairs","phy_debug_render_coms","phy_debug_render_core_shapes","phy_debug_render_joints","phy_debug_render_obb","phy_debug_render_shapes","phy_joint_anchor_1_x","phy_joint_anchor_1_y","phy_joint_anchor_2_x","phy_joint_anchor_2_y","phy_joint_angle","phy_joint_angle_limits","phy_joint_damping_ratio","phy_joint_frequency","phy_joint_length_1","phy_joint_length_2","phy_joint_lower_angle_limit","phy_joint_max_force","phy_joint_max_length","phy_joint_max_motor_force","phy_joint_max_motor_torque","phy_joint_max_torque","phy_joint_motor_force","phy_joint_motor_speed","phy_joint_motor_torque","phy_joint_reaction_force_x","phy_joint_reaction_force_y","phy_joint_reaction_torque","phy_joint_speed","phy_joint_translation","phy_joint_upper_angle_limit","phy_particle_data_flag_category","phy_particle_data_flag_color","phy_particle_data_flag_colour","phy_particle_data_flag_position","phy_particle_data_flag_typeflags","phy_particle_data_flag_velocity","phy_particle_flag_colormixing","phy_particle_flag_colourmixing","phy_particle_flag_elastic","phy_particle_flag_powder","phy_particle_flag_spring","phy_particle_flag_tensile","phy_particle_flag_viscous","phy_particle_flag_wall","phy_particle_flag_water","phy_particle_flag_zombie","phy_particle_group_flag_rigid","phy_particle_group_flag_solid","pi","pointer_invalid","pointer_null","pr_linelist","pr_linestrip","pr_pointlist","pr_trianglefan","pr_trianglelist","pr_trianglestrip","ps_distr_gaussian","ps_distr_invgaussian","ps_distr_linear","ps_mode_burst","ps_mode_stream","ps_shape_diamond","ps_shape_ellipse","ps_shape_line","ps_shape_rectangle","pt_shape_circle","pt_shape_cloud","pt_shape_disk","pt_shape_explosion","pt_shape_flare","pt_shape_line","pt_shape_pixel","pt_shape_ring","pt_shape_smoke","pt_shape_snow","pt_shape_spark","pt_shape_sphere","pt_shape_square","pt_shape_star","rollback_chat_message","rollback_connect_error","rollback_connect_info","rollback_connected_to_peer","rollback_connection_rejected","rollback_disconnected_from_peer","rollback_end_game","rollback_game_full","rollback_game_info","rollback_game_interrupted","rollback_game_resumed","rollback_high_latency","rollback_player_prefs","rollback_protocol_rejected","rollback_synchronized_with_peer","rollback_synchronizing_with_peer","self","seqaudiokey_loop","seqaudiokey_oneshot","seqdir_left","seqdir_right","seqinterpolation_assign","seqinterpolation_lerp","seqplay_loop","seqplay_oneshot","seqplay_pingpong","seqtextkey_bottom","seqtextkey_center","seqtextkey_justify","seqtextkey_left","seqtextkey_middle","seqtextkey_right","seqtextkey_top","seqtracktype_audio","seqtracktype_bool","seqtracktype_clipmask","seqtracktype_clipmask_mask","seqtracktype_clipmask_subject","seqtracktype_color","seqtracktype_colour","seqtracktype_empty","seqtracktype_graphic","seqtracktype_group","seqtracktype_instance","seqtracktype_message","seqtracktype_moment","seqtracktype_particlesystem","seqtracktype_real","seqtracktype_sequence","seqtracktype_spriteframes","seqtracktype_string","seqtracktype_text","shadowColor","shadowColour","shadowOffsetX","shadowOffsetY","shadowSoftness","sprite_add_ext_error_cancelled","sprite_add_ext_error_decompressfailed","sprite_add_ext_error_loadfailed","sprite_add_ext_error_setupfailed","sprite_add_ext_error_spritenotfound","sprite_add_ext_error_unknown","spritespeed_framespergameframe","spritespeed_framespersecond","surface_r16float","surface_r32float","surface_r8unorm","surface_rg8unorm","surface_rgba16float","surface_rgba32float","surface_rgba4unorm","surface_rgba8unorm","texturegroup_status_fetched","texturegroup_status_loaded","texturegroup_status_loading","texturegroup_status_unloaded","tf_anisotropic","tf_linear","tf_point","thickness","tile_flip","tile_index_mask","tile_mirror","tile_rotate","time_source_expire_after","time_source_expire_nearest","time_source_game","time_source_global","time_source_state_active","time_source_state_initial","time_source_state_paused","time_source_state_stopped","time_source_units_frames","time_source_units_seconds","timezone_local","timezone_utc","tm_countvsyncs","tm_sleep","tm_systemtiming","true","ty_real","ty_string","undefined","vertex_type_color","vertex_type_colour","vertex_type_float1","vertex_type_float2","vertex_type_float3","vertex_type_float4","vertex_type_ubyte4","vertex_usage_binormal","vertex_usage_blendindices","vertex_usage_blendweight","vertex_usage_color","vertex_usage_colour","vertex_usage_depth","vertex_usage_fog","vertex_usage_normal","vertex_usage_position","vertex_usage_psize","vertex_usage_sample","vertex_usage_tangent","vertex_usage_texcoord","video_format_rgba","video_format_yuv","video_status_closed","video_status_paused","video_status_playing","video_status_preparing","vk_add","vk_alt","vk_anykey","vk_backspace","vk_control","vk_decimal","vk_delete","vk_divide","vk_down","vk_end","vk_enter","vk_escape","vk_f1","vk_f10","vk_f11","vk_f12","vk_f2","vk_f3","vk_f4","vk_f5","vk_f6","vk_f7","vk_f8","vk_f9","vk_home","vk_insert","vk_lalt","vk_lcontrol","vk_left","vk_lshift","vk_multiply","vk_nokey","vk_numpad0","vk_numpad1","vk_numpad2","vk_numpad3","vk_numpad4","vk_numpad5","vk_numpad6","vk_numpad7","vk_numpad8","vk_numpad9","vk_pagedown","vk_pageup","vk_pause","vk_printscreen","vk_ralt","vk_rcontrol","vk_return","vk_right","vk_rshift","vk_shift","vk_space","vk_subtract","vk_tab","vk_up","wallpaper_config","wallpaper_subscription_data","wrap"],"variable.language":["alarm","application_surface","argument","argument0","argument1","argument2","argument3","argument4","argument5","argument6","argument7","argument8","argument9","argument10","argument11","argument12","argument13","argument14","argument15","argument_count","async_load","background_color","background_colour","background_showcolor","background_showcolour","bbox_bottom","bbox_left","bbox_right","bbox_top","browser_height","browser_width","colour?ColourTrack","current_day","current_hour","current_minute","current_month","current_second","current_time","current_weekday","current_year","cursor_sprite","debug_mode","delta_time","depth","direction","display_aa","drawn_by_sequence","event_action","event_data","event_number","event_object","event_type","font_texture_page_size","fps","fps_real","friction","game_display_name","game_id","game_project_name","game_save_id","gravity","gravity_direction","health","hspeed","iap_data","id","image_alpha","image_angle","image_blend","image_index","image_number","image_speed","image_xscale","image_yscale","in_collision_tree","in_sequence","instance_count","instance_id","keyboard_key","keyboard_lastchar","keyboard_lastkey","keyboard_string","layer","lives","longMessage","managed","mask_index","message","mouse_button","mouse_lastbutton","mouse_x","mouse_y","object_index","os_browser","os_device","os_type","os_version","path_endaction","path_index","path_orientation","path_position","path_positionprevious","path_scale","path_speed","persistent","phy_active","phy_angular_damping","phy_angular_velocity","phy_bullet","phy_col_normal_x","phy_col_normal_y","phy_collision_points","phy_collision_x","phy_collision_y","phy_com_x","phy_com_y","phy_dynamic","phy_fixed_rotation","phy_inertia","phy_kinematic","phy_linear_damping","phy_linear_velocity_x","phy_linear_velocity_y","phy_mass","phy_position_x","phy_position_xprevious","phy_position_y","phy_position_yprevious","phy_rotation","phy_sleeping","phy_speed","phy_speed_x","phy_speed_y","player_avatar_sprite","player_avatar_url","player_id","player_local","player_type","player_user_id","program_directory","rollback_api_server","rollback_confirmed_frame","rollback_current_frame","rollback_event_id","rollback_event_param","rollback_game_running","room","room_first","room_height","room_last","room_persistent","room_speed","room_width","score","script","sequence_instance","solid","speed","sprite_height","sprite_index","sprite_width","sprite_xoffset","sprite_yoffset","stacktrace","temp_directory","timeline_index","timeline_loop","timeline_position","timeline_running","timeline_speed","view_camera","view_current","view_enabled","view_hport","view_surface_id","view_visible","view_wport","view_xport","view_yport","visible","vspeed","webgl_enabled","working_directory","x","xprevious","xstart","y","yprevious","ystart"]},contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE]}}),c_)),zf.registerLanguage("go",(p_||(p_=1,u_=function(e){const t={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:t,illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"string",variants:[e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[e.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,illegal:/["']/}]}]}}),u_)),zf.registerLanguage("golo",(m_||(m_=1,__=function(e){return{name:"Golo",keywords:{keyword:["println","readln","print","import","module","function","local","return","let","var","while","for","foreach","times","in","case","when","match","with","break","continue","augment","augmentation","each","find","filter","reduce","if","then","else","otherwise","try","catch","finally","raise","throw","orIfNull","DynamicObject|10","DynamicVariable","struct","Observable","map","set","vector","list","array"],literal:["true","false","null"]},contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,{className:"meta",begin:"@[A-Za-z]+"}]}}),__)),zf.registerLanguage("gradle",(h_||(h_=1,g_=function(e){return{name:"Gradle",case_insensitive:!0,keywords:["task","project","allprojects","subprojects","artifacts","buildscript","configurations","dependencies","repositories","sourceSets","description","delete","from","into","include","exclude","source","classpath","destinationDir","includes","options","sourceCompatibility","targetCompatibility","group","flatDir","doLast","doFirst","flatten","todir","fromdir","ant","def","abstract","break","case","catch","continue","default","do","else","extends","final","finally","for","if","implements","instanceof","native","new","private","protected","public","return","static","switch","synchronized","throw","throws","transient","try","volatile","while","strictfp","package","import","false","null","super","this","true","antlrtask","checkstyle","codenarc","copy","boolean","byte","char","class","double","float","int","interface","long","short","void","compile","runTime","file","fileTree","abs","any","append","asList","asWritable","call","collect","compareTo","count","div","dump","each","eachByte","eachFile","eachLine","every","find","findAll","flatten","getAt","getErr","getIn","getOut","getText","grep","immutable","inject","inspect","intersect","invokeMethods","isCase","join","leftShift","minus","multiply","newInputStream","newOutputStream","newPrintWriter","newReader","newWriter","next","plus","pop","power","previous","print","println","push","putAt","read","readBytes","readLines","reverse","reverseEach","round","size","sort","splitEachLine","step","subMap","times","toInteger","toList","tokenize","upto","waitForOrKill","withPrintWriter","withReader","withStream","withWriter","withWriterAppend","write","writeLine"],contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,e.REGEXP_MODE]}}),g_)),zf.registerLanguage("graphql",(E_||(E_=1,f_=function(e){const t=e.regex;return{name:"GraphQL",aliases:["gql"],case_insensitive:!0,disableAutodetect:!1,keywords:{keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"],literal:["true","false","null"]},contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation",begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/,end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{scope:"symbol",begin:t.concat(/[_A-Za-z][_0-9A-Za-z]*/,t.lookahead(/\s*:/)),relevance:0}],illegal:[/[;<']/,/BEGIN/]}}),f_)),zf.registerLanguage("groovy",function(){if(S_)return b_;function e(e,t={}){return t.variants=e,t}return S_=1,b_=function(t){const r=t.regex,n="[A-Za-z0-9_$]+",a=e([t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,t.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]})]),i={className:"regexp",begin:/~?\/[^\/\n]+\//,contains:[t.BACKSLASH_ESCAPE]},o=e([t.BINARY_NUMBER_MODE,t.C_NUMBER_MODE]),s=e([{begin:/"""/,end:/"""/},{begin:/'''/,end:/'''/},{begin:"\\$/",end:"/\\$",relevance:10},t.APOS_STRING_MODE,t.QUOTE_STRING_MODE],{className:"string"}),l={match:[/(class|interface|trait|enum|record|extends|implements)/,/\s+/,t.UNDERSCORE_IDENT_RE],scope:{1:"keyword",3:"title.class"}};return{name:"Groovy",keywords:{"variable.language":"this super",literal:"true false null",type:["byte","short","char","int","long","boolean","float","double","void"],keyword:["def","as","in","assert","trait","abstract","static","volatile","transient","public","private","protected","synchronized","final","class","interface","enum","if","else","for","while","switch","case","break","default","continue","throw","throws","try","catch","finally","implements","extends","new","import","package","return","instanceof","var"]},contains:[t.SHEBANG({binary:"groovy",relevance:10}),a,s,i,o,l,{className:"meta",begin:"@[A-Za-z]+",relevance:0},{className:"attr",begin:n+"[ \t]*:",relevance:0},{begin:/\?/,end:/:/,relevance:0,contains:[a,s,i,o,"self"]},{className:"symbol",begin:"^[ \t]*"+r.lookahead(n+":"),excludeBegin:!0,end:n+":",relevance:0}],illegal:/#|<\//}},b_}()),zf.registerLanguage("haml",(T_||(T_=1,v_=function(e){return{name:"HAML",case_insensitive:!0,contains:[{className:"meta",begin:"^!!!( (5|1\\.1|Strict|Frameset|Basic|Mobile|RDFa|XML\\b.*))?$",relevance:10},e.COMMENT("^\\s*(!=#|=#|-#|/).*$",null,{relevance:0}),{begin:"^\\s*(-|=|!=)(?!#)",end:/$/,subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0},{className:"tag",begin:"^\\s*%",contains:[{className:"selector-tag",begin:"\\w+"},{className:"selector-id",begin:"#[\\w-]+"},{className:"selector-class",begin:"\\.[\\w-]+"},{begin:/\{\s*/,end:/\s*\}/,contains:[{begin:":\\w+\\s*=>",end:",\\s+",returnBegin:!0,endsWithParent:!0,contains:[{className:"attr",begin:":\\w+"},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{begin:"\\w+",relevance:0}]}]},{begin:"\\(\\s*",end:"\\s*\\)",excludeEnd:!0,contains:[{begin:"\\w+\\s*=",end:"\\s+",returnBegin:!0,endsWithParent:!0,contains:[{className:"attr",begin:"\\w+",relevance:0},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{begin:"\\w+",relevance:0}]}]}]},{begin:"^\\s*[=~]\\s*"},{begin:/#\{/,end:/\}/,subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0}]}}),v_)),zf.registerLanguage("handlebars",(C_||(C_=1,y_=function(e){const t=e.regex,r={$pattern:/[\w.\/]+/,built_in:["action","bindattr","collection","component","concat","debugger","each","each-in","get","hash","if","in","input","link-to","loc","log","lookup","mut","outlet","partial","query-params","render","template","textarea","unbound","unless","view","with","yield"]},n=/\[\]|\[[^\]]+\]/,a=/[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/,i=t.either(/""|"[^"]+"/,/''|'[^']+'/,n,a),o=t.concat(t.optional(/\.|\.\/|\//),i,t.anyNumberOfTimes(t.concat(/(\.|\/)/,i))),s=t.concat("(",n,"|",a,")(?==)"),l={begin:o},c=e.inherit(l,{keywords:{$pattern:/[\w.\/]+/,literal:["true","false","undefined","null"]}}),d={begin:/\(/,end:/\)/},u={className:"attr",begin:s,relevance:0,starts:{begin:/=/,end:/=/,starts:{contains:[e.NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,c,d]}}},p={contains:[e.NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{begin:/as\s+\|/,keywords:{keyword:"as"},end:/\|/,contains:[{begin:/\w+/}]},u,c,d],returnEnd:!0},_=e.inherit(l,{className:"name",keywords:r,starts:e.inherit(p,{end:/\)/})});d.contains=[_];const m=e.inherit(l,{keywords:r,className:"name",starts:e.inherit(p,{end:/\}\}/})}),g=e.inherit(l,{keywords:r,className:"name"}),h=e.inherit(l,{className:"name",keywords:r,starts:e.inherit(p,{end:/\}\}/})});return{name:"Handlebars",aliases:["hbs","html.hbs","html.handlebars","htmlbars"],case_insensitive:!0,subLanguage:"xml",contains:[{begin:/\\\{\{/,skip:!0},{begin:/\\\\(?=\{\{)/,skip:!0},e.COMMENT(/\{\{!--/,/--\}\}/),e.COMMENT(/\{\{!/,/\}\}/),{className:"template-tag",begin:/\{\{\{\{(?!\/)/,end:/\}\}\}\}/,contains:[m],starts:{end:/\{\{\{\{\//,returnEnd:!0,subLanguage:"xml"}},{className:"template-tag",begin:/\{\{\{\{\//,end:/\}\}\}\}/,contains:[g]},{className:"template-tag",begin:/\{\{#/,end:/\}\}/,contains:[m]},{className:"template-tag",begin:/\{\{(?=else\}\})/,end:/\}\}/,keywords:"else"},{className:"template-tag",begin:/\{\{(?=else if)/,end:/\}\}/,keywords:"else if"},{className:"template-tag",begin:/\{\{\//,end:/\}\}/,contains:[g]},{className:"template-variable",begin:/\{\{\{/,end:/\}\}\}/,contains:[h]},{className:"template-variable",begin:/\{\{/,end:/\}\}/,contains:[h]}]}}),y_)),zf.registerLanguage("haskell",(R_||(R_=1,N_=function(e){const t="([0-9]_*)+",r="([0-9a-fA-F]_*)+",n="([!#$%&*+.\\/<=>?@\\\\^~-]|(?!([(),;\\[\\]`|{}]|[_:\"']))(\\p{S}|\\p{P}))",a={variants:[e.COMMENT("--+","$"),e.COMMENT(/\{-/,/-\}/,{contains:["self"]})]},i={className:"meta",begin:/\{-#/,end:/#-\}/},o={className:"meta",begin:"^#",end:"$"},s={className:"type",begin:"\\b[A-Z][\\w']*",relevance:0},l={begin:"\\(",end:"\\)",illegal:'"',contains:[i,o,{className:"type",begin:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},e.inherit(e.TITLE_MODE,{begin:"[_a-z][\\w']*"}),a]},c={className:"number",relevance:0,variants:[{match:`\\b(${t})(\\.(${t}))?([eE][+-]?(${t}))?\\b`},{match:`\\b0[xX]_*(${r})(\\.(${r}))?([pP][+-]?(${t}))?\\b`},{match:"\\b0[oO](([0-7]_*)+)\\b"},{match:"\\b0[bB](([01]_*)+)\\b"}]};return{name:"Haskell",aliases:["hs"],keywords:"let in if then else case of where do module import hiding qualified type data newtype deriving class instance as default infix infixl infixr foreign export ccall stdcall cplusplus jvm dotnet safe unsafe family forall mdo proc rec",unicodeRegex:!0,contains:[{beginKeywords:"module",end:"where",keywords:"module where",contains:[l,a],illegal:"\\W\\.|;"},{begin:"\\bimport\\b",end:"$",keywords:"import qualified as hiding",contains:[l,a],illegal:"\\W\\.|;"},{className:"class",begin:"^(\\s*)?(class|instance)\\b",end:"where",keywords:"class family instance where",contains:[s,l,a]},{className:"class",begin:"\\b(data|(new)?type)\\b",end:"$",keywords:"data family type newtype deriving",contains:[i,s,l,{begin:/\{/,end:/\}/,contains:l.contains},a]},{beginKeywords:"default",end:"$",contains:[s,l,a]},{beginKeywords:"infix infixl infixr",end:"$",contains:[e.C_NUMBER_MODE,a]},{begin:"\\bforeign\\b",end:"$",keywords:"foreign import export ccall stdcall cplusplus jvm dotnet safe unsafe",contains:[s,e.QUOTE_STRING_MODE,a]},{className:"meta",begin:"#!\\/usr\\/bin\\/env runhaskell",end:"$"},i,o,{scope:"string",begin:/'(?=\\?.')/,end:/'/,contains:[{scope:"char.escape",match:/\\./}]},e.QUOTE_STRING_MODE,c,s,e.inherit(e.TITLE_MODE,{begin:"^[_a-z][\\w']*"}),{begin:`(?!-)${n}--+|--+(?!-)${n}`},a,{begin:"->|<-"}]}}),N_)),zf.registerLanguage("haxe",(O_||(O_=1,A_=function(e){return{name:"Haxe",aliases:["hx"],keywords:{keyword:"abstract break case cast catch continue default do dynamic else enum extern final for function here if import in inline is macro never new override package private get set public return static super switch this throw trace try typedef untyped using var while Int Float String Bool Dynamic Void Array ",built_in:"trace this",literal:"true false null _"},contains:[{className:"string",begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE,{className:"subst",begin:/\$\{/,end:/\}/},{className:"subst",begin:/\$/,end:/\W\}/}]},e.QUOTE_STRING_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"number",begin:/(-?)(\b0[xX][a-fA-F0-9_]+|(\b\d+(\.[\d_]*)?|\.[\d_]+)(([eE][-+]?\d+)|i32|u32|i64|f64)?)/,relevance:0},{className:"variable",begin:"\\$[a-zA-Z_$][a-zA-Z0-9_$]*"},{className:"meta",begin:/@:?/,end:/\(|$/,excludeEnd:!0},{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elseif end error"}},{className:"type",begin:/:[ \t]*/,end:/[^A-Za-z0-9_ \t\->]/,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/:[ \t]*/,end:/\W/,excludeBegin:!0,excludeEnd:!0},{className:"type",beginKeywords:"new",end:/\W/,excludeBegin:!0,excludeEnd:!0},{className:"title.class",beginKeywords:"enum",end:/\{/,contains:[e.TITLE_MODE]},{className:"title.class",begin:"\\babstract\\b(?=\\s*"+e.IDENT_RE+"\\s*\\()",end:/[\{$]/,contains:[{className:"type",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0},{className:"type",begin:/from +/,end:/\W/,excludeBegin:!0,excludeEnd:!0},{className:"type",begin:/to +/,end:/\W/,excludeBegin:!0,excludeEnd:!0},e.TITLE_MODE],keywords:{keyword:"abstract from to"}},{className:"title.class",begin:/\b(class|interface) +/,end:/[\{$]/,excludeEnd:!0,keywords:"class interface",contains:[{className:"keyword",begin:/\b(extends|implements) +/,keywords:"extends implements",contains:[{className:"type",begin:e.IDENT_RE,relevance:0}]},e.TITLE_MODE]},{className:"title.function",beginKeywords:"function",end:/\(/,excludeEnd:!0,illegal:/\S/,contains:[e.TITLE_MODE]}],illegal:/<\//}}),A_)),zf.registerLanguage("hsp",(x_||(x_=1,I_=function(e){return{name:"HSP",case_insensitive:!0,keywords:{$pattern:/[\w._]+/,keyword:"goto gosub return break repeat loop continue wait await dim sdim foreach dimtype dup dupptr end stop newmod delmod mref run exgoto on mcall assert logmes newlab resume yield onexit onerror onkey onclick oncmd exist delete mkdir chdir dirlist bload bsave bcopy memfile if else poke wpoke lpoke getstr chdpm memexpand memcpy memset notesel noteadd notedel noteload notesave randomize noteunsel noteget split strrep setease button chgdisp exec dialog mmload mmplay mmstop mci pset pget syscolor mes print title pos circle cls font sysfont objsize picload color palcolor palette redraw width gsel gcopy gzoom gmode bmpsave hsvcolor getkey listbox chkbox combox input mesbox buffer screen bgscr mouse objsel groll line clrobj boxf objprm objmode stick grect grotate gsquare gradf objimage objskip objenable celload celdiv celput newcom querycom delcom cnvstow comres axobj winobj sendmsg comevent comevarg sarrayconv callfunc cnvwtos comevdisp libptr system hspstat hspver stat cnt err strsize looplev sublev iparam wparam lparam refstr refdval int rnd strlen length length2 length3 length4 vartype gettime peek wpeek lpeek varptr varuse noteinfo instr abs limit getease str strmid strf getpath strtrim sin cos tan atan sqrt double absf expf logf limitf powf geteasef mousex mousey mousew hwnd hinstance hdc ginfo objinfo dirinfo sysinfo thismod __hspver__ __hsp30__ __date__ __time__ __line__ __file__ _debug __hspdef__ and or xor not screen_normal screen_palette screen_hide screen_fixedsize screen_tool screen_frame gmode_gdi gmode_mem gmode_rgb0 gmode_alpha gmode_rgb0alpha gmode_add gmode_sub gmode_pixela ginfo_mx ginfo_my ginfo_act ginfo_sel ginfo_wx1 ginfo_wy1 ginfo_wx2 ginfo_wy2 ginfo_vx ginfo_vy ginfo_sizex ginfo_sizey ginfo_winx ginfo_winy ginfo_mesx ginfo_mesy ginfo_r ginfo_g ginfo_b ginfo_paluse ginfo_dispx ginfo_dispy ginfo_cx ginfo_cy ginfo_intid ginfo_newid ginfo_sx ginfo_sy objinfo_mode objinfo_bmscr objinfo_hwnd notemax notesize dir_cur dir_exe dir_win dir_sys dir_cmdline dir_desktop dir_mydoc dir_tv font_normal font_bold font_italic font_underline font_strikeout font_antialias objmode_normal objmode_guifont objmode_usefont gsquare_grad msgothic msmincho do until while wend for next _break _continue switch case default swbreak swend ddim ldim alloc m_pi rad2deg deg2rad ease_linear ease_quad_in ease_quad_out ease_quad_inout ease_cubic_in ease_cubic_out ease_cubic_inout ease_quartic_in ease_quartic_out ease_quartic_inout ease_bounce_in ease_bounce_out ease_bounce_inout ease_shake_in ease_shake_out ease_shake_inout ease_loop"},contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{className:"string",begin:/\{"/,end:/"\}/,contains:[e.BACKSLASH_ESCAPE]},e.COMMENT(";","$",{relevance:0}),{className:"meta",begin:"#",end:"$",keywords:{keyword:"addion cfunc cmd cmpopt comfunc const defcfunc deffunc define else endif enum epack func global if ifdef ifndef include modcfunc modfunc modinit modterm module pack packopt regcmd runtime undef usecom uselib"},contains:[e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),e.NUMBER_MODE,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"symbol",begin:"^\\*(\\w+|@)"},e.NUMBER_MODE,e.C_NUMBER_MODE]}}),I_)),zf.registerLanguage("http",(D_||(D_=1,w_=function(e){const t="HTTP/([32]|1\\.[01])",r={className:"attribute",begin:e.regex.concat("^",/[A-Za-z][A-Za-z0-9-]*/,"(?=\\:\\s)"),starts:{contains:[{className:"punctuation",begin:/: /,relevance:0,starts:{end:"$",relevance:0}}]}},n=[r,{begin:"\\n\\n",starts:{subLanguage:[],endsWithParent:!0}}];return{name:"HTTP",aliases:["https"],illegal:/\S/,contains:[{begin:"^(?="+t+" \\d{3})",end:/$/,contains:[{className:"meta",begin:t},{className:"number",begin:"\\b\\d{3}\\b"}],starts:{end:/\b\B/,illegal:/\S/,contains:n}},{begin:"(?=^[A-Z]+ (.*?) "+t+"$)",end:/$/,contains:[{className:"string",begin:" ",end:" ",excludeBegin:!0,excludeEnd:!0},{className:"meta",begin:t},{className:"keyword",begin:"[A-Z]+"}],starts:{end:/\b\B/,illegal:/\S/,contains:n}},e.inherit(r,{relevance:0})]}}),w_)),zf.registerLanguage("hy",(k_||(k_=1,M_=function(e){const t="a-zA-Z_\\-!.?+*=<>&#'",r="["+t+"]["+t+"0-9/;:]*",n={$pattern:r,built_in:"!= % %= & &= * ** **= *= *map + += , --build-class-- --import-- -= . / // //= /= < << <<= <= = > >= >> >>= @ @= ^ ^= abs accumulate all and any ap-compose ap-dotimes ap-each ap-each-while ap-filter ap-first ap-if ap-last ap-map ap-map-when ap-pipe ap-reduce ap-reject apply as-> ascii assert assoc bin break butlast callable calling-module-name car case cdr chain chr coll? combinations compile compress cond cons cons? continue count curry cut cycle dec def default-method defclass defmacro defmacro-alias defmacro/g! defmain defmethod defmulti defn defn-alias defnc defnr defreader defseq del delattr delete-route dict-comp dir disassemble dispatch-reader-macro distinct divmod do doto drop drop-last drop-while empty? end-sequence eval eval-and-compile eval-when-compile even? every? except exec filter first flatten float? fn fnc fnr for for* format fraction genexpr gensym get getattr global globals group-by hasattr hash hex id identity if if* if-not if-python2 import in inc input instance? integer integer-char? integer? interleave interpose is is-coll is-cons is-empty is-even is-every is-float is-instance is-integer is-integer-char is-iterable is-iterator is-keyword is-neg is-none is-not is-numeric is-odd is-pos is-string is-symbol is-zero isinstance islice issubclass iter iterable? iterate iterator? keyword keyword? lambda last len let lif lif-not list* list-comp locals loop macro-error macroexpand macroexpand-1 macroexpand-all map max merge-with method-decorator min multi-decorator multicombinations name neg? next none? nonlocal not not-in not? nth numeric? oct odd? open or ord partition permutations pos? post-route postwalk pow prewalk print product profile/calls profile/cpu put-route quasiquote quote raise range read read-str recursive-replace reduce remove repeat repeatedly repr require rest round route route-with-methods rwm second seq set-comp setattr setv some sorted string string? sum switch symbol? take take-nth take-while tee try unless unquote unquote-splicing vars walk when while with with* with-decorator with-gensyms xi xor yield yield-from zero? zip zip-longest | |= ~"},a={begin:r,relevance:0},i={className:"number",begin:"[-+]?\\d+(\\.\\d+)?",relevance:0},o=e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),s=e.COMMENT(";","$",{relevance:0}),l={className:"literal",begin:/\b([Tt]rue|[Ff]alse|nil|None)\b/},c={begin:"[\\[\\{]",end:"[\\]\\}]",relevance:0},d={className:"comment",begin:"\\^"+r},u=e.COMMENT("\\^\\{","\\}"),p={className:"symbol",begin:"[:]{1,2}"+r},_={begin:"\\(",end:"\\)"},m={endsWithParent:!0,relevance:0},g={className:"name",relevance:0,keywords:n,begin:r,starts:m},h=[_,o,d,u,s,p,c,i,l,a];return _.contains=[e.COMMENT("comment",""),g,m],m.contains=h,c.contains=h,{name:"Hy",aliases:["hylang"],illegal:/\S/,contains:[e.SHEBANG(),_,o,d,u,s,p,c,i,l]}}),M_)),zf.registerLanguage("inform7",P_?L_:(P_=1,L_=function(e){return{name:"Inform 7",aliases:["i7"],case_insensitive:!0,keywords:{keyword:"thing room person man woman animal container supporter backdrop door scenery open closed locked inside gender is are say understand kind of rule"},contains:[{className:"string",begin:'"',end:'"',relevance:0,contains:[{className:"subst",begin:"\\[",end:"\\]"}]},{className:"section",begin:/^(Volume|Book|Part|Chapter|Section|Table)\b/,end:"$"},{begin:/^(Check|Carry out|Report|Instead of|To|Rule|When|Before|After)\b/,end:":",contains:[{begin:"\\(This",end:"\\)"}]},{className:"comment",begin:"\\[",end:"\\]",contains:["self"]}]}})),zf.registerLanguage("ini",(B_||(B_=1,F_=function(e){const t=e.regex,r={className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{begin:e.NUMBER_RE}]},n=e.COMMENT();n.variants=[{begin:/;/,end:/$/},{begin:/#/,end:/$/}];const a={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{begin:/\$\{(.*?)\}/}]},i={className:"literal",begin:/\bon|off|true|false|yes|no\b/},o={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]},s={begin:/\[/,end:/\]/,contains:[n,i,a,o,r,"self"],relevance:0},l=t.either(/[A-Za-z0-9_-]+/,/"(\\"|[^"])*"/,/'[^']*'/);return{name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,contains:[n,{className:"section",begin:/\[+/,end:/\]+/},{begin:t.concat(l,"(\\s*\\.\\s*",l,")*",t.lookahead(/\s*=\s*[^#\s]/)),className:"attr",starts:{end:/$/,contains:[n,s,i,a,o,r]}}]}}),F_)),zf.registerLanguage("irpf90",(G_||(G_=1,U_=function(e){const t=e.regex,r=/(_[a-z_\d]+)?/,n=/([de][+-]?\d+)?/,a={className:"number",variants:[{begin:t.concat(/\b\d+/,/\.(\d*)/,n,r)},{begin:t.concat(/\b\d+/,n,r)},{begin:t.concat(/\.\d+/,n,r)}],relevance:0};return{name:"IRPF90",case_insensitive:!0,keywords:{literal:".False. .True.",keyword:"kind do while private call intrinsic where elsewhere type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. goto save else use module select case access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit continue format pause cycle exit c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg synchronous nopass non_overridable pass protected volatile abstract extends import non_intrinsic value deferred generic final enumerator class associate bind enum c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated c_f_pointer c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure integer real character complex logical dimension allocatable|10 parameter external implicit|10 none double precision assign intent optional pointer target in out common equivalence data begin_provider &begin_provider end_provider begin_shell end_shell begin_template end_template subst assert touch soft_touch provide no_dep free irp_if irp_else irp_endif irp_write irp_read",built_in:"alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr num_images parity popcnt poppar shifta shiftl shiftr this_image IRP_ALIGN irp_here"},illegal:/\/\*/,contains:[e.inherit(e.APOS_STRING_MODE,{className:"string",relevance:0}),e.inherit(e.QUOTE_STRING_MODE,{className:"string",relevance:0}),{className:"function",beginKeywords:"subroutine function program",illegal:"[${=\\n]",contains:[e.UNDERSCORE_TITLE_MODE,{className:"params",begin:"\\(",end:"\\)"}]},e.COMMENT("!","$",{relevance:0}),e.COMMENT("begin_doc","end_doc",{relevance:10}),a]}}),U_)),zf.registerLanguage("isbl",(Y_||(Y_=1,z_=function(e){const t="[A-Za-zА-Яа-яёЁ_!][A-Za-zА-Яа-яёЁ_0-9]*",r={className:"number",begin:e.NUMBER_RE,relevance:0},n={className:"string",variants:[{begin:'"',end:'"'},{begin:"'",end:"'"}]},a={className:"doctag",begin:"\\b(?:TODO|DONE|BEGIN|END|STUB|CHG|FIXME|NOTE|BUG|XXX)\\b",relevance:0},i={variants:[{className:"comment",begin:"//",end:"$",relevance:0,contains:[e.PHRASAL_WORDS_MODE,a]},{className:"comment",begin:"/\\*",end:"\\*/",relevance:0,contains:[e.PHRASAL_WORDS_MODE,a]}]},o={$pattern:t,keyword:"and и else иначе endexcept endfinally endforeach конецвсе endif конецесли endwhile конецпока except exitfor finally foreach все if если in в not не or или try while пока ",built_in:"SYSRES_CONST_ACCES_RIGHT_TYPE_EDIT SYSRES_CONST_ACCES_RIGHT_TYPE_FULL SYSRES_CONST_ACCES_RIGHT_TYPE_VIEW SYSRES_CONST_ACCESS_MODE_REQUISITE_CODE SYSRES_CONST_ACCESS_NO_ACCESS_VIEW SYSRES_CONST_ACCESS_NO_ACCESS_VIEW_CODE SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_RIGHTS_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_VIEW SYSRES_CONST_ACCESS_RIGHTS_VIEW_CODE SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_CODE SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_YES_CODE SYSRES_CONST_ACCESS_TYPE_CHANGE SYSRES_CONST_ACCESS_TYPE_CHANGE_CODE SYSRES_CONST_ACCESS_TYPE_EXISTS SYSRES_CONST_ACCESS_TYPE_EXISTS_CODE SYSRES_CONST_ACCESS_TYPE_FULL SYSRES_CONST_ACCESS_TYPE_FULL_CODE SYSRES_CONST_ACCESS_TYPE_VIEW SYSRES_CONST_ACCESS_TYPE_VIEW_CODE SYSRES_CONST_ACTION_TYPE_ABORT SYSRES_CONST_ACTION_TYPE_ACCEPT SYSRES_CONST_ACTION_TYPE_ACCESS_RIGHTS SYSRES_CONST_ACTION_TYPE_ADD_ATTACHMENT SYSRES_CONST_ACTION_TYPE_CHANGE_CARD SYSRES_CONST_ACTION_TYPE_CHANGE_KIND SYSRES_CONST_ACTION_TYPE_CHANGE_STORAGE SYSRES_CONST_ACTION_TYPE_CONTINUE SYSRES_CONST_ACTION_TYPE_COPY SYSRES_CONST_ACTION_TYPE_CREATE SYSRES_CONST_ACTION_TYPE_CREATE_VERSION SYSRES_CONST_ACTION_TYPE_DELETE SYSRES_CONST_ACTION_TYPE_DELETE_ATTACHMENT SYSRES_CONST_ACTION_TYPE_DELETE_VERSION SYSRES_CONST_ACTION_TYPE_DISABLE_DELEGATE_ACCESS_RIGHTS SYSRES_CONST_ACTION_TYPE_ENABLE_DELEGATE_ACCESS_RIGHTS SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE_AND_PASSWORD SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_PASSWORD SYSRES_CONST_ACTION_TYPE_EXPORT_WITH_LOCK SYSRES_CONST_ACTION_TYPE_EXPORT_WITHOUT_LOCK SYSRES_CONST_ACTION_TYPE_IMPORT_WITH_UNLOCK SYSRES_CONST_ACTION_TYPE_IMPORT_WITHOUT_UNLOCK SYSRES_CONST_ACTION_TYPE_LIFE_CYCLE_STAGE SYSRES_CONST_ACTION_TYPE_LOCK SYSRES_CONST_ACTION_TYPE_LOCK_FOR_SERVER SYSRES_CONST_ACTION_TYPE_LOCK_MODIFY SYSRES_CONST_ACTION_TYPE_MARK_AS_READED SYSRES_CONST_ACTION_TYPE_MARK_AS_UNREADED SYSRES_CONST_ACTION_TYPE_MODIFY SYSRES_CONST_ACTION_TYPE_MODIFY_CARD SYSRES_CONST_ACTION_TYPE_MOVE_TO_ARCHIVE SYSRES_CONST_ACTION_TYPE_OFF_ENCRYPTION SYSRES_CONST_ACTION_TYPE_PASSWORD_CHANGE SYSRES_CONST_ACTION_TYPE_PERFORM SYSRES_CONST_ACTION_TYPE_RECOVER_FROM_LOCAL_COPY SYSRES_CONST_ACTION_TYPE_RESTART SYSRES_CONST_ACTION_TYPE_RESTORE_FROM_ARCHIVE SYSRES_CONST_ACTION_TYPE_REVISION SYSRES_CONST_ACTION_TYPE_SEND_BY_MAIL SYSRES_CONST_ACTION_TYPE_SIGN SYSRES_CONST_ACTION_TYPE_START SYSRES_CONST_ACTION_TYPE_UNLOCK SYSRES_CONST_ACTION_TYPE_UNLOCK_FROM_SERVER SYSRES_CONST_ACTION_TYPE_VERSION_STATE SYSRES_CONST_ACTION_TYPE_VERSION_VISIBILITY SYSRES_CONST_ACTION_TYPE_VIEW SYSRES_CONST_ACTION_TYPE_VIEW_SHADOW_COPY SYSRES_CONST_ACTION_TYPE_WORKFLOW_DESCRIPTION_MODIFY SYSRES_CONST_ACTION_TYPE_WRITE_HISTORY SYSRES_CONST_ACTIVE_VERSION_STATE_PICK_VALUE SYSRES_CONST_ADD_REFERENCE_MODE_NAME SYSRES_CONST_ADDITION_REQUISITE_CODE SYSRES_CONST_ADDITIONAL_PARAMS_REQUISITE_CODE SYSRES_CONST_ADITIONAL_JOB_END_DATE_REQUISITE_NAME SYSRES_CONST_ADITIONAL_JOB_READ_REQUISITE_NAME SYSRES_CONST_ADITIONAL_JOB_START_DATE_REQUISITE_NAME SYSRES_CONST_ADITIONAL_JOB_STATE_REQUISITE_NAME SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION_CODE SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE_ACTION SYSRES_CONST_ALL_ACCEPT_CONDITION_RUS SYSRES_CONST_ALL_USERS_GROUP SYSRES_CONST_ALL_USERS_GROUP_NAME SYSRES_CONST_ALL_USERS_SERVER_GROUP_NAME SYSRES_CONST_ALLOWED_ACCESS_TYPE_CODE SYSRES_CONST_ALLOWED_ACCESS_TYPE_NAME SYSRES_CONST_APP_VIEWER_TYPE_REQUISITE_CODE SYSRES_CONST_APPROVING_SIGNATURE_NAME SYSRES_CONST_APPROVING_SIGNATURE_REQUISITE_CODE SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE_CODE SYSRES_CONST_ATTACH_TYPE_COMPONENT_TOKEN SYSRES_CONST_ATTACH_TYPE_DOC SYSRES_CONST_ATTACH_TYPE_EDOC SYSRES_CONST_ATTACH_TYPE_FOLDER SYSRES_CONST_ATTACH_TYPE_JOB SYSRES_CONST_ATTACH_TYPE_REFERENCE SYSRES_CONST_ATTACH_TYPE_TASK SYSRES_CONST_AUTH_ENCODED_PASSWORD SYSRES_CONST_AUTH_ENCODED_PASSWORD_CODE SYSRES_CONST_AUTH_NOVELL SYSRES_CONST_AUTH_PASSWORD SYSRES_CONST_AUTH_PASSWORD_CODE SYSRES_CONST_AUTH_WINDOWS SYSRES_CONST_AUTHENTICATING_SIGNATURE_NAME SYSRES_CONST_AUTHENTICATING_SIGNATURE_REQUISITE_CODE SYSRES_CONST_AUTO_ENUM_METHOD_FLAG SYSRES_CONST_AUTO_NUMERATION_CODE SYSRES_CONST_AUTO_STRONG_ENUM_METHOD_FLAG SYSRES_CONST_AUTOTEXT_NAME_REQUISITE_CODE SYSRES_CONST_AUTOTEXT_TEXT_REQUISITE_CODE SYSRES_CONST_AUTOTEXT_USAGE_ALL SYSRES_CONST_AUTOTEXT_USAGE_ALL_CODE SYSRES_CONST_AUTOTEXT_USAGE_SIGN SYSRES_CONST_AUTOTEXT_USAGE_SIGN_CODE SYSRES_CONST_AUTOTEXT_USAGE_WORK SYSRES_CONST_AUTOTEXT_USAGE_WORK_CODE SYSRES_CONST_AUTOTEXT_USE_ANYWHERE_CODE SYSRES_CONST_AUTOTEXT_USE_ON_SIGNING_CODE SYSRES_CONST_AUTOTEXT_USE_ON_WORK_CODE SYSRES_CONST_BEGIN_DATE_REQUISITE_CODE SYSRES_CONST_BLACK_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_BLUE_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_BTN_PART SYSRES_CONST_CALCULATED_ROLE_TYPE_CODE SYSRES_CONST_CALL_TYPE_VARIABLE_BUTTON_VALUE SYSRES_CONST_CALL_TYPE_VARIABLE_PROGRAM_VALUE SYSRES_CONST_CANCEL_MESSAGE_FUNCTION_RESULT SYSRES_CONST_CARD_PART SYSRES_CONST_CARD_REFERENCE_MODE_NAME SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_ENCRYPT_VALUE SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_AND_ENCRYPT_VALUE SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_VALUE SYSRES_CONST_CHECK_PARAM_VALUE_DATE_PARAM_TYPE SYSRES_CONST_CHECK_PARAM_VALUE_FLOAT_PARAM_TYPE SYSRES_CONST_CHECK_PARAM_VALUE_INTEGER_PARAM_TYPE SYSRES_CONST_CHECK_PARAM_VALUE_PICK_PARAM_TYPE SYSRES_CONST_CHECK_PARAM_VALUE_REEFRENCE_PARAM_TYPE SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_FEMININE SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_MASCULINE SYSRES_CONST_CODE_COMPONENT_TYPE_ADMIN SYSRES_CONST_CODE_COMPONENT_TYPE_DEVELOPER SYSRES_CONST_CODE_COMPONENT_TYPE_DOCS SYSRES_CONST_CODE_COMPONENT_TYPE_EDOC_CARDS SYSRES_CONST_CODE_COMPONENT_TYPE_EXTERNAL_EXECUTABLE SYSRES_CONST_CODE_COMPONENT_TYPE_OTHER SYSRES_CONST_CODE_COMPONENT_TYPE_REFERENCE SYSRES_CONST_CODE_COMPONENT_TYPE_REPORT SYSRES_CONST_CODE_COMPONENT_TYPE_SCRIPT SYSRES_CONST_CODE_COMPONENT_TYPE_URL SYSRES_CONST_CODE_REQUISITE_ACCESS SYSRES_CONST_CODE_REQUISITE_CODE SYSRES_CONST_CODE_REQUISITE_COMPONENT SYSRES_CONST_CODE_REQUISITE_DESCRIPTION SYSRES_CONST_CODE_REQUISITE_EXCLUDE_COMPONENT SYSRES_CONST_CODE_REQUISITE_RECORD SYSRES_CONST_COMMENT_REQ_CODE SYSRES_CONST_COMMON_SETTINGS_REQUISITE_CODE SYSRES_CONST_COMP_CODE_GRD SYSRES_CONST_COMPONENT_GROUP_TYPE_REQUISITE_CODE SYSRES_CONST_COMPONENT_TYPE_ADMIN_COMPONENTS SYSRES_CONST_COMPONENT_TYPE_DEVELOPER_COMPONENTS SYSRES_CONST_COMPONENT_TYPE_DOCS SYSRES_CONST_COMPONENT_TYPE_EDOC_CARDS SYSRES_CONST_COMPONENT_TYPE_EDOCS SYSRES_CONST_COMPONENT_TYPE_EXTERNAL_EXECUTABLE SYSRES_CONST_COMPONENT_TYPE_OTHER SYSRES_CONST_COMPONENT_TYPE_REFERENCE_TYPES SYSRES_CONST_COMPONENT_TYPE_REFERENCES SYSRES_CONST_COMPONENT_TYPE_REPORTS SYSRES_CONST_COMPONENT_TYPE_SCRIPTS SYSRES_CONST_COMPONENT_TYPE_URL SYSRES_CONST_COMPONENTS_REMOTE_SERVERS_VIEW_CODE SYSRES_CONST_CONDITION_BLOCK_DESCRIPTION SYSRES_CONST_CONST_FIRM_STATUS_COMMON SYSRES_CONST_CONST_FIRM_STATUS_INDIVIDUAL SYSRES_CONST_CONST_NEGATIVE_VALUE SYSRES_CONST_CONST_POSITIVE_VALUE SYSRES_CONST_CONST_SERVER_STATUS_DONT_REPLICATE SYSRES_CONST_CONST_SERVER_STATUS_REPLICATE SYSRES_CONST_CONTENTS_REQUISITE_CODE SYSRES_CONST_DATA_TYPE_BOOLEAN SYSRES_CONST_DATA_TYPE_DATE SYSRES_CONST_DATA_TYPE_FLOAT SYSRES_CONST_DATA_TYPE_INTEGER SYSRES_CONST_DATA_TYPE_PICK SYSRES_CONST_DATA_TYPE_REFERENCE SYSRES_CONST_DATA_TYPE_STRING SYSRES_CONST_DATA_TYPE_TEXT SYSRES_CONST_DATA_TYPE_VARIANT SYSRES_CONST_DATE_CLOSE_REQ_CODE SYSRES_CONST_DATE_FORMAT_DATE_ONLY_CHAR SYSRES_CONST_DATE_OPEN_REQ_CODE SYSRES_CONST_DATE_REQUISITE SYSRES_CONST_DATE_REQUISITE_CODE SYSRES_CONST_DATE_REQUISITE_NAME SYSRES_CONST_DATE_REQUISITE_TYPE SYSRES_CONST_DATE_TYPE_CHAR SYSRES_CONST_DATETIME_FORMAT_VALUE SYSRES_CONST_DEA_ACCESS_RIGHTS_ACTION_CODE SYSRES_CONST_DESCRIPTION_LOCALIZE_ID_REQUISITE_CODE SYSRES_CONST_DESCRIPTION_REQUISITE_CODE SYSRES_CONST_DET1_PART SYSRES_CONST_DET2_PART SYSRES_CONST_DET3_PART SYSRES_CONST_DET4_PART SYSRES_CONST_DET5_PART SYSRES_CONST_DET6_PART SYSRES_CONST_DETAIL_DATASET_KEY_REQUISITE_CODE SYSRES_CONST_DETAIL_PICK_REQUISITE_CODE SYSRES_CONST_DETAIL_REQ_CODE SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_CODE SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_NAME SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_CODE SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_NAME SYSRES_CONST_DOCUMENT_STORAGES_CODE SYSRES_CONST_DOCUMENT_TEMPLATES_TYPE_NAME SYSRES_CONST_DOUBLE_REQUISITE_CODE SYSRES_CONST_EDITOR_CLOSE_FILE_OBSERV_TYPE_CODE SYSRES_CONST_EDITOR_CLOSE_PROCESS_OBSERV_TYPE_CODE SYSRES_CONST_EDITOR_TYPE_REQUISITE_CODE SYSRES_CONST_EDITORS_APPLICATION_NAME_REQUISITE_CODE SYSRES_CONST_EDITORS_CREATE_SEVERAL_PROCESSES_REQUISITE_CODE SYSRES_CONST_EDITORS_EXTENSION_REQUISITE_CODE SYSRES_CONST_EDITORS_OBSERVER_BY_PROCESS_TYPE SYSRES_CONST_EDITORS_REFERENCE_CODE SYSRES_CONST_EDITORS_REPLACE_SPEC_CHARS_REQUISITE_CODE SYSRES_CONST_EDITORS_USE_PLUGINS_REQUISITE_CODE SYSRES_CONST_EDITORS_VIEW_DOCUMENT_OPENED_TO_EDIT_CODE SYSRES_CONST_EDOC_CARD_TYPE_REQUISITE_CODE SYSRES_CONST_EDOC_CARD_TYPES_LINK_REQUISITE_CODE SYSRES_CONST_EDOC_CERTIFICATE_AND_PASSWORD_ENCODE_CODE SYSRES_CONST_EDOC_CERTIFICATE_ENCODE_CODE SYSRES_CONST_EDOC_DATE_REQUISITE_CODE SYSRES_CONST_EDOC_KIND_REFERENCE_CODE SYSRES_CONST_EDOC_KINDS_BY_TEMPLATE_ACTION_CODE SYSRES_CONST_EDOC_MANAGE_ACCESS_CODE SYSRES_CONST_EDOC_NONE_ENCODE_CODE SYSRES_CONST_EDOC_NUMBER_REQUISITE_CODE SYSRES_CONST_EDOC_PASSWORD_ENCODE_CODE SYSRES_CONST_EDOC_READONLY_ACCESS_CODE SYSRES_CONST_EDOC_SHELL_LIFE_TYPE_VIEW_VALUE SYSRES_CONST_EDOC_SIZE_RESTRICTION_PRIORITY_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_CHECK_ACCESS_RIGHTS_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_COMPUTER_NAME_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_DATABASE_NAME_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_EDIT_IN_STORAGE_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_LOCAL_PATH_REQUISITE_CODE SYSRES_CONST_EDOC_STORAGE_SHARED_SOURCE_NAME_REQUISITE_CODE SYSRES_CONST_EDOC_TEMPLATE_REQUISITE_CODE SYSRES_CONST_EDOC_TYPES_REFERENCE_CODE SYSRES_CONST_EDOC_VERSION_ACTIVE_STAGE_CODE SYSRES_CONST_EDOC_VERSION_DESIGN_STAGE_CODE SYSRES_CONST_EDOC_VERSION_OBSOLETE_STAGE_CODE SYSRES_CONST_EDOC_WRITE_ACCES_CODE SYSRES_CONST_EDOCUMENT_CARD_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE SYSRES_CONST_ENCODE_CERTIFICATE_TYPE_CODE SYSRES_CONST_END_DATE_REQUISITE_CODE SYSRES_CONST_ENUMERATION_TYPE_REQUISITE_CODE SYSRES_CONST_EXECUTE_ACCESS_RIGHTS_TYPE_CODE SYSRES_CONST_EXECUTIVE_FILE_STORAGE_TYPE SYSRES_CONST_EXIST_CONST SYSRES_CONST_EXIST_VALUE SYSRES_CONST_EXPORT_LOCK_TYPE_ASK SYSRES_CONST_EXPORT_LOCK_TYPE_WITH_LOCK SYSRES_CONST_EXPORT_LOCK_TYPE_WITHOUT_LOCK SYSRES_CONST_EXPORT_VERSION_TYPE_ASK SYSRES_CONST_EXPORT_VERSION_TYPE_LAST SYSRES_CONST_EXPORT_VERSION_TYPE_LAST_ACTIVE SYSRES_CONST_EXTENSION_REQUISITE_CODE SYSRES_CONST_FILTER_NAME_REQUISITE_CODE SYSRES_CONST_FILTER_REQUISITE_CODE SYSRES_CONST_FILTER_TYPE_COMMON_CODE SYSRES_CONST_FILTER_TYPE_COMMON_NAME SYSRES_CONST_FILTER_TYPE_USER_CODE SYSRES_CONST_FILTER_TYPE_USER_NAME SYSRES_CONST_FILTER_VALUE_REQUISITE_NAME SYSRES_CONST_FLOAT_NUMBER_FORMAT_CHAR SYSRES_CONST_FLOAT_REQUISITE_TYPE SYSRES_CONST_FOLDER_AUTHOR_VALUE SYSRES_CONST_FOLDER_KIND_ANY_OBJECTS SYSRES_CONST_FOLDER_KIND_COMPONENTS SYSRES_CONST_FOLDER_KIND_EDOCS SYSRES_CONST_FOLDER_KIND_JOBS SYSRES_CONST_FOLDER_KIND_TASKS SYSRES_CONST_FOLDER_TYPE_COMMON SYSRES_CONST_FOLDER_TYPE_COMPONENT SYSRES_CONST_FOLDER_TYPE_FAVORITES SYSRES_CONST_FOLDER_TYPE_INBOX SYSRES_CONST_FOLDER_TYPE_OUTBOX SYSRES_CONST_FOLDER_TYPE_QUICK_LAUNCH SYSRES_CONST_FOLDER_TYPE_SEARCH SYSRES_CONST_FOLDER_TYPE_SHORTCUTS SYSRES_CONST_FOLDER_TYPE_USER SYSRES_CONST_FROM_DICTIONARY_ENUM_METHOD_FLAG SYSRES_CONST_FULL_SUBSTITUTE_TYPE SYSRES_CONST_FULL_SUBSTITUTE_TYPE_CODE SYSRES_CONST_FUNCTION_CANCEL_RESULT SYSRES_CONST_FUNCTION_CATEGORY_SYSTEM SYSRES_CONST_FUNCTION_CATEGORY_USER SYSRES_CONST_FUNCTION_FAILURE_RESULT SYSRES_CONST_FUNCTION_SAVE_RESULT SYSRES_CONST_GENERATED_REQUISITE SYSRES_CONST_GREEN_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_GROUP_ACCOUNT_TYPE_VALUE_CODE SYSRES_CONST_GROUP_CATEGORY_NORMAL_CODE SYSRES_CONST_GROUP_CATEGORY_NORMAL_NAME SYSRES_CONST_GROUP_CATEGORY_SERVICE_CODE SYSRES_CONST_GROUP_CATEGORY_SERVICE_NAME SYSRES_CONST_GROUP_COMMON_CATEGORY_FIELD_VALUE SYSRES_CONST_GROUP_FULL_NAME_REQUISITE_CODE SYSRES_CONST_GROUP_NAME_REQUISITE_CODE SYSRES_CONST_GROUP_RIGHTS_T_REQUISITE_CODE SYSRES_CONST_GROUP_SERVER_CODES_REQUISITE_CODE SYSRES_CONST_GROUP_SERVER_NAME_REQUISITE_CODE SYSRES_CONST_GROUP_SERVICE_CATEGORY_FIELD_VALUE SYSRES_CONST_GROUP_USER_REQUISITE_CODE SYSRES_CONST_GROUPS_REFERENCE_CODE SYSRES_CONST_GROUPS_REQUISITE_CODE SYSRES_CONST_HIDDEN_MODE_NAME SYSRES_CONST_HIGH_LVL_REQUISITE_CODE SYSRES_CONST_HISTORY_ACTION_CREATE_CODE SYSRES_CONST_HISTORY_ACTION_DELETE_CODE SYSRES_CONST_HISTORY_ACTION_EDIT_CODE SYSRES_CONST_HOUR_CHAR SYSRES_CONST_ID_REQUISITE_CODE SYSRES_CONST_IDSPS_REQUISITE_CODE SYSRES_CONST_IMAGE_MODE_COLOR SYSRES_CONST_IMAGE_MODE_GREYSCALE SYSRES_CONST_IMAGE_MODE_MONOCHROME SYSRES_CONST_IMPORTANCE_HIGH SYSRES_CONST_IMPORTANCE_LOW SYSRES_CONST_IMPORTANCE_NORMAL SYSRES_CONST_IN_DESIGN_VERSION_STATE_PICK_VALUE SYSRES_CONST_INCOMING_WORK_RULE_TYPE_CODE SYSRES_CONST_INT_REQUISITE SYSRES_CONST_INT_REQUISITE_TYPE SYSRES_CONST_INTEGER_NUMBER_FORMAT_CHAR SYSRES_CONST_INTEGER_TYPE_CHAR SYSRES_CONST_IS_GENERATED_REQUISITE_NEGATIVE_VALUE SYSRES_CONST_IS_PUBLIC_ROLE_REQUISITE_CODE SYSRES_CONST_IS_REMOTE_USER_NEGATIVE_VALUE SYSRES_CONST_IS_REMOTE_USER_POSITIVE_VALUE SYSRES_CONST_IS_STORED_REQUISITE_NEGATIVE_VALUE SYSRES_CONST_IS_STORED_REQUISITE_STORED_VALUE SYSRES_CONST_ITALIC_LIFE_CYCLE_STAGE_DRAW_STYLE SYSRES_CONST_JOB_BLOCK_DESCRIPTION SYSRES_CONST_JOB_KIND_CONTROL_JOB SYSRES_CONST_JOB_KIND_JOB SYSRES_CONST_JOB_KIND_NOTICE SYSRES_CONST_JOB_STATE_ABORTED SYSRES_CONST_JOB_STATE_COMPLETE SYSRES_CONST_JOB_STATE_WORKING SYSRES_CONST_KIND_REQUISITE_CODE SYSRES_CONST_KIND_REQUISITE_NAME SYSRES_CONST_KINDS_CREATE_SHADOW_COPIES_REQUISITE_CODE SYSRES_CONST_KINDS_DEFAULT_EDOC_LIFE_STAGE_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_ALL_TEPLATES_ALLOWED_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_ALLOW_LIFE_CYCLE_STAGE_CHANGING_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_ALLOW_MULTIPLE_ACTIVE_VERSIONS_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_SHARE_ACCES_RIGHTS_BY_DEFAULT_CODE SYSRES_CONST_KINDS_EDOC_TEMPLATE_REQUISITE_CODE SYSRES_CONST_KINDS_EDOC_TYPE_REQUISITE_CODE SYSRES_CONST_KINDS_SIGNERS_REQUISITES_CODE SYSRES_CONST_KOD_INPUT_TYPE SYSRES_CONST_LAST_UPDATE_DATE_REQUISITE_CODE SYSRES_CONST_LIFE_CYCLE_START_STAGE_REQUISITE_CODE SYSRES_CONST_LILAC_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_LINK_OBJECT_KIND_COMPONENT SYSRES_CONST_LINK_OBJECT_KIND_DOCUMENT SYSRES_CONST_LINK_OBJECT_KIND_EDOC SYSRES_CONST_LINK_OBJECT_KIND_FOLDER SYSRES_CONST_LINK_OBJECT_KIND_JOB SYSRES_CONST_LINK_OBJECT_KIND_REFERENCE SYSRES_CONST_LINK_OBJECT_KIND_TASK SYSRES_CONST_LINK_REF_TYPE_REQUISITE_CODE SYSRES_CONST_LIST_REFERENCE_MODE_NAME SYSRES_CONST_LOCALIZATION_DICTIONARY_MAIN_VIEW_CODE SYSRES_CONST_MAIN_VIEW_CODE SYSRES_CONST_MANUAL_ENUM_METHOD_FLAG SYSRES_CONST_MASTER_COMP_TYPE_REQUISITE_CODE SYSRES_CONST_MASTER_TABLE_REC_ID_REQUISITE_CODE SYSRES_CONST_MAXIMIZED_MODE_NAME SYSRES_CONST_ME_VALUE SYSRES_CONST_MESSAGE_ATTENTION_CAPTION SYSRES_CONST_MESSAGE_CONFIRMATION_CAPTION SYSRES_CONST_MESSAGE_ERROR_CAPTION SYSRES_CONST_MESSAGE_INFORMATION_CAPTION SYSRES_CONST_MINIMIZED_MODE_NAME SYSRES_CONST_MINUTE_CHAR SYSRES_CONST_MODULE_REQUISITE_CODE SYSRES_CONST_MONITORING_BLOCK_DESCRIPTION SYSRES_CONST_MONTH_FORMAT_VALUE SYSRES_CONST_NAME_LOCALIZE_ID_REQUISITE_CODE SYSRES_CONST_NAME_REQUISITE_CODE SYSRES_CONST_NAME_SINGULAR_REQUISITE_CODE SYSRES_CONST_NAMEAN_INPUT_TYPE SYSRES_CONST_NEGATIVE_PICK_VALUE SYSRES_CONST_NEGATIVE_VALUE SYSRES_CONST_NO SYSRES_CONST_NO_PICK_VALUE SYSRES_CONST_NO_SIGNATURE_REQUISITE_CODE SYSRES_CONST_NO_VALUE SYSRES_CONST_NONE_ACCESS_RIGHTS_TYPE_CODE SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE_MASCULINE SYSRES_CONST_NORMAL_ACCESS_RIGHTS_TYPE_CODE SYSRES_CONST_NORMAL_LIFE_CYCLE_STAGE_DRAW_STYLE SYSRES_CONST_NORMAL_MODE_NAME SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_CODE SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_NAME SYSRES_CONST_NOTE_REQUISITE_CODE SYSRES_CONST_NOTICE_BLOCK_DESCRIPTION SYSRES_CONST_NUM_REQUISITE SYSRES_CONST_NUM_STR_REQUISITE_CODE SYSRES_CONST_NUMERATION_AUTO_NOT_STRONG SYSRES_CONST_NUMERATION_AUTO_STRONG SYSRES_CONST_NUMERATION_FROM_DICTONARY SYSRES_CONST_NUMERATION_MANUAL SYSRES_CONST_NUMERIC_TYPE_CHAR SYSRES_CONST_NUMREQ_REQUISITE_CODE SYSRES_CONST_OBSOLETE_VERSION_STATE_PICK_VALUE SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_CODE SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_FEMININE SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_MASCULINE SYSRES_CONST_OPTIONAL_FORM_COMP_REQCODE_PREFIX SYSRES_CONST_ORANGE_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_ORIGINALREF_REQUISITE_CODE SYSRES_CONST_OURFIRM_REF_CODE SYSRES_CONST_OURFIRM_REQUISITE_CODE SYSRES_CONST_OURFIRM_VAR SYSRES_CONST_OUTGOING_WORK_RULE_TYPE_CODE SYSRES_CONST_PICK_NEGATIVE_RESULT SYSRES_CONST_PICK_POSITIVE_RESULT SYSRES_CONST_PICK_REQUISITE SYSRES_CONST_PICK_REQUISITE_TYPE SYSRES_CONST_PICK_TYPE_CHAR SYSRES_CONST_PLAN_STATUS_REQUISITE_CODE SYSRES_CONST_PLATFORM_VERSION_COMMENT SYSRES_CONST_PLUGINS_SETTINGS_DESCRIPTION_REQUISITE_CODE SYSRES_CONST_POSITIVE_PICK_VALUE SYSRES_CONST_POWER_TO_CREATE_ACTION_CODE SYSRES_CONST_POWER_TO_SIGN_ACTION_CODE SYSRES_CONST_PRIORITY_REQUISITE_CODE SYSRES_CONST_QUALIFIED_TASK_TYPE SYSRES_CONST_QUALIFIED_TASK_TYPE_CODE SYSRES_CONST_RECSTAT_REQUISITE_CODE SYSRES_CONST_RED_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_REF_ID_T_REF_TYPE_REQUISITE_CODE SYSRES_CONST_REF_REQUISITE SYSRES_CONST_REF_REQUISITE_TYPE SYSRES_CONST_REF_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE SYSRES_CONST_REFERENCE_RECORD_HISTORY_CREATE_ACTION_CODE SYSRES_CONST_REFERENCE_RECORD_HISTORY_DELETE_ACTION_CODE SYSRES_CONST_REFERENCE_RECORD_HISTORY_MODIFY_ACTION_CODE SYSRES_CONST_REFERENCE_TYPE_CHAR SYSRES_CONST_REFERENCE_TYPE_REQUISITE_NAME SYSRES_CONST_REFERENCES_ADD_PARAMS_REQUISITE_CODE SYSRES_CONST_REFERENCES_DISPLAY_REQUISITE_REQUISITE_CODE SYSRES_CONST_REMOTE_SERVER_STATUS_WORKING SYSRES_CONST_REMOTE_SERVER_TYPE_MAIN SYSRES_CONST_REMOTE_SERVER_TYPE_SECONDARY SYSRES_CONST_REMOTE_USER_FLAG_VALUE_CODE SYSRES_CONST_REPORT_APP_EDITOR_INTERNAL SYSRES_CONST_REPORT_BASE_REPORT_ID_REQUISITE_CODE SYSRES_CONST_REPORT_BASE_REPORT_REQUISITE_CODE SYSRES_CONST_REPORT_SCRIPT_REQUISITE_CODE SYSRES_CONST_REPORT_TEMPLATE_REQUISITE_CODE SYSRES_CONST_REPORT_VIEWER_CODE_REQUISITE_CODE SYSRES_CONST_REQ_ALLOW_COMPONENT_DEFAULT_VALUE SYSRES_CONST_REQ_ALLOW_RECORD_DEFAULT_VALUE SYSRES_CONST_REQ_ALLOW_SERVER_COMPONENT_DEFAULT_VALUE SYSRES_CONST_REQ_MODE_AVAILABLE_CODE SYSRES_CONST_REQ_MODE_EDIT_CODE SYSRES_CONST_REQ_MODE_HIDDEN_CODE SYSRES_CONST_REQ_MODE_NOT_AVAILABLE_CODE SYSRES_CONST_REQ_MODE_VIEW_CODE SYSRES_CONST_REQ_NUMBER_REQUISITE_CODE SYSRES_CONST_REQ_SECTION_VALUE SYSRES_CONST_REQ_TYPE_VALUE SYSRES_CONST_REQUISITE_FORMAT_BY_UNIT SYSRES_CONST_REQUISITE_FORMAT_DATE_FULL SYSRES_CONST_REQUISITE_FORMAT_DATE_TIME SYSRES_CONST_REQUISITE_FORMAT_LEFT SYSRES_CONST_REQUISITE_FORMAT_RIGHT SYSRES_CONST_REQUISITE_FORMAT_WITHOUT_UNIT SYSRES_CONST_REQUISITE_NUMBER_REQUISITE_CODE SYSRES_CONST_REQUISITE_SECTION_ACTIONS SYSRES_CONST_REQUISITE_SECTION_BUTTON SYSRES_CONST_REQUISITE_SECTION_BUTTONS SYSRES_CONST_REQUISITE_SECTION_CARD SYSRES_CONST_REQUISITE_SECTION_TABLE SYSRES_CONST_REQUISITE_SECTION_TABLE10 SYSRES_CONST_REQUISITE_SECTION_TABLE11 SYSRES_CONST_REQUISITE_SECTION_TABLE12 SYSRES_CONST_REQUISITE_SECTION_TABLE13 SYSRES_CONST_REQUISITE_SECTION_TABLE14 SYSRES_CONST_REQUISITE_SECTION_TABLE15 SYSRES_CONST_REQUISITE_SECTION_TABLE16 SYSRES_CONST_REQUISITE_SECTION_TABLE17 SYSRES_CONST_REQUISITE_SECTION_TABLE18 SYSRES_CONST_REQUISITE_SECTION_TABLE19 SYSRES_CONST_REQUISITE_SECTION_TABLE2 SYSRES_CONST_REQUISITE_SECTION_TABLE20 SYSRES_CONST_REQUISITE_SECTION_TABLE21 SYSRES_CONST_REQUISITE_SECTION_TABLE22 SYSRES_CONST_REQUISITE_SECTION_TABLE23 SYSRES_CONST_REQUISITE_SECTION_TABLE24 SYSRES_CONST_REQUISITE_SECTION_TABLE3 SYSRES_CONST_REQUISITE_SECTION_TABLE4 SYSRES_CONST_REQUISITE_SECTION_TABLE5 SYSRES_CONST_REQUISITE_SECTION_TABLE6 SYSRES_CONST_REQUISITE_SECTION_TABLE7 SYSRES_CONST_REQUISITE_SECTION_TABLE8 SYSRES_CONST_REQUISITE_SECTION_TABLE9 SYSRES_CONST_REQUISITES_PSEUDOREFERENCE_REQUISITE_NUMBER_REQUISITE_CODE SYSRES_CONST_RIGHT_ALIGNMENT_CODE SYSRES_CONST_ROLES_REFERENCE_CODE SYSRES_CONST_ROUTE_STEP_AFTER_RUS SYSRES_CONST_ROUTE_STEP_AND_CONDITION_RUS SYSRES_CONST_ROUTE_STEP_OR_CONDITION_RUS SYSRES_CONST_ROUTE_TYPE_COMPLEX SYSRES_CONST_ROUTE_TYPE_PARALLEL SYSRES_CONST_ROUTE_TYPE_SERIAL SYSRES_CONST_SBDATASETDESC_NEGATIVE_VALUE SYSRES_CONST_SBDATASETDESC_POSITIVE_VALUE SYSRES_CONST_SBVIEWSDESC_POSITIVE_VALUE SYSRES_CONST_SCRIPT_BLOCK_DESCRIPTION SYSRES_CONST_SEARCH_BY_TEXT_REQUISITE_CODE SYSRES_CONST_SEARCHES_COMPONENT_CONTENT SYSRES_CONST_SEARCHES_CRITERIA_ACTION_NAME SYSRES_CONST_SEARCHES_EDOC_CONTENT SYSRES_CONST_SEARCHES_FOLDER_CONTENT SYSRES_CONST_SEARCHES_JOB_CONTENT SYSRES_CONST_SEARCHES_REFERENCE_CODE SYSRES_CONST_SEARCHES_TASK_CONTENT SYSRES_CONST_SECOND_CHAR SYSRES_CONST_SECTION_REQUISITE_ACTIONS_VALUE SYSRES_CONST_SECTION_REQUISITE_CARD_VALUE SYSRES_CONST_SECTION_REQUISITE_CODE SYSRES_CONST_SECTION_REQUISITE_DETAIL_1_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_2_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_3_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_4_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_5_VALUE SYSRES_CONST_SECTION_REQUISITE_DETAIL_6_VALUE SYSRES_CONST_SELECT_REFERENCE_MODE_NAME SYSRES_CONST_SELECT_TYPE_SELECTABLE SYSRES_CONST_SELECT_TYPE_SELECTABLE_ONLY_CHILD SYSRES_CONST_SELECT_TYPE_SELECTABLE_WITH_CHILD SYSRES_CONST_SELECT_TYPE_UNSLECTABLE SYSRES_CONST_SERVER_TYPE_MAIN SYSRES_CONST_SERVICE_USER_CATEGORY_FIELD_VALUE SYSRES_CONST_SETTINGS_USER_REQUISITE_CODE SYSRES_CONST_SIGNATURE_AND_ENCODE_CERTIFICATE_TYPE_CODE SYSRES_CONST_SIGNATURE_CERTIFICATE_TYPE_CODE SYSRES_CONST_SINGULAR_TITLE_REQUISITE_CODE SYSRES_CONST_SQL_SERVER_AUTHENTIFICATION_FLAG_VALUE_CODE SYSRES_CONST_SQL_SERVER_ENCODE_AUTHENTIFICATION_FLAG_VALUE_CODE SYSRES_CONST_STANDART_ROUTE_REFERENCE_CODE SYSRES_CONST_STANDART_ROUTE_REFERENCE_COMMENT_REQUISITE_CODE SYSRES_CONST_STANDART_ROUTES_GROUPS_REFERENCE_CODE SYSRES_CONST_STATE_REQ_NAME SYSRES_CONST_STATE_REQUISITE_ACTIVE_VALUE SYSRES_CONST_STATE_REQUISITE_CLOSED_VALUE SYSRES_CONST_STATE_REQUISITE_CODE SYSRES_CONST_STATIC_ROLE_TYPE_CODE SYSRES_CONST_STATUS_PLAN_DEFAULT_VALUE SYSRES_CONST_STATUS_VALUE_AUTOCLEANING SYSRES_CONST_STATUS_VALUE_BLUE_SQUARE SYSRES_CONST_STATUS_VALUE_COMPLETE SYSRES_CONST_STATUS_VALUE_GREEN_SQUARE SYSRES_CONST_STATUS_VALUE_ORANGE_SQUARE SYSRES_CONST_STATUS_VALUE_PURPLE_SQUARE SYSRES_CONST_STATUS_VALUE_RED_SQUARE SYSRES_CONST_STATUS_VALUE_SUSPEND SYSRES_CONST_STATUS_VALUE_YELLOW_SQUARE SYSRES_CONST_STDROUTE_SHOW_TO_USERS_REQUISITE_CODE SYSRES_CONST_STORAGE_TYPE_FILE SYSRES_CONST_STORAGE_TYPE_SQL_SERVER SYSRES_CONST_STR_REQUISITE SYSRES_CONST_STRIKEOUT_LIFE_CYCLE_STAGE_DRAW_STYLE SYSRES_CONST_STRING_FORMAT_LEFT_ALIGN_CHAR SYSRES_CONST_STRING_FORMAT_RIGHT_ALIGN_CHAR SYSRES_CONST_STRING_REQUISITE_CODE SYSRES_CONST_STRING_REQUISITE_TYPE SYSRES_CONST_STRING_TYPE_CHAR SYSRES_CONST_SUBSTITUTES_PSEUDOREFERENCE_CODE SYSRES_CONST_SUBTASK_BLOCK_DESCRIPTION SYSRES_CONST_SYSTEM_SETTING_CURRENT_USER_PARAM_VALUE SYSRES_CONST_SYSTEM_SETTING_EMPTY_VALUE_PARAM_VALUE SYSRES_CONST_SYSTEM_VERSION_COMMENT SYSRES_CONST_TASK_ACCESS_TYPE_ALL SYSRES_CONST_TASK_ACCESS_TYPE_ALL_MEMBERS SYSRES_CONST_TASK_ACCESS_TYPE_MANUAL SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION_AND_PASSWORD SYSRES_CONST_TASK_ENCODE_TYPE_NONE SYSRES_CONST_TASK_ENCODE_TYPE_PASSWORD SYSRES_CONST_TASK_ROUTE_ALL_CONDITION SYSRES_CONST_TASK_ROUTE_AND_CONDITION SYSRES_CONST_TASK_ROUTE_OR_CONDITION SYSRES_CONST_TASK_STATE_ABORTED SYSRES_CONST_TASK_STATE_COMPLETE SYSRES_CONST_TASK_STATE_CONTINUED SYSRES_CONST_TASK_STATE_CONTROL SYSRES_CONST_TASK_STATE_INIT SYSRES_CONST_TASK_STATE_WORKING SYSRES_CONST_TASK_TITLE SYSRES_CONST_TASK_TYPES_GROUPS_REFERENCE_CODE SYSRES_CONST_TASK_TYPES_REFERENCE_CODE SYSRES_CONST_TEMPLATES_REFERENCE_CODE SYSRES_CONST_TEST_DATE_REQUISITE_NAME SYSRES_CONST_TEST_DEV_DATABASE_NAME SYSRES_CONST_TEST_DEV_SYSTEM_CODE SYSRES_CONST_TEST_EDMS_DATABASE_NAME SYSRES_CONST_TEST_EDMS_MAIN_CODE SYSRES_CONST_TEST_EDMS_MAIN_DB_NAME SYSRES_CONST_TEST_EDMS_SECOND_CODE SYSRES_CONST_TEST_EDMS_SECOND_DB_NAME SYSRES_CONST_TEST_EDMS_SYSTEM_CODE SYSRES_CONST_TEST_NUMERIC_REQUISITE_NAME SYSRES_CONST_TEXT_REQUISITE SYSRES_CONST_TEXT_REQUISITE_CODE SYSRES_CONST_TEXT_REQUISITE_TYPE SYSRES_CONST_TEXT_TYPE_CHAR SYSRES_CONST_TYPE_CODE_REQUISITE_CODE SYSRES_CONST_TYPE_REQUISITE_CODE SYSRES_CONST_UNDEFINED_LIFE_CYCLE_STAGE_FONT_COLOR SYSRES_CONST_UNITS_SECTION_ID_REQUISITE_CODE SYSRES_CONST_UNITS_SECTION_REQUISITE_CODE SYSRES_CONST_UNOPERATING_RECORD_FLAG_VALUE_CODE SYSRES_CONST_UNSTORED_DATA_REQUISITE_CODE SYSRES_CONST_UNSTORED_DATA_REQUISITE_NAME SYSRES_CONST_USE_ACCESS_TYPE_CODE SYSRES_CONST_USE_ACCESS_TYPE_NAME SYSRES_CONST_USER_ACCOUNT_TYPE_VALUE_CODE SYSRES_CONST_USER_ADDITIONAL_INFORMATION_REQUISITE_CODE SYSRES_CONST_USER_AND_GROUP_ID_FROM_PSEUDOREFERENCE_REQUISITE_CODE SYSRES_CONST_USER_CATEGORY_NORMAL SYSRES_CONST_USER_CERTIFICATE_REQUISITE_CODE SYSRES_CONST_USER_CERTIFICATE_STATE_REQUISITE_CODE SYSRES_CONST_USER_CERTIFICATE_SUBJECT_NAME_REQUISITE_CODE SYSRES_CONST_USER_CERTIFICATE_THUMBPRINT_REQUISITE_CODE SYSRES_CONST_USER_COMMON_CATEGORY SYSRES_CONST_USER_COMMON_CATEGORY_CODE SYSRES_CONST_USER_FULL_NAME_REQUISITE_CODE SYSRES_CONST_USER_GROUP_TYPE_REQUISITE_CODE SYSRES_CONST_USER_LOGIN_REQUISITE_CODE SYSRES_CONST_USER_REMOTE_CONTROLLER_REQUISITE_CODE SYSRES_CONST_USER_REMOTE_SYSTEM_REQUISITE_CODE SYSRES_CONST_USER_RIGHTS_T_REQUISITE_CODE SYSRES_CONST_USER_SERVER_NAME_REQUISITE_CODE SYSRES_CONST_USER_SERVICE_CATEGORY SYSRES_CONST_USER_SERVICE_CATEGORY_CODE SYSRES_CONST_USER_STATUS_ADMINISTRATOR_CODE SYSRES_CONST_USER_STATUS_ADMINISTRATOR_NAME SYSRES_CONST_USER_STATUS_DEVELOPER_CODE SYSRES_CONST_USER_STATUS_DEVELOPER_NAME SYSRES_CONST_USER_STATUS_DISABLED_CODE SYSRES_CONST_USER_STATUS_DISABLED_NAME SYSRES_CONST_USER_STATUS_SYSTEM_DEVELOPER_CODE SYSRES_CONST_USER_STATUS_USER_CODE SYSRES_CONST_USER_STATUS_USER_NAME SYSRES_CONST_USER_STATUS_USER_NAME_DEPRECATED SYSRES_CONST_USER_TYPE_FIELD_VALUE_USER SYSRES_CONST_USER_TYPE_REQUISITE_CODE SYSRES_CONST_USERS_CONTROLLER_REQUISITE_CODE SYSRES_CONST_USERS_IS_MAIN_SERVER_REQUISITE_CODE SYSRES_CONST_USERS_REFERENCE_CODE SYSRES_CONST_USERS_REGISTRATION_CERTIFICATES_ACTION_NAME SYSRES_CONST_USERS_REQUISITE_CODE SYSRES_CONST_USERS_SYSTEM_REQUISITE_CODE SYSRES_CONST_USERS_USER_ACCESS_RIGHTS_TYPR_REQUISITE_CODE SYSRES_CONST_USERS_USER_AUTHENTICATION_REQUISITE_CODE SYSRES_CONST_USERS_USER_COMPONENT_REQUISITE_CODE SYSRES_CONST_USERS_USER_GROUP_REQUISITE_CODE SYSRES_CONST_USERS_VIEW_CERTIFICATES_ACTION_NAME SYSRES_CONST_VIEW_DEFAULT_CODE SYSRES_CONST_VIEW_DEFAULT_NAME SYSRES_CONST_VIEWER_REQUISITE_CODE SYSRES_CONST_WAITING_BLOCK_DESCRIPTION SYSRES_CONST_WIZARD_FORM_LABEL_TEST_STRING SYSRES_CONST_WIZARD_QUERY_PARAM_HEIGHT_ETALON_STRING SYSRES_CONST_WIZARD_REFERENCE_COMMENT_REQUISITE_CODE SYSRES_CONST_WORK_RULES_DESCRIPTION_REQUISITE_CODE SYSRES_CONST_WORK_TIME_CALENDAR_REFERENCE_CODE SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE_RUS SYSRES_CONST_WORK_WORKFLOW_SOFT_ROUTE_TYPE_VALUE_CODE_RUS SYSRES_CONST_WORKFLOW_ROUTE_TYPR_HARD SYSRES_CONST_WORKFLOW_ROUTE_TYPR_SOFT SYSRES_CONST_XML_ENCODING SYSRES_CONST_XREC_STAT_REQUISITE_CODE SYSRES_CONST_XRECID_FIELD_NAME SYSRES_CONST_YES SYSRES_CONST_YES_NO_2_REQUISITE_CODE SYSRES_CONST_YES_NO_REQUISITE_CODE SYSRES_CONST_YES_NO_T_REF_TYPE_REQUISITE_CODE SYSRES_CONST_YES_PICK_VALUE SYSRES_CONST_YES_VALUE CR FALSE nil NO_VALUE NULL TAB TRUE YES_VALUE ADMINISTRATORS_GROUP_NAME CUSTOMIZERS_GROUP_NAME DEVELOPERS_GROUP_NAME SERVICE_USERS_GROUP_NAME DECISION_BLOCK_FIRST_OPERAND_PROPERTY DECISION_BLOCK_NAME_PROPERTY DECISION_BLOCK_OPERATION_PROPERTY DECISION_BLOCK_RESULT_TYPE_PROPERTY DECISION_BLOCK_SECOND_OPERAND_PROPERTY ANY_FILE_EXTENTION COMPRESSED_DOCUMENT_EXTENSION EXTENDED_DOCUMENT_EXTENSION SHORT_COMPRESSED_DOCUMENT_EXTENSION SHORT_EXTENDED_DOCUMENT_EXTENSION JOB_BLOCK_ABORT_DEADLINE_PROPERTY JOB_BLOCK_AFTER_FINISH_EVENT JOB_BLOCK_AFTER_QUERY_PARAMETERS_EVENT JOB_BLOCK_ATTACHMENT_PROPERTY JOB_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY JOB_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY JOB_BLOCK_BEFORE_QUERY_PARAMETERS_EVENT JOB_BLOCK_BEFORE_START_EVENT JOB_BLOCK_CREATED_JOBS_PROPERTY JOB_BLOCK_DEADLINE_PROPERTY JOB_BLOCK_EXECUTION_RESULTS_PROPERTY JOB_BLOCK_IS_PARALLEL_PROPERTY JOB_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY JOB_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY JOB_BLOCK_JOB_TEXT_PROPERTY JOB_BLOCK_NAME_PROPERTY JOB_BLOCK_NEED_SIGN_ON_PERFORM_PROPERTY JOB_BLOCK_PERFORMER_PROPERTY JOB_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY JOB_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY JOB_BLOCK_SUBJECT_PROPERTY ENGLISH_LANGUAGE_CODE RUSSIAN_LANGUAGE_CODE smHidden smMaximized smMinimized smNormal wmNo wmYes COMPONENT_TOKEN_LINK_KIND DOCUMENT_LINK_KIND EDOCUMENT_LINK_KIND FOLDER_LINK_KIND JOB_LINK_KIND REFERENCE_LINK_KIND TASK_LINK_KIND COMPONENT_TOKEN_LOCK_TYPE EDOCUMENT_VERSION_LOCK_TYPE MONITOR_BLOCK_AFTER_FINISH_EVENT MONITOR_BLOCK_BEFORE_START_EVENT MONITOR_BLOCK_DEADLINE_PROPERTY MONITOR_BLOCK_INTERVAL_PROPERTY MONITOR_BLOCK_INTERVAL_TYPE_PROPERTY MONITOR_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY MONITOR_BLOCK_NAME_PROPERTY MONITOR_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY MONITOR_BLOCK_SEARCH_SCRIPT_PROPERTY NOTICE_BLOCK_AFTER_FINISH_EVENT NOTICE_BLOCK_ATTACHMENT_PROPERTY NOTICE_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY NOTICE_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY NOTICE_BLOCK_BEFORE_START_EVENT NOTICE_BLOCK_CREATED_NOTICES_PROPERTY NOTICE_BLOCK_DEADLINE_PROPERTY NOTICE_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY NOTICE_BLOCK_NAME_PROPERTY NOTICE_BLOCK_NOTICE_TEXT_PROPERTY NOTICE_BLOCK_PERFORMER_PROPERTY NOTICE_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY NOTICE_BLOCK_SUBJECT_PROPERTY dseAfterCancel dseAfterClose dseAfterDelete dseAfterDeleteOutOfTransaction dseAfterInsert dseAfterOpen dseAfterScroll dseAfterUpdate dseAfterUpdateOutOfTransaction dseBeforeCancel dseBeforeClose dseBeforeDelete dseBeforeDetailUpdate dseBeforeInsert dseBeforeOpen dseBeforeUpdate dseOnAnyRequisiteChange dseOnCloseRecord dseOnDeleteError dseOnOpenRecord dseOnPrepareUpdate dseOnUpdateError dseOnUpdateRatifiedRecord dseOnValidDelete dseOnValidUpdate reOnChange reOnChangeValues SELECTION_BEGIN_ROUTE_EVENT SELECTION_END_ROUTE_EVENT CURRENT_PERIOD_IS_REQUIRED PREVIOUS_CARD_TYPE_NAME SHOW_RECORD_PROPERTIES_FORM ACCESS_RIGHTS_SETTING_DIALOG_CODE ADMINISTRATOR_USER_CODE ANALYTIC_REPORT_TYPE asrtHideLocal asrtHideRemote CALCULATED_ROLE_TYPE_CODE COMPONENTS_REFERENCE_DEVELOPER_VIEW_CODE DCTS_TEST_PROTOCOLS_FOLDER_PATH E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED_BY_USER E_EDOC_VERSION_ALREDY_SIGNED E_EDOC_VERSION_ALREDY_SIGNED_BY_USER EDOC_TYPES_CODE_REQUISITE_FIELD_NAME EDOCUMENTS_ALIAS_NAME FILES_FOLDER_PATH FILTER_OPERANDS_DELIMITER FILTER_OPERATIONS_DELIMITER FORMCARD_NAME FORMLIST_NAME GET_EXTENDED_DOCUMENT_EXTENSION_CREATION_MODE GET_EXTENDED_DOCUMENT_EXTENSION_IMPORT_MODE INTEGRATED_REPORT_TYPE IS_BUILDER_APPLICATION_ROLE IS_BUILDER_APPLICATION_ROLE2 IS_BUILDER_USERS ISBSYSDEV LOG_FOLDER_PATH mbCancel mbNo mbNoToAll mbOK mbYes mbYesToAll MEMORY_DATASET_DESRIPTIONS_FILENAME mrNo mrNoToAll mrYes mrYesToAll MULTIPLE_SELECT_DIALOG_CODE NONOPERATING_RECORD_FLAG_FEMININE NONOPERATING_RECORD_FLAG_MASCULINE OPERATING_RECORD_FLAG_FEMININE OPERATING_RECORD_FLAG_MASCULINE PROFILING_SETTINGS_COMMON_SETTINGS_CODE_VALUE PROGRAM_INITIATED_LOOKUP_ACTION ratDelete ratEdit ratInsert REPORT_TYPE REQUIRED_PICK_VALUES_VARIABLE rmCard rmList SBRTE_PROGID_DEV SBRTE_PROGID_RELEASE STATIC_ROLE_TYPE_CODE SUPPRESS_EMPTY_TEMPLATE_CREATION SYSTEM_USER_CODE UPDATE_DIALOG_DATASET USED_IN_OBJECT_HINT_PARAM USER_INITIATED_LOOKUP_ACTION USER_NAME_FORMAT USER_SELECTION_RESTRICTIONS WORKFLOW_TEST_PROTOCOLS_FOLDER_PATH ELS_SUBTYPE_CONTROL_NAME ELS_FOLDER_KIND_CONTROL_NAME REPEAT_PROCESS_CURRENT_OBJECT_EXCEPTION_NAME PRIVILEGE_COMPONENT_FULL_ACCESS PRIVILEGE_DEVELOPMENT_EXPORT PRIVILEGE_DEVELOPMENT_IMPORT PRIVILEGE_DOCUMENT_DELETE PRIVILEGE_ESD PRIVILEGE_FOLDER_DELETE PRIVILEGE_MANAGE_ACCESS_RIGHTS PRIVILEGE_MANAGE_REPLICATION PRIVILEGE_MANAGE_SESSION_SERVER PRIVILEGE_OBJECT_FULL_ACCESS PRIVILEGE_OBJECT_VIEW PRIVILEGE_RESERVE_LICENSE PRIVILEGE_SYSTEM_CUSTOMIZE PRIVILEGE_SYSTEM_DEVELOP PRIVILEGE_SYSTEM_INSTALL PRIVILEGE_TASK_DELETE PRIVILEGE_USER_PLUGIN_SETTINGS_CUSTOMIZE PRIVILEGES_PSEUDOREFERENCE_CODE ACCESS_TYPES_PSEUDOREFERENCE_CODE ALL_AVAILABLE_COMPONENTS_PSEUDOREFERENCE_CODE ALL_AVAILABLE_PRIVILEGES_PSEUDOREFERENCE_CODE ALL_REPLICATE_COMPONENTS_PSEUDOREFERENCE_CODE AVAILABLE_DEVELOPERS_COMPONENTS_PSEUDOREFERENCE_CODE COMPONENTS_PSEUDOREFERENCE_CODE FILTRATER_SETTINGS_CONFLICTS_PSEUDOREFERENCE_CODE GROUPS_PSEUDOREFERENCE_CODE RECEIVE_PROTOCOL_PSEUDOREFERENCE_CODE REFERENCE_REQUISITE_PSEUDOREFERENCE_CODE REFERENCE_REQUISITES_PSEUDOREFERENCE_CODE REFTYPES_PSEUDOREFERENCE_CODE REPLICATION_SEANCES_DIARY_PSEUDOREFERENCE_CODE SEND_PROTOCOL_PSEUDOREFERENCE_CODE SUBSTITUTES_PSEUDOREFERENCE_CODE SYSTEM_SETTINGS_PSEUDOREFERENCE_CODE UNITS_PSEUDOREFERENCE_CODE USERS_PSEUDOREFERENCE_CODE VIEWERS_PSEUDOREFERENCE_CODE CERTIFICATE_TYPE_ENCRYPT CERTIFICATE_TYPE_SIGN CERTIFICATE_TYPE_SIGN_AND_ENCRYPT STORAGE_TYPE_FILE STORAGE_TYPE_NAS_CIFS STORAGE_TYPE_SAPERION STORAGE_TYPE_SQL_SERVER COMPTYPE2_REQUISITE_DOCUMENTS_VALUE COMPTYPE2_REQUISITE_TASKS_VALUE COMPTYPE2_REQUISITE_FOLDERS_VALUE COMPTYPE2_REQUISITE_REFERENCES_VALUE SYSREQ_CODE SYSREQ_COMPTYPE2 SYSREQ_CONST_AVAILABLE_FOR_WEB SYSREQ_CONST_COMMON_CODE SYSREQ_CONST_COMMON_VALUE SYSREQ_CONST_FIRM_CODE SYSREQ_CONST_FIRM_STATUS SYSREQ_CONST_FIRM_VALUE SYSREQ_CONST_SERVER_STATUS SYSREQ_CONTENTS SYSREQ_DATE_OPEN SYSREQ_DATE_CLOSE SYSREQ_DESCRIPTION SYSREQ_DESCRIPTION_LOCALIZE_ID SYSREQ_DOUBLE SYSREQ_EDOC_ACCESS_TYPE SYSREQ_EDOC_AUTHOR SYSREQ_EDOC_CREATED SYSREQ_EDOC_DELEGATE_RIGHTS_REQUISITE_CODE SYSREQ_EDOC_EDITOR SYSREQ_EDOC_ENCODE_TYPE SYSREQ_EDOC_ENCRYPTION_PLUGIN_NAME SYSREQ_EDOC_ENCRYPTION_PLUGIN_VERSION SYSREQ_EDOC_EXPORT_DATE SYSREQ_EDOC_EXPORTER SYSREQ_EDOC_KIND SYSREQ_EDOC_LIFE_STAGE_NAME SYSREQ_EDOC_LOCKED_FOR_SERVER_CODE SYSREQ_EDOC_MODIFIED SYSREQ_EDOC_NAME SYSREQ_EDOC_NOTE SYSREQ_EDOC_QUALIFIED_ID SYSREQ_EDOC_SESSION_KEY SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_NAME SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_VERSION SYSREQ_EDOC_SIGNATURE_TYPE SYSREQ_EDOC_SIGNED SYSREQ_EDOC_STORAGE SYSREQ_EDOC_STORAGES_ARCHIVE_STORAGE SYSREQ_EDOC_STORAGES_CHECK_RIGHTS SYSREQ_EDOC_STORAGES_COMPUTER_NAME SYSREQ_EDOC_STORAGES_EDIT_IN_STORAGE SYSREQ_EDOC_STORAGES_EXECUTIVE_STORAGE SYSREQ_EDOC_STORAGES_FUNCTION SYSREQ_EDOC_STORAGES_INITIALIZED SYSREQ_EDOC_STORAGES_LOCAL_PATH SYSREQ_EDOC_STORAGES_SAPERION_DATABASE_NAME SYSREQ_EDOC_STORAGES_SEARCH_BY_TEXT SYSREQ_EDOC_STORAGES_SERVER_NAME SYSREQ_EDOC_STORAGES_SHARED_SOURCE_NAME SYSREQ_EDOC_STORAGES_TYPE SYSREQ_EDOC_TEXT_MODIFIED SYSREQ_EDOC_TYPE_ACT_CODE SYSREQ_EDOC_TYPE_ACT_DESCRIPTION SYSREQ_EDOC_TYPE_ACT_DESCRIPTION_LOCALIZE_ID SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE_EXISTS SYSREQ_EDOC_TYPE_ACT_SECTION SYSREQ_EDOC_TYPE_ADD_PARAMS SYSREQ_EDOC_TYPE_COMMENT SYSREQ_EDOC_TYPE_EVENT_TEXT SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID SYSREQ_EDOC_TYPE_NAME_LOCALIZE_ID SYSREQ_EDOC_TYPE_NUMERATION_METHOD SYSREQ_EDOC_TYPE_PSEUDO_REQUISITE_CODE SYSREQ_EDOC_TYPE_REQ_CODE SYSREQ_EDOC_TYPE_REQ_DESCRIPTION SYSREQ_EDOC_TYPE_REQ_DESCRIPTION_LOCALIZE_ID SYSREQ_EDOC_TYPE_REQ_IS_LEADING SYSREQ_EDOC_TYPE_REQ_IS_REQUIRED SYSREQ_EDOC_TYPE_REQ_NUMBER SYSREQ_EDOC_TYPE_REQ_ON_CHANGE SYSREQ_EDOC_TYPE_REQ_ON_CHANGE_EXISTS SYSREQ_EDOC_TYPE_REQ_ON_SELECT SYSREQ_EDOC_TYPE_REQ_ON_SELECT_KIND SYSREQ_EDOC_TYPE_REQ_SECTION SYSREQ_EDOC_TYPE_VIEW_CARD SYSREQ_EDOC_TYPE_VIEW_CODE SYSREQ_EDOC_TYPE_VIEW_COMMENT SYSREQ_EDOC_TYPE_VIEW_IS_MAIN SYSREQ_EDOC_TYPE_VIEW_NAME SYSREQ_EDOC_TYPE_VIEW_NAME_LOCALIZE_ID SYSREQ_EDOC_VERSION_AUTHOR SYSREQ_EDOC_VERSION_CRC SYSREQ_EDOC_VERSION_DATA SYSREQ_EDOC_VERSION_EDITOR SYSREQ_EDOC_VERSION_EXPORT_DATE SYSREQ_EDOC_VERSION_EXPORTER SYSREQ_EDOC_VERSION_HIDDEN SYSREQ_EDOC_VERSION_LIFE_STAGE SYSREQ_EDOC_VERSION_MODIFIED SYSREQ_EDOC_VERSION_NOTE SYSREQ_EDOC_VERSION_SIGNATURE_TYPE SYSREQ_EDOC_VERSION_SIGNED SYSREQ_EDOC_VERSION_SIZE SYSREQ_EDOC_VERSION_SOURCE SYSREQ_EDOC_VERSION_TEXT_MODIFIED SYSREQ_EDOCKIND_DEFAULT_VERSION_STATE_CODE SYSREQ_FOLDER_KIND SYSREQ_FUNC_CATEGORY SYSREQ_FUNC_COMMENT SYSREQ_FUNC_GROUP SYSREQ_FUNC_GROUP_COMMENT SYSREQ_FUNC_GROUP_NUMBER SYSREQ_FUNC_HELP SYSREQ_FUNC_PARAM_DEF_VALUE SYSREQ_FUNC_PARAM_IDENT SYSREQ_FUNC_PARAM_NUMBER SYSREQ_FUNC_PARAM_TYPE SYSREQ_FUNC_TEXT SYSREQ_GROUP_CATEGORY SYSREQ_ID SYSREQ_LAST_UPDATE SYSREQ_LEADER_REFERENCE SYSREQ_LINE_NUMBER SYSREQ_MAIN_RECORD_ID SYSREQ_NAME SYSREQ_NAME_LOCALIZE_ID SYSREQ_NOTE SYSREQ_ORIGINAL_RECORD SYSREQ_OUR_FIRM SYSREQ_PROFILING_SETTINGS_BATCH_LOGING SYSREQ_PROFILING_SETTINGS_BATCH_SIZE SYSREQ_PROFILING_SETTINGS_PROFILING_ENABLED SYSREQ_PROFILING_SETTINGS_SQL_PROFILING_ENABLED SYSREQ_PROFILING_SETTINGS_START_LOGGED SYSREQ_RECORD_STATUS SYSREQ_REF_REQ_FIELD_NAME SYSREQ_REF_REQ_FORMAT SYSREQ_REF_REQ_GENERATED SYSREQ_REF_REQ_LENGTH SYSREQ_REF_REQ_PRECISION SYSREQ_REF_REQ_REFERENCE SYSREQ_REF_REQ_SECTION SYSREQ_REF_REQ_STORED SYSREQ_REF_REQ_TOKENS SYSREQ_REF_REQ_TYPE SYSREQ_REF_REQ_VIEW SYSREQ_REF_TYPE_ACT_CODE SYSREQ_REF_TYPE_ACT_DESCRIPTION SYSREQ_REF_TYPE_ACT_DESCRIPTION_LOCALIZE_ID SYSREQ_REF_TYPE_ACT_ON_EXECUTE SYSREQ_REF_TYPE_ACT_ON_EXECUTE_EXISTS SYSREQ_REF_TYPE_ACT_SECTION SYSREQ_REF_TYPE_ADD_PARAMS SYSREQ_REF_TYPE_COMMENT SYSREQ_REF_TYPE_COMMON_SETTINGS SYSREQ_REF_TYPE_DISPLAY_REQUISITE_NAME SYSREQ_REF_TYPE_EVENT_TEXT SYSREQ_REF_TYPE_MAIN_LEADING_REF SYSREQ_REF_TYPE_NAME_IN_SINGULAR SYSREQ_REF_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID SYSREQ_REF_TYPE_NAME_LOCALIZE_ID SYSREQ_REF_TYPE_NUMERATION_METHOD SYSREQ_REF_TYPE_REQ_CODE SYSREQ_REF_TYPE_REQ_DESCRIPTION SYSREQ_REF_TYPE_REQ_DESCRIPTION_LOCALIZE_ID SYSREQ_REF_TYPE_REQ_IS_CONTROL SYSREQ_REF_TYPE_REQ_IS_FILTER SYSREQ_REF_TYPE_REQ_IS_LEADING SYSREQ_REF_TYPE_REQ_IS_REQUIRED SYSREQ_REF_TYPE_REQ_NUMBER SYSREQ_REF_TYPE_REQ_ON_CHANGE SYSREQ_REF_TYPE_REQ_ON_CHANGE_EXISTS SYSREQ_REF_TYPE_REQ_ON_SELECT SYSREQ_REF_TYPE_REQ_ON_SELECT_KIND SYSREQ_REF_TYPE_REQ_SECTION SYSREQ_REF_TYPE_VIEW_CARD SYSREQ_REF_TYPE_VIEW_CODE SYSREQ_REF_TYPE_VIEW_COMMENT SYSREQ_REF_TYPE_VIEW_IS_MAIN SYSREQ_REF_TYPE_VIEW_NAME SYSREQ_REF_TYPE_VIEW_NAME_LOCALIZE_ID SYSREQ_REFERENCE_TYPE_ID SYSREQ_STATE SYSREQ_STATЕ SYSREQ_SYSTEM_SETTINGS_VALUE SYSREQ_TYPE SYSREQ_UNIT SYSREQ_UNIT_ID SYSREQ_USER_GROUPS_GROUP_FULL_NAME SYSREQ_USER_GROUPS_GROUP_NAME SYSREQ_USER_GROUPS_GROUP_SERVER_NAME SYSREQ_USERS_ACCESS_RIGHTS SYSREQ_USERS_AUTHENTICATION SYSREQ_USERS_CATEGORY SYSREQ_USERS_COMPONENT SYSREQ_USERS_COMPONENT_USER_IS_PUBLIC SYSREQ_USERS_DOMAIN SYSREQ_USERS_FULL_USER_NAME SYSREQ_USERS_GROUP SYSREQ_USERS_IS_MAIN_SERVER SYSREQ_USERS_LOGIN SYSREQ_USERS_REFERENCE_USER_IS_PUBLIC SYSREQ_USERS_STATUS SYSREQ_USERS_USER_CERTIFICATE SYSREQ_USERS_USER_CERTIFICATE_INFO SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_NAME SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_VERSION SYSREQ_USERS_USER_CERTIFICATE_STATE SYSREQ_USERS_USER_CERTIFICATE_SUBJECT_NAME SYSREQ_USERS_USER_CERTIFICATE_THUMBPRINT SYSREQ_USERS_USER_DEFAULT_CERTIFICATE SYSREQ_USERS_USER_DESCRIPTION SYSREQ_USERS_USER_GLOBAL_NAME SYSREQ_USERS_USER_LOGIN SYSREQ_USERS_USER_MAIN_SERVER SYSREQ_USERS_USER_TYPE SYSREQ_WORK_RULES_FOLDER_ID RESULT_VAR_NAME RESULT_VAR_NAME_ENG AUTO_NUMERATION_RULE_ID CANT_CHANGE_ID_REQUISITE_RULE_ID CANT_CHANGE_OURFIRM_REQUISITE_RULE_ID CHECK_CHANGING_REFERENCE_RECORD_USE_RULE_ID CHECK_CODE_REQUISITE_RULE_ID CHECK_DELETING_REFERENCE_RECORD_USE_RULE_ID CHECK_FILTRATER_CHANGES_RULE_ID CHECK_RECORD_INTERVAL_RULE_ID CHECK_REFERENCE_INTERVAL_RULE_ID CHECK_REQUIRED_DATA_FULLNESS_RULE_ID CHECK_REQUIRED_REQUISITES_FULLNESS_RULE_ID MAKE_RECORD_UNRATIFIED_RULE_ID RESTORE_AUTO_NUMERATION_RULE_ID SET_FIRM_CONTEXT_FROM_RECORD_RULE_ID SET_FIRST_RECORD_IN_LIST_FORM_RULE_ID SET_IDSPS_VALUE_RULE_ID SET_NEXT_CODE_VALUE_RULE_ID SET_OURFIRM_BOUNDS_RULE_ID SET_OURFIRM_REQUISITE_RULE_ID SCRIPT_BLOCK_AFTER_FINISH_EVENT SCRIPT_BLOCK_BEFORE_START_EVENT SCRIPT_BLOCK_EXECUTION_RESULTS_PROPERTY SCRIPT_BLOCK_NAME_PROPERTY SCRIPT_BLOCK_SCRIPT_PROPERTY SUBTASK_BLOCK_ABORT_DEADLINE_PROPERTY SUBTASK_BLOCK_AFTER_FINISH_EVENT SUBTASK_BLOCK_ASSIGN_PARAMS_EVENT SUBTASK_BLOCK_ATTACHMENTS_PROPERTY SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY SUBTASK_BLOCK_BEFORE_START_EVENT SUBTASK_BLOCK_CREATED_TASK_PROPERTY SUBTASK_BLOCK_CREATION_EVENT SUBTASK_BLOCK_DEADLINE_PROPERTY SUBTASK_BLOCK_IMPORTANCE_PROPERTY SUBTASK_BLOCK_INITIATOR_PROPERTY SUBTASK_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY SUBTASK_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY SUBTASK_BLOCK_JOBS_TYPE_PROPERTY SUBTASK_BLOCK_NAME_PROPERTY SUBTASK_BLOCK_PARALLEL_ROUTE_PROPERTY SUBTASK_BLOCK_PERFORMERS_PROPERTY SUBTASK_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY SUBTASK_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY SUBTASK_BLOCK_REQUIRE_SIGN_PROPERTY SUBTASK_BLOCK_STANDARD_ROUTE_PROPERTY SUBTASK_BLOCK_START_EVENT SUBTASK_BLOCK_STEP_CONTROL_PROPERTY SUBTASK_BLOCK_SUBJECT_PROPERTY SUBTASK_BLOCK_TASK_CONTROL_PROPERTY SUBTASK_BLOCK_TEXT_PROPERTY SUBTASK_BLOCK_UNLOCK_ATTACHMENTS_ON_STOP_PROPERTY SUBTASK_BLOCK_USE_STANDARD_ROUTE_PROPERTY SUBTASK_BLOCK_WAIT_FOR_TASK_COMPLETE_PROPERTY SYSCOMP_CONTROL_JOBS SYSCOMP_FOLDERS SYSCOMP_JOBS SYSCOMP_NOTICES SYSCOMP_TASKS SYSDLG_CREATE_EDOCUMENT SYSDLG_CREATE_EDOCUMENT_VERSION SYSDLG_CURRENT_PERIOD SYSDLG_EDIT_FUNCTION_HELP SYSDLG_EDOCUMENT_KINDS_FOR_TEMPLATE SYSDLG_EXPORT_MULTIPLE_EDOCUMENTS SYSDLG_EXPORT_SINGLE_EDOCUMENT SYSDLG_IMPORT_EDOCUMENT SYSDLG_MULTIPLE_SELECT SYSDLG_SETUP_ACCESS_RIGHTS SYSDLG_SETUP_DEFAULT_RIGHTS SYSDLG_SETUP_FILTER_CONDITION SYSDLG_SETUP_SIGN_RIGHTS SYSDLG_SETUP_TASK_OBSERVERS SYSDLG_SETUP_TASK_ROUTE SYSDLG_SETUP_USERS_LIST SYSDLG_SIGN_EDOCUMENT SYSDLG_SIGN_MULTIPLE_EDOCUMENTS SYSREF_ACCESS_RIGHTS_TYPES SYSREF_ADMINISTRATION_HISTORY SYSREF_ALL_AVAILABLE_COMPONENTS SYSREF_ALL_AVAILABLE_PRIVILEGES SYSREF_ALL_REPLICATING_COMPONENTS SYSREF_AVAILABLE_DEVELOPERS_COMPONENTS SYSREF_CALENDAR_EVENTS SYSREF_COMPONENT_TOKEN_HISTORY SYSREF_COMPONENT_TOKENS SYSREF_COMPONENTS SYSREF_CONSTANTS SYSREF_DATA_RECEIVE_PROTOCOL SYSREF_DATA_SEND_PROTOCOL SYSREF_DIALOGS SYSREF_DIALOGS_REQUISITES SYSREF_EDITORS SYSREF_EDOC_CARDS SYSREF_EDOC_TYPES SYSREF_EDOCUMENT_CARD_REQUISITES SYSREF_EDOCUMENT_CARD_TYPES SYSREF_EDOCUMENT_CARD_TYPES_REFERENCE SYSREF_EDOCUMENT_CARDS SYSREF_EDOCUMENT_HISTORY SYSREF_EDOCUMENT_KINDS SYSREF_EDOCUMENT_REQUISITES SYSREF_EDOCUMENT_SIGNATURES SYSREF_EDOCUMENT_TEMPLATES SYSREF_EDOCUMENT_TEXT_STORAGES SYSREF_EDOCUMENT_VIEWS SYSREF_FILTERER_SETUP_CONFLICTS SYSREF_FILTRATER_SETTING_CONFLICTS SYSREF_FOLDER_HISTORY SYSREF_FOLDERS SYSREF_FUNCTION_GROUPS SYSREF_FUNCTION_PARAMS SYSREF_FUNCTIONS SYSREF_JOB_HISTORY SYSREF_LINKS SYSREF_LOCALIZATION_DICTIONARY SYSREF_LOCALIZATION_LANGUAGES SYSREF_MODULES SYSREF_PRIVILEGES SYSREF_RECORD_HISTORY SYSREF_REFERENCE_REQUISITES SYSREF_REFERENCE_TYPE_VIEWS SYSREF_REFERENCE_TYPES SYSREF_REFERENCES SYSREF_REFERENCES_REQUISITES SYSREF_REMOTE_SERVERS SYSREF_REPLICATION_SESSIONS_LOG SYSREF_REPLICATION_SESSIONS_PROTOCOL SYSREF_REPORTS SYSREF_ROLES SYSREF_ROUTE_BLOCK_GROUPS SYSREF_ROUTE_BLOCKS SYSREF_SCRIPTS SYSREF_SEARCHES SYSREF_SERVER_EVENTS SYSREF_SERVER_EVENTS_HISTORY SYSREF_STANDARD_ROUTE_GROUPS SYSREF_STANDARD_ROUTES SYSREF_STATUSES SYSREF_SYSTEM_SETTINGS SYSREF_TASK_HISTORY SYSREF_TASK_KIND_GROUPS SYSREF_TASK_KINDS SYSREF_TASK_RIGHTS SYSREF_TASK_SIGNATURES SYSREF_TASKS SYSREF_UNITS SYSREF_USER_GROUPS SYSREF_USER_GROUPS_REFERENCE SYSREF_USER_SUBSTITUTION SYSREF_USERS SYSREF_USERS_REFERENCE SYSREF_VIEWERS SYSREF_WORKING_TIME_CALENDARS ACCESS_RIGHTS_TABLE_NAME EDMS_ACCESS_TABLE_NAME EDOC_TYPES_TABLE_NAME TEST_DEV_DB_NAME TEST_DEV_SYSTEM_CODE TEST_EDMS_DB_NAME TEST_EDMS_MAIN_CODE TEST_EDMS_MAIN_DB_NAME TEST_EDMS_SECOND_CODE TEST_EDMS_SECOND_DB_NAME TEST_EDMS_SYSTEM_CODE TEST_ISB5_MAIN_CODE TEST_ISB5_SECOND_CODE TEST_SQL_SERVER_2005_NAME TEST_SQL_SERVER_NAME ATTENTION_CAPTION cbsCommandLinks cbsDefault CONFIRMATION_CAPTION ERROR_CAPTION INFORMATION_CAPTION mrCancel mrOk EDOC_VERSION_ACTIVE_STAGE_CODE EDOC_VERSION_DESIGN_STAGE_CODE EDOC_VERSION_OBSOLETE_STAGE_CODE cpDataEnciphermentEnabled cpDigitalSignatureEnabled cpID cpIssuer cpPluginVersion cpSerial cpSubjectName cpSubjSimpleName cpValidFromDate cpValidToDate ISBL_SYNTAX NO_SYNTAX XML_SYNTAX WAIT_BLOCK_AFTER_FINISH_EVENT WAIT_BLOCK_BEFORE_START_EVENT WAIT_BLOCK_DEADLINE_PROPERTY WAIT_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY WAIT_BLOCK_NAME_PROPERTY WAIT_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY SYSRES_COMMON SYSRES_CONST SYSRES_MBFUNC SYSRES_SBDATA SYSRES_SBGUI SYSRES_SBINTF SYSRES_SBREFDSC SYSRES_SQLERRORS SYSRES_SYSCOMP atUser atGroup atRole aemEnabledAlways aemDisabledAlways aemEnabledOnBrowse aemEnabledOnEdit aemDisabledOnBrowseEmpty apBegin apEnd alLeft alRight asmNever asmNoButCustomize asmAsLastTime asmYesButCustomize asmAlways cirCommon cirRevoked ctSignature ctEncode ctSignatureEncode clbUnchecked clbChecked clbGrayed ceISB ceAlways ceNever ctDocument ctReference ctScript ctUnknown ctReport ctDialog ctFunction ctFolder ctEDocument ctTask ctJob ctNotice ctControlJob cfInternal cfDisplay ciUnspecified ciWrite ciRead ckFolder ckEDocument ckTask ckJob ckComponentToken ckAny ckReference ckScript ckReport ckDialog ctISBLEditor ctBevel ctButton ctCheckListBox ctComboBox ctComboEdit ctGrid ctDBCheckBox ctDBComboBox ctDBEdit ctDBEllipsis ctDBMemo ctDBNavigator ctDBRadioGroup ctDBStatusLabel ctEdit ctGroupBox ctInplaceHint ctMemo ctPanel ctListBox ctRadioButton ctRichEdit ctTabSheet ctWebBrowser ctImage ctHyperLink ctLabel ctDBMultiEllipsis ctRibbon ctRichView ctInnerPanel ctPanelGroup ctBitButton cctDate cctInteger cctNumeric cctPick cctReference cctString cctText cltInternal cltPrimary cltGUI dseBeforeOpen dseAfterOpen dseBeforeClose dseAfterClose dseOnValidDelete dseBeforeDelete dseAfterDelete dseAfterDeleteOutOfTransaction dseOnDeleteError dseBeforeInsert dseAfterInsert dseOnValidUpdate dseBeforeUpdate dseOnUpdateRatifiedRecord dseAfterUpdate dseAfterUpdateOutOfTransaction dseOnUpdateError dseAfterScroll dseOnOpenRecord dseOnCloseRecord dseBeforeCancel dseAfterCancel dseOnUpdateDeadlockError dseBeforeDetailUpdate dseOnPrepareUpdate dseOnAnyRequisiteChange dssEdit dssInsert dssBrowse dssInActive dftDate dftShortDate dftDateTime dftTimeStamp dotDays dotHours dotMinutes dotSeconds dtkndLocal dtkndUTC arNone arView arEdit arFull ddaView ddaEdit emLock emEdit emSign emExportWithLock emImportWithUnlock emChangeVersionNote emOpenForModify emChangeLifeStage emDelete emCreateVersion emImport emUnlockExportedWithLock emStart emAbort emReInit emMarkAsReaded emMarkAsUnreaded emPerform emAccept emResume emChangeRights emEditRoute emEditObserver emRecoveryFromLocalCopy emChangeWorkAccessType emChangeEncodeTypeToCertificate emChangeEncodeTypeToPassword emChangeEncodeTypeToNone emChangeEncodeTypeToCertificatePassword emChangeStandardRoute emGetText emOpenForView emMoveToStorage emCreateObject emChangeVersionHidden emDeleteVersion emChangeLifeCycleStage emApprovingSign emExport emContinue emLockFromEdit emUnLockForEdit emLockForServer emUnlockFromServer emDelegateAccessRights emReEncode ecotFile ecotProcess eaGet eaCopy eaCreate eaCreateStandardRoute edltAll edltNothing edltQuery essmText essmCard esvtLast esvtLastActive esvtSpecified edsfExecutive edsfArchive edstSQLServer edstFile edvstNone edvstEDocumentVersionCopy edvstFile edvstTemplate edvstScannedFile vsDefault vsDesign vsActive vsObsolete etNone etCertificate etPassword etCertificatePassword ecException ecWarning ecInformation estAll estApprovingOnly evtLast evtLastActive evtQuery fdtString fdtNumeric fdtInteger fdtDate fdtText fdtUnknown fdtWideString fdtLargeInteger ftInbox ftOutbox ftFavorites ftCommonFolder ftUserFolder ftComponents ftQuickLaunch ftShortcuts ftSearch grhAuto grhX1 grhX2 grhX3 hltText hltRTF hltHTML iffBMP iffJPEG iffMultiPageTIFF iffSinglePageTIFF iffTIFF iffPNG im8bGrayscale im24bRGB im1bMonochrome itBMP itJPEG itWMF itPNG ikhInformation ikhWarning ikhError ikhNoIcon icUnknown icScript icFunction icIntegratedReport icAnalyticReport icDataSetEventHandler icActionHandler icFormEventHandler icLookUpEventHandler icRequisiteChangeEventHandler icBeforeSearchEventHandler icRoleCalculation icSelectRouteEventHandler icBlockPropertyCalculation icBlockQueryParamsEventHandler icChangeSearchResultEventHandler icBlockEventHandler icSubTaskInitEventHandler icEDocDataSetEventHandler icEDocLookUpEventHandler icEDocActionHandler icEDocFormEventHandler icEDocRequisiteChangeEventHandler icStructuredConversionRule icStructuredConversionEventBefore icStructuredConversionEventAfter icWizardEventHandler icWizardFinishEventHandler icWizardStepEventHandler icWizardStepFinishEventHandler icWizardActionEnableEventHandler icWizardActionExecuteEventHandler icCreateJobsHandler icCreateNoticesHandler icBeforeLookUpEventHandler icAfterLookUpEventHandler icTaskAbortEventHandler icWorkflowBlockActionHandler icDialogDataSetEventHandler icDialogActionHandler icDialogLookUpEventHandler icDialogRequisiteChangeEventHandler icDialogFormEventHandler icDialogValidCloseEventHandler icBlockFormEventHandler icTaskFormEventHandler icReferenceMethod icEDocMethod icDialogMethod icProcessMessageHandler isShow isHide isByUserSettings jkJob jkNotice jkControlJob jtInner jtLeft jtRight jtFull jtCross lbpAbove lbpBelow lbpLeft lbpRight eltPerConnection eltPerUser sfcUndefined sfcBlack sfcGreen sfcRed sfcBlue sfcOrange sfcLilac sfsItalic sfsStrikeout sfsNormal ldctStandardRoute ldctWizard ldctScript ldctFunction ldctRouteBlock ldctIntegratedReport ldctAnalyticReport ldctReferenceType ldctEDocumentType ldctDialog ldctServerEvents mrcrtNone mrcrtUser mrcrtMaximal mrcrtCustom vtEqual vtGreaterOrEqual vtLessOrEqual vtRange rdYesterday rdToday rdTomorrow rdThisWeek rdThisMonth rdThisYear rdNextMonth rdNextWeek rdLastWeek rdLastMonth rdWindow rdFile rdPrinter rdtString rdtNumeric rdtInteger rdtDate rdtReference rdtAccount rdtText rdtPick rdtUnknown rdtLargeInteger rdtDocument reOnChange reOnChangeValues ttGlobal ttLocal ttUser ttSystem ssmBrowse ssmSelect ssmMultiSelect ssmBrowseModal smSelect smLike smCard stNone stAuthenticating stApproving sctString sctStream sstAnsiSort sstNaturalSort svtEqual svtContain soatString soatNumeric soatInteger soatDatetime soatReferenceRecord soatText soatPick soatBoolean soatEDocument soatAccount soatIntegerCollection soatNumericCollection soatStringCollection soatPickCollection soatDatetimeCollection soatBooleanCollection soatReferenceRecordCollection soatEDocumentCollection soatAccountCollection soatContents soatUnknown tarAbortByUser tarAbortByWorkflowException tvtAllWords tvtExactPhrase tvtAnyWord usNone usCompleted usRedSquare usBlueSquare usYellowSquare usGreenSquare usOrangeSquare usPurpleSquare usFollowUp utUnknown utUser utDeveloper utAdministrator utSystemDeveloper utDisconnected btAnd btDetailAnd btOr btNotOr btOnly vmView vmSelect vmNavigation vsmSingle vsmMultiple vsmMultipleCheck vsmNoSelection wfatPrevious wfatNext wfatCancel wfatFinish wfepUndefined wfepText3 wfepText6 wfepText9 wfepSpinEdit wfepDropDown wfepRadioGroup wfepFlag wfepText12 wfepText15 wfepText18 wfepText21 wfepText24 wfepText27 wfepText30 wfepRadioGroupColumn1 wfepRadioGroupColumn2 wfepRadioGroupColumn3 wfetQueryParameter wfetText wfetDelimiter wfetLabel wptString wptInteger wptNumeric wptBoolean wptDateTime wptPick wptText wptUser wptUserList wptEDocumentInfo wptEDocumentInfoList wptReferenceRecordInfo wptReferenceRecordInfoList wptFolderInfo wptTaskInfo wptContents wptFileName wptDate wsrComplete wsrGoNext wsrGoPrevious wsrCustom wsrCancel wsrGoFinal wstForm wstEDocument wstTaskCard wstReferenceRecordCard wstFinal waAll waPerformers waManual wsbStart wsbFinish wsbNotice wsbStep wsbDecision wsbWait wsbMonitor wsbScript wsbConnector wsbSubTask wsbLifeCycleStage wsbPause wdtInteger wdtFloat wdtString wdtPick wdtDateTime wdtBoolean wdtTask wdtJob wdtFolder wdtEDocument wdtReferenceRecord wdtUser wdtGroup wdtRole wdtIntegerCollection wdtFloatCollection wdtStringCollection wdtPickCollection wdtDateTimeCollection wdtBooleanCollection wdtTaskCollection wdtJobCollection wdtFolderCollection wdtEDocumentCollection wdtReferenceRecordCollection wdtUserCollection wdtGroupCollection wdtRoleCollection wdtContents wdtUserList wdtSearchDescription wdtDeadLine wdtPickSet wdtAccountCollection wiLow wiNormal wiHigh wrtSoft wrtHard wsInit wsRunning wsDone wsControlled wsAborted wsContinued wtmFull wtmFromCurrent wtmOnlyCurrent ",class:"AltState Application CallType ComponentTokens CreatedJobs CreatedNotices ControlState DialogResult Dialogs EDocuments EDocumentVersionSource Folders GlobalIDs Job Jobs InputValue LookUpReference LookUpRequisiteNames LookUpSearch Object ParentComponent Processes References Requisite ReportName Reports Result Scripts Searches SelectedAttachments SelectedItems SelectMode Sender ServerEvents ServiceFactory ShiftState SubTask SystemDialogs Tasks Wizard Wizards Work ВызовСпособ ИмяОтчета РеквЗнач ",literal:"null true false nil "},s={begin:"\\.\\s*"+e.UNDERSCORE_IDENT_RE,keywords:o,relevance:0},l={className:"type",begin:":[ \\t]*("+"IApplication IAccessRights IAccountRepository IAccountSelectionRestrictions IAction IActionList IAdministrationHistoryDescription IAnchors IApplication IArchiveInfo IAttachment IAttachmentList ICheckListBox ICheckPointedList IColumn IComponent IComponentDescription IComponentToken IComponentTokenFactory IComponentTokenInfo ICompRecordInfo IConnection IContents IControl IControlJob IControlJobInfo IControlList ICrypto ICrypto2 ICustomJob ICustomJobInfo ICustomListBox ICustomObjectWizardStep ICustomWork ICustomWorkInfo IDataSet IDataSetAccessInfo IDataSigner IDateCriterion IDateRequisite IDateRequisiteDescription IDateValue IDeaAccessRights IDeaObjectInfo IDevelopmentComponentLock IDialog IDialogFactory IDialogPickRequisiteItems IDialogsFactory IDICSFactory IDocRequisite IDocumentInfo IDualListDialog IECertificate IECertificateInfo IECertificates IEditControl IEditorForm IEdmsExplorer IEdmsObject IEdmsObjectDescription IEdmsObjectFactory IEdmsObjectInfo IEDocument IEDocumentAccessRights IEDocumentDescription IEDocumentEditor IEDocumentFactory IEDocumentInfo IEDocumentStorage IEDocumentVersion IEDocumentVersionListDialog IEDocumentVersionSource IEDocumentWizardStep IEDocVerSignature IEDocVersionState IEnabledMode IEncodeProvider IEncrypter IEvent IEventList IException IExternalEvents IExternalHandler IFactory IField IFileDialog IFolder IFolderDescription IFolderDialog IFolderFactory IFolderInfo IForEach IForm IFormTitle IFormWizardStep IGlobalIDFactory IGlobalIDInfo IGrid IHasher IHistoryDescription IHyperLinkControl IImageButton IImageControl IInnerPanel IInplaceHint IIntegerCriterion IIntegerList IIntegerRequisite IIntegerValue IISBLEditorForm IJob IJobDescription IJobFactory IJobForm IJobInfo ILabelControl ILargeIntegerCriterion ILargeIntegerRequisite ILargeIntegerValue ILicenseInfo ILifeCycleStage IList IListBox ILocalIDInfo ILocalization ILock IMemoryDataSet IMessagingFactory IMetadataRepository INotice INoticeInfo INumericCriterion INumericRequisite INumericValue IObject IObjectDescription IObjectImporter IObjectInfo IObserver IPanelGroup IPickCriterion IPickProperty IPickRequisite IPickRequisiteDescription IPickRequisiteItem IPickRequisiteItems IPickValue IPrivilege IPrivilegeList IProcess IProcessFactory IProcessMessage IProgress IProperty IPropertyChangeEvent IQuery IReference IReferenceCriterion IReferenceEnabledMode IReferenceFactory IReferenceHistoryDescription IReferenceInfo IReferenceRecordCardWizardStep IReferenceRequisiteDescription IReferencesFactory IReferenceValue IRefRequisite IReport IReportFactory IRequisite IRequisiteDescription IRequisiteDescriptionList IRequisiteFactory IRichEdit IRouteStep IRule IRuleList ISchemeBlock IScript IScriptFactory ISearchCriteria ISearchCriterion ISearchDescription ISearchFactory ISearchFolderInfo ISearchForObjectDescription ISearchResultRestrictions ISecuredContext ISelectDialog IServerEvent IServerEventFactory IServiceDialog IServiceFactory ISignature ISignProvider ISignProvider2 ISignProvider3 ISimpleCriterion IStringCriterion IStringList IStringRequisite IStringRequisiteDescription IStringValue ISystemDialogsFactory ISystemInfo ITabSheet ITask ITaskAbortReasonInfo ITaskCardWizardStep ITaskDescription ITaskFactory ITaskInfo ITaskRoute ITextCriterion ITextRequisite ITextValue ITreeListSelectDialog IUser IUserList IValue IView IWebBrowserControl IWizard IWizardAction IWizardFactory IWizardFormElement IWizardParam IWizardPickParam IWizardReferenceParam IWizardStep IWorkAccessRights IWorkDescription IWorkflowAskableParam IWorkflowAskableParams IWorkflowBlock IWorkflowBlockResult IWorkflowEnabledMode IWorkflowParam IWorkflowPickParam IWorkflowReferenceParam IWorkState IWorkTreeCustomNode IWorkTreeJobNode IWorkTreeTaskNode IXMLEditorForm SBCrypto ".trim().replace(/\s/g,"|")+")",end:"[ \\t]*=",excludeEnd:!0},c={className:"variable",keywords:o,begin:t,relevance:0,contains:[l,s]},d="[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]*\\(";return{name:"ISBL",case_insensitive:!0,keywords:o,illegal:"\\$|\\?|%|,|;$|~|#|@|</",contains:[{className:"function",begin:d,end:"\\)$",returnBegin:!0,keywords:o,illegal:"[\\[\\]\\|\\$\\?%,~#@]",contains:[{className:"title",keywords:{$pattern:t,built_in:"AddSubString AdjustLineBreaks AmountInWords Analysis ArrayDimCount ArrayHighBound ArrayLowBound ArrayOf ArrayReDim Assert Assigned BeginOfMonth BeginOfPeriod BuildProfilingOperationAnalysis CallProcedure CanReadFile CArrayElement CDataSetRequisite ChangeDate ChangeReferenceDataset Char CharPos CheckParam CheckParamValue CompareStrings ConstantExists ControlState ConvertDateStr Copy CopyFile CreateArray CreateCachedReference CreateConnection CreateDialog CreateDualListDialog CreateEditor CreateException CreateFile CreateFolderDialog CreateInputDialog CreateLinkFile CreateList CreateLock CreateMemoryDataSet CreateObject CreateOpenDialog CreateProgress CreateQuery CreateReference CreateReport CreateSaveDialog CreateScript CreateSQLPivotFunction CreateStringList CreateTreeListSelectDialog CSelectSQL CSQL CSubString CurrentUserID CurrentUserName CurrentVersion DataSetLocateEx DateDiff DateTimeDiff DateToStr DayOfWeek DeleteFile DirectoryExists DisableCheckAccessRights DisableCheckFullShowingRestriction DisableMassTaskSendingRestrictions DropTable DupeString EditText EnableCheckAccessRights EnableCheckFullShowingRestriction EnableMassTaskSendingRestrictions EndOfMonth EndOfPeriod ExceptionExists ExceptionsOff ExceptionsOn Execute ExecuteProcess Exit ExpandEnvironmentVariables ExtractFileDrive ExtractFileExt ExtractFileName ExtractFilePath ExtractParams FileExists FileSize FindFile FindSubString FirmContext ForceDirectories Format FormatDate FormatNumeric FormatSQLDate FormatString FreeException GetComponent GetComponentLaunchParam GetConstant GetLastException GetReferenceRecord GetRefTypeByRefID GetTableID GetTempFolder IfThen In IndexOf InputDialog InputDialogEx InteractiveMode IsFileLocked IsGraphicFile IsNumeric Length LoadString LoadStringFmt LocalTimeToUTC LowerCase Max MessageBox MessageBoxEx MimeDecodeBinary MimeDecodeString MimeEncodeBinary MimeEncodeString Min MoneyInWords MoveFile NewID Now OpenFile Ord Precision Raise ReadCertificateFromFile ReadFile ReferenceCodeByID ReferenceNumber ReferenceRequisiteMode ReferenceRequisiteValue RegionDateSettings RegionNumberSettings RegionTimeSettings RegRead RegWrite RenameFile Replace Round SelectServerCode SelectSQL ServerDateTime SetConstant SetManagedFolderFieldsState ShowConstantsInputDialog ShowMessage Sleep Split SQL SQL2XLSTAB SQLProfilingSendReport StrToDate SubString SubStringCount SystemSetting Time TimeDiff Today Transliterate Trim UpperCase UserStatus UTCToLocalTime ValidateXML VarIsClear VarIsEmpty VarIsNull WorkTimeDiff WriteFile WriteFileEx WriteObjectHistory Анализ БазаДанных БлокЕсть БлокЕстьРасш БлокИнфо БлокСнять БлокСнятьРасш БлокУстановить Ввод ВводМеню ВедС ВедСпр ВерхняяГраницаМассива ВнешПрогр Восст ВременнаяПапка Время ВыборSQL ВыбратьЗапись ВыделитьСтр Вызвать Выполнить ВыпПрогр ГрафическийФайл ГруппаДополнительно ДатаВремяСерв ДеньНедели ДиалогДаНет ДлинаСтр ДобПодстр ЕПусто ЕслиТо ЕЧисло ЗамПодстр ЗаписьСправочника ЗначПоляСпр ИДТипСпр ИзвлечьДиск ИзвлечьИмяФайла ИзвлечьПуть ИзвлечьРасширение ИзмДат ИзменитьРазмерМассива ИзмеренийМассива ИмяОрг ИмяПоляСпр Индекс ИндикаторЗакрыть ИндикаторОткрыть ИндикаторШаг ИнтерактивныйРежим ИтогТблСпр КодВидВедСпр КодВидСпрПоИД КодПоAnalit КодСимвола КодСпр КолПодстр КолПроп КонМес Конст КонстЕсть КонстЗнач КонТран КопироватьФайл КопияСтр КПериод КСтрТблСпр Макс МаксСтрТблСпр Массив Меню МенюРасш Мин НаборДанныхНайтиРасш НаимВидСпр НаимПоAnalit НаимСпр НастроитьПереводыСтрок НачМес НачТран НижняяГраницаМассива НомерСпр НПериод Окно Окр Окружение ОтлИнфДобавить ОтлИнфУдалить Отчет ОтчетАнал ОтчетИнт ПапкаСуществует Пауза ПВыборSQL ПереименоватьФайл Переменные ПереместитьФайл Подстр ПоискПодстр ПоискСтр ПолучитьИДТаблицы ПользовательДополнительно ПользовательИД ПользовательИмя ПользовательСтатус Прервать ПроверитьПараметр ПроверитьПараметрЗнач ПроверитьУсловие РазбСтр РазнВремя РазнДат РазнДатаВремя РазнРабВремя РегУстВрем РегУстДат РегУстЧсл РедТекст РеестрЗапись РеестрСписокИменПарам РеестрЧтение РеквСпр РеквСпрПр Сегодня Сейчас Сервер СерверПроцессИД СертификатФайлСчитать СжПроб Символ СистемаДиректумКод СистемаИнформация СистемаКод Содержит СоединениеЗакрыть СоединениеОткрыть СоздатьДиалог СоздатьДиалогВыбораИзДвухСписков СоздатьДиалогВыбораПапки СоздатьДиалогОткрытияФайла СоздатьДиалогСохраненияФайла СоздатьЗапрос СоздатьИндикатор СоздатьИсключение СоздатьКэшированныйСправочник СоздатьМассив СоздатьНаборДанных СоздатьОбъект СоздатьОтчет СоздатьПапку СоздатьРедактор СоздатьСоединение СоздатьСписок СоздатьСписокСтрок СоздатьСправочник СоздатьСценарий СоздСпр СостСпр Сохр СохрСпр СписокСистем Спр Справочник СпрБлокЕсть СпрБлокСнять СпрБлокСнятьРасш СпрБлокУстановить СпрИзмНабДан СпрКод СпрНомер СпрОбновить СпрОткрыть СпрОтменить СпрПарам СпрПолеЗнач СпрПолеИмя СпрРекв СпрРеквВведЗн СпрРеквНовые СпрРеквПр СпрРеквПредЗн СпрРеквРежим СпрРеквТипТекст СпрСоздать СпрСост СпрСохранить СпрТблИтог СпрТблСтр СпрТблСтрКол СпрТблСтрМакс СпрТблСтрМин СпрТблСтрПред СпрТблСтрСлед СпрТблСтрСозд СпрТблСтрУд СпрТекПредст СпрУдалить СравнитьСтр СтрВерхРегистр СтрНижнРегистр СтрТблСпр СумПроп Сценарий СценарийПарам ТекВерсия ТекОрг Точн Тран Транслитерация УдалитьТаблицу УдалитьФайл УдСпр УдСтрТблСпр Уст УстановкиКонстант ФайлАтрибутСчитать ФайлАтрибутУстановить ФайлВремя ФайлВремяУстановить ФайлВыбрать ФайлЗанят ФайлЗаписать ФайлИскать ФайлКопировать ФайлМожноЧитать ФайлОткрыть ФайлПереименовать ФайлПерекодировать ФайлПереместить ФайлПросмотреть ФайлРазмер ФайлСоздать ФайлСсылкаСоздать ФайлСуществует ФайлСчитать ФайлУдалить ФмтSQLДат ФмтДат ФмтСтр ФмтЧсл Формат ЦМассивЭлемент ЦНаборДанныхРеквизит ЦПодстр "},begin:d,end:"\\(",returnBegin:!0,excludeEnd:!0},s,c,n,r,i]},l,s,c,n,r,i]}}),z_)),zf.registerLanguage("java",function(){if(H_)return q_;H_=1;var e="[0-9](_*[0-9])*",t=`\\.(${e})`,r="[0-9a-fA-F](_*[0-9a-fA-F])*",n={className:"number",variants:[{begin:`(\\b(${e})((${t})|\\.)?|(${t}))[eE][+-]?(${e})[fFdD]?\\b`},{begin:`\\b(${e})((${t})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${t})[fFdD]?\\b`},{begin:`\\b(${e})[fFdD]\\b`},{begin:`\\b0[xX]((${r})\\.?|(${r})?\\.(${r}))[pP][+-]?(${e})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${r})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function a(e,t,r){return-1===r?"":e.replace(t,n=>a(e,t,r-1))}return q_=function(e){const t=e.regex,r="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",i=r+a("(?:<"+r+"~~~(?:\\s*,\\s*"+r+"~~~)*>)?",/~~~/g,2),o={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},s={className:"meta",begin:"@"+r,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},l={className:"params",begin:/\(/,end:/\)/,keywords:o,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:o,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[t.concat(/(?!else)/,r),/\s+/,r,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,r],className:{1:"keyword",3:"title.class"},contains:[l,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+i+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:o,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:o,relevance:0,contains:[s,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,n,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},n,s]}},q_}()),zf.registerLanguage("javascript",function(){if($_)return V_;$_=1;const e="[A-Za-z$_][0-9A-Za-z$_]*",t=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],r=["true","false","null","undefined","NaN","Infinity"],n=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],a=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],i=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],o=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],s=[].concat(i,n,a);return V_=function(l){const c=l.regex,d=e,u="<>",p="</>",_={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const r=e[0].length+e.index,n=e.input[r];if("<"===n||","===n)return void t.ignoreMatch();let a;">"===n&&(((e,{after:t})=>{const r="</"+e[0].slice(1);return-1!==e.input.indexOf(r,t)})(e,{after:r})||t.ignoreMatch());const i=e.input.substring(r);((a=i.match(/^\s*=/))||(a=i.match(/^\s+extends\s+/))&&0===a.index)&&t.ignoreMatch()}},m={$pattern:e,keyword:t,literal:r,built_in:s,"variable.language":o},g="[0-9](_?[0-9])*",h=`\\.(${g})`,f="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",E={className:"number",variants:[{begin:`(\\b(${f})((${h})|\\.)?|(${h}))[eE][+-]?(${g})\\b`},{begin:`\\b(${f})\\b((${h})\\b|\\.)?|(${h})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},b={className:"subst",begin:"\\$\\{",end:"\\}",keywords:m,contains:[]},S={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[l.BACKSLASH_ESCAPE,b],subLanguage:"xml"}},v={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[l.BACKSLASH_ESCAPE,b],subLanguage:"css"}},T={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[l.BACKSLASH_ESCAPE,b],subLanguage:"graphql"}},y={className:"string",begin:"`",end:"`",contains:[l.BACKSLASH_ESCAPE,b]},C={className:"comment",variants:[l.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:d+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),l.C_BLOCK_COMMENT_MODE,l.C_LINE_COMMENT_MODE]},N=[l.APOS_STRING_MODE,l.QUOTE_STRING_MODE,S,v,T,y,{match:/\$\d+/},E];b.contains=N.concat({begin:/\{/,end:/\}/,keywords:m,contains:["self"].concat(N)});const R=[].concat(C,b.contains),A=R.concat([{begin:/(\s*)\(/,end:/\)/,keywords:m,contains:["self"].concat(R)}]),O={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:m,contains:A},I={variants:[{match:[/class/,/\s+/,d,/\s+/,/extends/,/\s+/,c.concat(d,"(",c.concat(/\./,d),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,d],scope:{1:"keyword",3:"title.class"}}]},x={relevance:0,match:c.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...n,...a]}},w={variants:[{match:[/function/,/\s+/,d,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[O],illegal:/%/},D={match:c.concat(/\b/,function(e){return c.concat("(?!",e.join("|"),")")}([...i,"super","import"].map(e=>`${e}\\s*\\(`)),d,c.lookahead(/\s*\(/)),className:"title.function",relevance:0},M={begin:c.concat(/\./,c.lookahead(c.concat(d,/(?![0-9A-Za-z$_(])/))),end:d,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},k={match:[/get|set/,/\s+/,d,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},O]},L="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+l.UNDERSCORE_IDENT_RE+")\\s*=>",P={match:[/const|var|let/,/\s+/,d,/\s*/,/=\s*/,/(async\s*)?/,c.lookahead(L)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[O]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:m,exports:{PARAMS_CONTAINS:A,CLASS_REFERENCE:x},illegal:/#(?![$_A-z])/,contains:[l.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},l.APOS_STRING_MODE,l.QUOTE_STRING_MODE,S,v,T,y,C,{match:/\$\d+/},E,x,{scope:"attr",match:d+c.lookahead(":"),relevance:0},P,{begin:"("+l.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[C,l.REGEXP_MODE,{className:"function",begin:L,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:l.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:m,contains:A}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:u,end:p},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:_.begin,"on:begin":_.isTrulyOpeningTag,end:_.end}],subLanguage:"xml",contains:[{begin:_.begin,end:_.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+l.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[O,l.inherit(l.TITLE_MODE,{begin:d,className:"title.function"})]},{match:/\.\.\./,relevance:0},M,{match:"\\$"+d,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[O]},D,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},I,k,{match:/\$[(.]/}]}},V_}()),zf.registerLanguage("jboss-cli",(j_||(j_=1,W_=function(e){const t={className:"params",begin:/\(/,end:/\)/,contains:[{begin:/[\w-]+ *=/,returnBegin:!0,relevance:0,contains:[{className:"attr",begin:/[\w-]+/}]}],relevance:0};return{name:"JBoss CLI",aliases:["wildfly-cli"],keywords:{$pattern:"[a-z-]+",keyword:"alias batch cd clear command connect connection-factory connection-info data-source deploy deployment-info deployment-overlay echo echo-dmr help history if jdbc-driver-info jms-queue|20 jms-topic|20 ls patch pwd quit read-attribute read-operation reload rollout-plan run-batch set shutdown try unalias undeploy unset version xa-data-source",literal:"true false"},contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,{className:"params",begin:/--[\w\-=\/]+/},{className:"function",begin:/:[\w\-.]+/,relevance:0},{className:"string",begin:/\B([\/.])[\w\-.\/=]+/},t]}}),W_)),zf.registerLanguage("json",(K_||(K_=1,Q_=function(e){const t=["true","false","null"],r={scope:"literal",beginKeywords:t.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:t},contains:[{className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{match:/[{}[\],:]/,className:"punctuation",relevance:0},e.QUOTE_STRING_MODE,r,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}),Q_)),zf.registerLanguage("julia",(Z_||(Z_=1,X_=function(e){const t="[A-Za-z_\\u00A1-\\uFFFF][A-Za-z_0-9\\u00A1-\\uFFFF]*",r={$pattern:t,keyword:["baremodule","begin","break","catch","ccall","const","continue","do","else","elseif","end","export","false","finally","for","function","global","if","import","in","isa","let","local","macro","module","quote","return","true","try","using","where","while"],literal:["ARGS","C_NULL","DEPOT_PATH","ENDIAN_BOM","ENV","Inf","Inf16","Inf32","Inf64","InsertionSort","LOAD_PATH","MergeSort","NaN","NaN16","NaN32","NaN64","PROGRAM_FILE","QuickSort","RoundDown","RoundFromZero","RoundNearest","RoundNearestTiesAway","RoundNearestTiesUp","RoundToZero","RoundUp","VERSION|0","devnull","false","im","missing","nothing","pi","stderr","stdin","stdout","true","undef","π","ℯ"],built_in:["AbstractArray","AbstractChannel","AbstractChar","AbstractDict","AbstractDisplay","AbstractFloat","AbstractIrrational","AbstractMatrix","AbstractRange","AbstractSet","AbstractString","AbstractUnitRange","AbstractVecOrMat","AbstractVector","Any","ArgumentError","Array","AssertionError","BigFloat","BigInt","BitArray","BitMatrix","BitSet","BitVector","Bool","BoundsError","CapturedException","CartesianIndex","CartesianIndices","Cchar","Cdouble","Cfloat","Channel","Char","Cint","Cintmax_t","Clong","Clonglong","Cmd","Colon","Complex","ComplexF16","ComplexF32","ComplexF64","CompositeException","Condition","Cptrdiff_t","Cshort","Csize_t","Cssize_t","Cstring","Cuchar","Cuint","Cuintmax_t","Culong","Culonglong","Cushort","Cvoid","Cwchar_t","Cwstring","DataType","DenseArray","DenseMatrix","DenseVecOrMat","DenseVector","Dict","DimensionMismatch","Dims","DivideError","DomainError","EOFError","Enum","ErrorException","Exception","ExponentialBackOff","Expr","Float16","Float32","Float64","Function","GlobalRef","HTML","IO","IOBuffer","IOContext","IOStream","IdDict","IndexCartesian","IndexLinear","IndexStyle","InexactError","InitError","Int","Int128","Int16","Int32","Int64","Int8","Integer","InterruptException","InvalidStateException","Irrational","KeyError","LinRange","LineNumberNode","LinearIndices","LoadError","MIME","Matrix","Method","MethodError","Missing","MissingException","Module","NTuple","NamedTuple","Nothing","Number","OrdinalRange","OutOfMemoryError","OverflowError","Pair","PartialQuickSort","PermutedDimsArray","Pipe","ProcessFailedException","Ptr","QuoteNode","Rational","RawFD","ReadOnlyMemoryError","Real","ReentrantLock","Ref","Regex","RegexMatch","RoundingMode","SegmentationFault","Set","Signed","Some","StackOverflowError","StepRange","StepRangeLen","StridedArray","StridedMatrix","StridedVecOrMat","StridedVector","String","StringIndexError","SubArray","SubString","SubstitutionString","Symbol","SystemError","Task","TaskFailedException","Text","TextDisplay","Timer","Tuple","Type","TypeError","TypeVar","UInt","UInt128","UInt16","UInt32","UInt64","UInt8","UndefInitializer","UndefKeywordError","UndefRefError","UndefVarError","Union","UnionAll","UnitRange","Unsigned","Val","Vararg","VecElement","VecOrMat","Vector","VersionNumber","WeakKeyDict","WeakRef"]},n={keywords:r,illegal:/<\//},a={className:"subst",begin:/\$\(/,end:/\)/,keywords:r},i={className:"variable",begin:"\\$"+t},o={className:"string",contains:[e.BACKSLASH_ESCAPE,a,i],variants:[{begin:/\w*"""/,end:/"""\w*/,relevance:10},{begin:/\w*"/,end:/"\w*/}]},s={className:"string",contains:[e.BACKSLASH_ESCAPE,a,i],begin:"`",end:"`"},l={className:"meta",begin:"@"+t};return n.name="Julia",n.contains=[{className:"number",begin:/(\b0x[\d_]*(\.[\d_]*)?|0x\.\d[\d_]*)p[-+]?\d+|\b0[box][a-fA-F0-9][a-fA-F0-9_]*|(\b\d[\d_]*(\.[\d_]*)?|\.\d[\d_]*)([eEfF][-+]?\d+)?/,relevance:0},{className:"string",begin:/'(.|\\[xXuU][a-zA-Z0-9]+)'/},o,s,l,{className:"comment",variants:[{begin:"#=",end:"=#",relevance:10},{begin:"#",end:"$"}]},e.HASH_COMMENT_MODE,{className:"keyword",begin:"\\b(((abstract|primitive)\\s+)type|(mutable\\s+)?struct)\\b"},{begin:/<:/}],a.contains=n.contains,n}),X_)),zf.registerLanguage("julia-repl",em?J_:(em=1,J_=function(e){return{name:"Julia REPL",contains:[{className:"meta.prompt",begin:/^julia>/,relevance:10,starts:{end:/^(?![ ]{6})/,subLanguage:"julia"}}],aliases:["jldoctest"]}})),zf.registerLanguage("kotlin",function(){if(rm)return tm;rm=1;var e="[0-9](_*[0-9])*",t=`\\.(${e})`,r="[0-9a-fA-F](_*[0-9a-fA-F])*",n={className:"number",variants:[{begin:`(\\b(${e})((${t})|\\.)?|(${t}))[eE][+-]?(${e})[fFdD]?\\b`},{begin:`\\b(${e})((${t})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${t})[fFdD]?\\b`},{begin:`\\b(${e})[fFdD]\\b`},{begin:`\\b0[xX]((${r})\\.?|(${r})?\\.(${r}))[pP][+-]?(${e})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${r})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};return tm=function(e){const t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},r={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@"},a={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},i={className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},o={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[i,a]},{begin:"'",end:"'",illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[e.BACKSLASH_ESCAPE,i,a]}]};a.contains.push(o);const s={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?"},l={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[e.inherit(o,{className:"string"}),"self"]}]},c=n,d=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),u={variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},p=u;return p.variants[1].contains=[u],u.variants[1].contains=[p],{name:"Kotlin",aliases:["kt","kts"],keywords:t,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,d,{className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},r,s,l,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:t,relevance:5,contains:[{begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin:/</,end:/>/,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[u,e.C_LINE_COMMENT_MODE,d],relevance:0},e.C_LINE_COMMENT_MODE,d,s,l,o,e.C_NUMBER_MODE]},d]},{begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},e.UNDERSCORE_TITLE_MODE,{className:"type",begin:/</,end:/>/,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},s,l]},o,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:"\n"},c]}},tm}()),zf.registerLanguage("lasso",(am||(am=1,nm=function(e){const t="[a-zA-Z_][\\w.]*",r="<\\?(lasso(script)?|=)",n="\\]|\\?>",a={$pattern:t+"|&[lg]t;",literal:"true false none minimal full all void and or not bw nbw ew new cn ncn lt lte gt gte eq neq rx nrx ft",built_in:"array date decimal duration integer map pair string tag xml null boolean bytes keyword list locale queue set stack staticarray local var variable global data self inherited currentcapture givenblock",keyword:"cache database_names database_schemanames database_tablenames define_tag define_type email_batch encode_set html_comment handle handle_error header if inline iterate ljax_target link link_currentaction link_currentgroup link_currentrecord link_detail link_firstgroup link_firstrecord link_lastgroup link_lastrecord link_nextgroup link_nextrecord link_prevgroup link_prevrecord log loop namespace_using output_none portal private protect records referer referrer repeating resultset rows search_args search_arguments select sort_args sort_arguments thread_atomic value_list while abort case else fail_if fail_ifnot fail if_empty if_false if_null if_true loop_abort loop_continue loop_count params params_up return return_value run_children soap_definetag soap_lastrequest soap_lastresponse tag_name ascending average by define descending do equals frozen group handle_failure import in into join let match max min on order parent protected provide public require returnhome skip split_thread sum take thread to trait type where with yield yieldhome"},i=e.COMMENT("\x3c!--","--\x3e",{relevance:0}),o={className:"meta",begin:"\\[noprocess\\]",starts:{end:"\\[/noprocess\\]",returnEnd:!0,contains:[i]}},s={className:"meta",begin:"\\[/noprocess|"+r},l={className:"symbol",begin:"'"+t+"'"},c=[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.inherit(e.C_NUMBER_MODE,{begin:e.C_NUMBER_RE+"|(-?infinity|NaN)\\b"}),e.inherit(e.APOS_STRING_MODE,{illegal:null}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),{className:"string",begin:"`",end:"`"},{variants:[{begin:"[#$]"+t},{begin:"#",end:"\\d+",illegal:"\\W"}]},{className:"type",begin:"::\\s*",end:t,illegal:"\\W"},{className:"params",variants:[{begin:"-(?!infinity)"+t,relevance:0},{begin:"(\\.\\.\\.)"}]},{begin:/(->|\.)\s*/,relevance:0,contains:[l]},{className:"class",beginKeywords:"define",returnEnd:!0,end:"\\(|=>",contains:[e.inherit(e.TITLE_MODE,{begin:t+"(=(?!>))?|[-+*/%](?!>)"})]}];return{name:"Lasso",aliases:["ls","lassoscript"],case_insensitive:!0,keywords:a,contains:[{className:"meta",begin:n,relevance:0,starts:{end:"\\[|"+r,returnEnd:!0,relevance:0,contains:[i]}},o,s,{className:"meta",begin:"\\[no_square_brackets",starts:{end:"\\[/no_square_brackets\\]",keywords:a,contains:[{className:"meta",begin:n,relevance:0,starts:{end:"\\[noprocess\\]|"+r,returnEnd:!0,contains:[i]}},o,s].concat(c)}},{className:"meta",begin:"\\[",relevance:0},{className:"meta",begin:"^#!",end:"lasso9$",relevance:10}].concat(c)}}),nm)),zf.registerLanguage("latex",(om||(om=1,im=function(e){const t=[{begin:/\^{6}[0-9a-f]{6}/},{begin:/\^{5}[0-9a-f]{5}/},{begin:/\^{4}[0-9a-f]{4}/},{begin:/\^{3}[0-9a-f]{3}/},{begin:/\^{2}[0-9a-f]{2}/},{begin:/\^{2}[\u0000-\u007f]/}],r=[{className:"keyword",begin:/\\/,relevance:0,contains:[{endsParent:!0,begin:e.regex.either(...["(?:NeedsTeXFormat|RequirePackage|GetIdInfo)","Provides(?:Expl)?(?:Package|Class|File)","(?:DeclareOption|ProcessOptions)","(?:documentclass|usepackage|input|include)","makeat(?:letter|other)","ExplSyntax(?:On|Off)","(?:new|renew|provide)?command","(?:re)newenvironment","(?:New|Renew|Provide|Declare)(?:Expandable)?DocumentCommand","(?:New|Renew|Provide|Declare)DocumentEnvironment","(?:(?:e|g|x)?def|let)","(?:begin|end)","(?:part|chapter|(?:sub){0,2}section|(?:sub)?paragraph)","caption","(?:label|(?:eq|page|name)?ref|(?:paren|foot|super)?cite)","(?:alpha|beta|[Gg]amma|[Dd]elta|(?:var)?epsilon|zeta|eta|[Tt]heta|vartheta)","(?:iota|(?:var)?kappa|[Ll]ambda|mu|nu|[Xx]i|[Pp]i|varpi|(?:var)rho)","(?:[Ss]igma|varsigma|tau|[Uu]psilon|[Pp]hi|varphi|chi|[Pp]si|[Oo]mega)","(?:frac|sum|prod|lim|infty|times|sqrt|leq|geq|left|right|middle|[bB]igg?)","(?:[lr]angle|q?quad|[lcvdi]?dots|d?dot|hat|tilde|bar)"].map(e=>e+"(?![a-zA-Z@:_])"))},{endsParent:!0,begin:new RegExp(["(?:__)?[a-zA-Z]{2,}_[a-zA-Z](?:_?[a-zA-Z])+:[a-zA-Z]*","[lgc]__?[a-zA-Z](?:_?[a-zA-Z])*_[a-zA-Z]{2,}","[qs]__?[a-zA-Z](?:_?[a-zA-Z])+","use(?:_i)?:[a-zA-Z]*","(?:else|fi|or):","(?:if|cs|exp):w","(?:hbox|vbox):n","::[a-zA-Z]_unbraced","::[a-zA-Z:]"].map(e=>e+"(?![a-zA-Z:_])").join("|"))},{endsParent:!0,variants:t},{endsParent:!0,relevance:0,variants:[{begin:/[a-zA-Z@]+/},{begin:/[^a-zA-Z@]?/}]}]},{className:"params",relevance:0,begin:/#+\d?/},{variants:t},{className:"built_in",relevance:0,begin:/[$&^_]/},{className:"meta",begin:/% ?!(T[eE]X|tex|BIB|bib)/,end:"$",relevance:10},e.COMMENT("%","$",{relevance:0})],n={begin:/\{/,end:/\}/,relevance:0,contains:["self",...r]},a=e.inherit(n,{relevance:0,endsParent:!0,contains:[n,...r]}),i={begin:/\[/,end:/\]/,endsParent:!0,relevance:0,contains:[n,...r]},o={begin:/\s+/,relevance:0},s=[a],l=[i],c=function(e,t){return{contains:[o],starts:{relevance:0,contains:e,starts:t}}},d=function(e,t){return{begin:"\\\\"+e+"(?![a-zA-Z@:_])",keywords:{$pattern:/\\[a-zA-Z]+/,keyword:"\\"+e},relevance:0,contains:[o],starts:t}},u=function(t,r){return e.inherit({begin:"\\\\begin(?=[ \t]*(\\r?\\n[ \t]*)?\\{"+t+"\\})",keywords:{$pattern:/\\[a-zA-Z]+/,keyword:"\\begin"},relevance:0},c(s,r))},p=(t="string")=>e.END_SAME_AS_BEGIN({className:t,begin:/(.|\r?\n)/,end:/(.|\r?\n)/,excludeBegin:!0,excludeEnd:!0,endsParent:!0}),_=function(e){return{className:"string",end:"(?=\\\\end\\{"+e+"\\})"}},m=(e="string")=>({relevance:0,begin:/\{/,starts:{endsParent:!0,contains:[{className:e,end:/(?=\})/,endsParent:!0,contains:[{begin:/\{/,end:/\}/,relevance:0,contains:["self"]}]}]}});return{name:"LaTeX",aliases:["tex"],contains:[...["verb","lstinline"].map(e=>d(e,{contains:[p()]})),d("mint",c(s,{contains:[p()]})),d("mintinline",c(s,{contains:[m(),p()]})),d("url",{contains:[m("link"),m("link")]}),d("hyperref",{contains:[m("link")]}),d("href",c(l,{contains:[m("link")]})),...[].concat(...["","\\*"].map(e=>[u("verbatim"+e,_("verbatim"+e)),u("filecontents"+e,c(s,_("filecontents"+e))),...["","B","L"].map(t=>u(t+"Verbatim"+e,c(l,_(t+"Verbatim"+e))))])),u("minted",c(l,c(s,_("minted")))),...r]}}),im)),zf.registerLanguage("ldif",(lm||(lm=1,sm=function(e){return{name:"LDIF",contains:[{className:"attribute",match:"^dn(?=:)",relevance:10},{className:"attribute",match:"^\\w+(?=:)"},{className:"literal",match:"^-"},e.HASH_COMMENT_MODE]}}),sm)),zf.registerLanguage("leaf",dm?cm:(dm=1,cm=function(e){const t=/([A-Za-z_][A-Za-z_0-9]*)?/,r={scope:"params",begin:/\(/,end:/\)(?=\:?)/,endsParent:!0,relevance:7,contains:[{scope:"string",begin:'"',end:'"'},{scope:"keyword",match:["true","false","in"].join("|")},{scope:"variable",match:/[A-Za-z_][A-Za-z_0-9]*/},{scope:"operator",match:/\+|\-|\*|\/|\%|\=\=|\=|\!|\>|\<|\&\&|\|\|/}]},n={match:[t,/(?=\()/],scope:{1:"keyword"},contains:[r]};return r.contains.unshift(n),{name:"Leaf",contains:[{match:[/#+/,t,/(?=\()/],scope:{1:"punctuation",2:"keyword"},starts:{contains:[{match:/\:/,scope:"punctuation"}]},contains:[r]},{match:[/#+/,t,/:?/],scope:{1:"punctuation",2:"keyword",3:"punctuation"}}]}})),zf.registerLanguage("less",function(){if(pm)return um;pm=1;const e=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],t=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),r=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),n=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),a=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),i=r.concat(n).sort().reverse();return um=function(o){const s=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(o),l=i,c="[\\w-]+",d="("+c+"|@\\{"+c+"\\})",u=[],p=[],_=function(e){return{className:"string",begin:"~?"+e+".*?"+e}},m=function(e,t,r){return{className:e,begin:t,relevance:r}},g={$pattern:/[a-z-]+/,keyword:"and or not only",attribute:t.join(" ")},h={begin:"\\(",end:"\\)",contains:p,keywords:g,relevance:0};p.push(o.C_LINE_COMMENT_MODE,o.C_BLOCK_COMMENT_MODE,_("'"),_('"'),s.CSS_NUMBER_MODE,{begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]",excludeEnd:!0}},s.HEXCOLOR,h,m("variable","@@?"+c,10),m("variable","@\\{"+c+"\\}"),m("built_in","~?`[^`]*?`"),{className:"attribute",begin:c+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0},s.IMPORTANT,{beginKeywords:"and not"},s.FUNCTION_DISPATCH);const f=p.concat({begin:/\{/,end:/\}/,contains:u}),E={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(p)},b={begin:d+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},s.CSS_VARIABLE,{className:"attribute",begin:"\\b("+a.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:p}}]},S={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:g,returnEnd:!0,contains:p,relevance:0}},v={className:"variable",variants:[{begin:"@"+c+"\\s*:",relevance:15},{begin:"@"+c}],starts:{end:"[;}]",returnEnd:!0,contains:f}},T={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:d,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:"[<='$\"]",relevance:0,contains:[o.C_LINE_COMMENT_MODE,o.C_BLOCK_COMMENT_MODE,E,m("keyword","all\\b"),m("variable","@\\{"+c+"\\}"),{begin:"\\b("+e.join("|")+")\\b",className:"selector-tag"},s.CSS_NUMBER_MODE,m("selector-tag",d,0),m("selector-id","#"+d),m("selector-class","\\."+d,0),m("selector-tag","&",0),s.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+n.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:f},{begin:"!important"},s.FUNCTION_DISPATCH]},y={begin:c+":(:)?"+`(${l.join("|")})`,returnBegin:!0,contains:[T]};return u.push(o.C_LINE_COMMENT_MODE,o.C_BLOCK_COMMENT_MODE,S,v,y,b,T,E,s.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:"[=>'/<($\"]",contains:u}},um}()),zf.registerLanguage("lisp",(mm||(mm=1,_m=function(e){const t="[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*",r="\\|[^]*?\\|",n="(-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|-)?\\d+)?",a={className:"literal",begin:"\\b(t{1}|nil)\\b"},i={className:"number",variants:[{begin:n,relevance:0},{begin:"#(b|B)[0-1]+(/[0-1]+)?"},{begin:"#(o|O)[0-7]+(/[0-7]+)?"},{begin:"#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?"},{begin:"#(c|C)\\("+n+" +"+n,end:"\\)"}]},o=e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),s=e.COMMENT(";","$",{relevance:0}),l={begin:"\\*",end:"\\*"},c={className:"symbol",begin:"[:&]"+t},d={begin:t,relevance:0},u={begin:r},p={contains:[i,o,l,c,{begin:"\\(",end:"\\)",contains:["self",a,o,i,d]},d],variants:[{begin:"['`]\\(",end:"\\)"},{begin:"\\(quote ",end:"\\)",keywords:{name:"quote"}},{begin:"'"+r}]},_={variants:[{begin:"'"+t},{begin:"#'"+t+"(::"+t+")*"}]},m={begin:"\\(\\s*",end:"\\)"},g={endsWithParent:!0,relevance:0};return m.contains=[{className:"name",variants:[{begin:t,relevance:0},{begin:r}]},g],g.contains=[p,_,m,a,i,o,s,l,c,u,d],{name:"Lisp",illegal:/\S/,contains:[i,e.SHEBANG(),a,o,s,p,_,m,d]}}),_m)),zf.registerLanguage("livecodeserver",(hm||(hm=1,gm=function(e){const t={className:"variable",variants:[{begin:"\\b([gtps][A-Z]{1}[a-zA-Z0-9]*)(\\[.+\\])?(?:\\s*?)"},{begin:"\\$_[A-Z]+"}],relevance:0},r=[e.C_BLOCK_COMMENT_MODE,e.HASH_COMMENT_MODE,e.COMMENT("--","$"),e.COMMENT("[^:]//","$")],n=e.inherit(e.TITLE_MODE,{variants:[{begin:"\\b_*rig[A-Z][A-Za-z0-9_\\-]*"},{begin:"\\b_[a-z0-9\\-]+"}]}),a=e.inherit(e.TITLE_MODE,{begin:"\\b([A-Za-z0-9_\\-]+)\\b"});return{name:"LiveCode",case_insensitive:!1,keywords:{keyword:"$_COOKIE $_FILES $_GET $_GET_BINARY $_GET_RAW $_POST $_POST_BINARY $_POST_RAW $_SESSION $_SERVER codepoint codepoints segment segments codeunit codeunits sentence sentences trueWord trueWords paragraph after byte bytes english the until http forever descending using line real8 with seventh for stdout finally element word words fourth before black ninth sixth characters chars stderr uInt1 uInt1s uInt2 uInt2s stdin string lines relative rel any fifth items from middle mid at else of catch then third it file milliseconds seconds second secs sec int1 int1s int4 int4s internet int2 int2s normal text item last long detailed effective uInt4 uInt4s repeat end repeat URL in try into switch to words https token binfile each tenth as ticks tick system real4 by dateItems without char character ascending eighth whole dateTime numeric short first ftp integer abbreviated abbr abbrev private case while if div mod wrap and or bitAnd bitNot bitOr bitXor among not in a an within contains ends with begins the keys of keys",literal:"SIX TEN FORMFEED NINE ZERO NONE SPACE FOUR FALSE COLON CRLF PI COMMA ENDOFFILE EOF EIGHT FIVE QUOTE EMPTY ONE TRUE RETURN CR LINEFEED RIGHT BACKSLASH NULL SEVEN TAB THREE TWO six ten formfeed nine zero none space four false colon crlf pi comma endoffile eof eight five quote empty one true return cr linefeed right backslash null seven tab three two RIVERSION RISTATE FILE_READ_MODE FILE_WRITE_MODE FILE_WRITE_MODE DIR_WRITE_MODE FILE_READ_UMASK FILE_WRITE_UMASK DIR_READ_UMASK DIR_WRITE_UMASK",built_in:"put abs acos aliasReference annuity arrayDecode arrayEncode asin atan atan2 average avg avgDev base64Decode base64Encode baseConvert binaryDecode binaryEncode byteOffset byteToNum cachedURL cachedURLs charToNum cipherNames codepointOffset codepointProperty codepointToNum codeunitOffset commandNames compound compress constantNames cos date dateFormat decompress difference directories diskSpace DNSServers exp exp1 exp2 exp10 extents files flushEvents folders format functionNames geometricMean global globals hasMemory harmonicMean hostAddress hostAddressToName hostName hostNameToAddress isNumber ISOToMac itemOffset keys len length libURLErrorData libUrlFormData libURLftpCommand libURLLastHTTPHeaders libURLLastRHHeaders libUrlMultipartFormAddPart libUrlMultipartFormData libURLVersion lineOffset ln ln1 localNames log log2 log10 longFilePath lower macToISO matchChunk matchText matrixMultiply max md5Digest median merge messageAuthenticationCode messageDigest millisec millisecs millisecond milliseconds min monthNames nativeCharToNum normalizeText num number numToByte numToChar numToCodepoint numToNativeChar offset open openfiles openProcesses openProcessIDs openSockets paragraphOffset paramCount param params peerAddress pendingMessages platform popStdDev populationStandardDeviation populationVariance popVariance processID random randomBytes replaceText result revCreateXMLTree revCreateXMLTreeFromFile revCurrentRecord revCurrentRecordIsFirst revCurrentRecordIsLast revDatabaseColumnCount revDatabaseColumnIsNull revDatabaseColumnLengths revDatabaseColumnNames revDatabaseColumnNamed revDatabaseColumnNumbered revDatabaseColumnTypes revDatabaseConnectResult revDatabaseCursors revDatabaseID revDatabaseTableNames revDatabaseType revDataFromQuery revdb_closeCursor revdb_columnbynumber revdb_columncount revdb_columnisnull revdb_columnlengths revdb_columnnames revdb_columntypes revdb_commit revdb_connect revdb_connections revdb_connectionerr revdb_currentrecord revdb_cursorconnection revdb_cursorerr revdb_cursors revdb_dbtype revdb_disconnect revdb_execute revdb_iseof revdb_isbof revdb_movefirst revdb_movelast revdb_movenext revdb_moveprev revdb_query revdb_querylist revdb_recordcount revdb_rollback revdb_tablenames revGetDatabaseDriverPath revNumberOfRecords revOpenDatabase revOpenDatabases revQueryDatabase revQueryDatabaseBlob revQueryResult revQueryIsAtStart revQueryIsAtEnd revUnixFromMacPath revXMLAttribute revXMLAttributes revXMLAttributeValues revXMLChildContents revXMLChildNames revXMLCreateTreeFromFileWithNamespaces revXMLCreateTreeWithNamespaces revXMLDataFromXPathQuery revXMLEvaluateXPath revXMLFirstChild revXMLMatchingNode revXMLNextSibling revXMLNodeContents revXMLNumberOfChildren revXMLParent revXMLPreviousSibling revXMLRootNode revXMLRPC_CreateRequest revXMLRPC_Documents revXMLRPC_Error revXMLRPC_GetHost revXMLRPC_GetMethod revXMLRPC_GetParam revXMLText revXMLRPC_Execute revXMLRPC_GetParamCount revXMLRPC_GetParamNode revXMLRPC_GetParamType revXMLRPC_GetPath revXMLRPC_GetPort revXMLRPC_GetProtocol revXMLRPC_GetRequest revXMLRPC_GetResponse revXMLRPC_GetSocket revXMLTree revXMLTrees revXMLValidateDTD revZipDescribeItem revZipEnumerateItems revZipOpenArchives round sampVariance sec secs seconds sentenceOffset sha1Digest shell shortFilePath sin specialFolderPath sqrt standardDeviation statRound stdDev sum sysError systemVersion tan tempName textDecode textEncode tick ticks time to tokenOffset toLower toUpper transpose truewordOffset trunc uniDecode uniEncode upper URLDecode URLEncode URLStatus uuid value variableNames variance version waitDepth weekdayNames wordOffset xsltApplyStylesheet xsltApplyStylesheetFromFile xsltLoadStylesheet xsltLoadStylesheetFromFile add breakpoint cancel clear local variable file word line folder directory URL close socket process combine constant convert create new alias folder directory decrypt delete variable word line folder directory URL dispatch divide do encrypt filter get include intersect kill libURLDownloadToFile libURLFollowHttpRedirects libURLftpUpload libURLftpUploadFile libURLresetAll libUrlSetAuthCallback libURLSetDriver libURLSetCustomHTTPHeaders libUrlSetExpect100 libURLSetFTPListCommand libURLSetFTPMode libURLSetFTPStopTime libURLSetStatusCallback load extension loadedExtensions multiply socket prepare process post seek rel relative read from process rename replace require resetAll resolve revAddXMLNode revAppendXML revCloseCursor revCloseDatabase revCommitDatabase revCopyFile revCopyFolder revCopyXMLNode revDeleteFolder revDeleteXMLNode revDeleteAllXMLTrees revDeleteXMLTree revExecuteSQL revGoURL revInsertXMLNode revMoveFolder revMoveToFirstRecord revMoveToLastRecord revMoveToNextRecord revMoveToPreviousRecord revMoveToRecord revMoveXMLNode revPutIntoXMLNode revRollBackDatabase revSetDatabaseDriverPath revSetXMLAttribute revXMLRPC_AddParam revXMLRPC_DeleteAllDocuments revXMLAddDTD revXMLRPC_Free revXMLRPC_FreeAll revXMLRPC_DeleteDocument revXMLRPC_DeleteParam revXMLRPC_SetHost revXMLRPC_SetMethod revXMLRPC_SetPort revXMLRPC_SetProtocol revXMLRPC_SetSocket revZipAddItemWithData revZipAddItemWithFile revZipAddUncompressedItemWithData revZipAddUncompressedItemWithFile revZipCancel revZipCloseArchive revZipDeleteItem revZipExtractItemToFile revZipExtractItemToVariable revZipSetProgressCallback revZipRenameItem revZipReplaceItemWithData revZipReplaceItemWithFile revZipOpenArchive send set sort split start stop subtract symmetric union unload vectorDotProduct wait write"},contains:[t,{className:"keyword",begin:"\\bend\\sif\\b"},{className:"function",beginKeywords:"function",end:"$",contains:[t,a,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.BINARY_NUMBER_MODE,e.C_NUMBER_MODE,n]},{className:"function",begin:"\\bend\\s+",end:"$",keywords:"end",contains:[a,n],relevance:0},{beginKeywords:"command on",end:"$",contains:[t,a,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.BINARY_NUMBER_MODE,e.C_NUMBER_MODE,n]},{className:"meta",variants:[{begin:"<\\?(rev|lc|livecode)",relevance:10},{begin:"<\\?"},{begin:"\\?>"}]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.BINARY_NUMBER_MODE,e.C_NUMBER_MODE,n].concat(r),illegal:";$|^\\[|^=|&|\\{"}}),gm)),zf.registerLanguage("livescript",function(){if(Em)return fm;Em=1;const e=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],t=["true","false","null","undefined","NaN","Infinity"],r=[].concat(["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]);return fm=function(n){const a={keyword:e.concat(["then","unless","until","loop","of","by","when","and","or","is","isnt","not","it","that","otherwise","from","to","til","fallthrough","case","enum","native","list","map","__hasProp","__extends","__slice","__bind","__indexOf"]),literal:t.concat(["yes","no","on","off","it","that","void"]),built_in:r.concat(["npm","print"])},i="[A-Za-z$_](?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*",o=n.inherit(n.TITLE_MODE,{begin:i}),s={className:"subst",begin:/#\{/,end:/\}/,keywords:a},l={className:"subst",begin:/#[A-Za-z$_]/,end:/(?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*/,keywords:a},c=[n.BINARY_NUMBER_MODE,{className:"number",begin:"(\\b0[xX][a-fA-F0-9_]+)|(\\b\\d(\\d|_\\d)*(\\.(\\d(\\d|_\\d)*)?)?(_*[eE]([-+]\\d(_\\d|\\d)*)?)?[_a-z]*)",relevance:0,starts:{end:"(\\s*/)?",relevance:0}},{className:"string",variants:[{begin:/'''/,end:/'''/,contains:[n.BACKSLASH_ESCAPE]},{begin:/'/,end:/'/,contains:[n.BACKSLASH_ESCAPE]},{begin:/"""/,end:/"""/,contains:[n.BACKSLASH_ESCAPE,s,l]},{begin:/"/,end:/"/,contains:[n.BACKSLASH_ESCAPE,s,l]},{begin:/\\/,end:/(\s|$)/,excludeEnd:!0}]},{className:"regexp",variants:[{begin:"//",end:"//[gim]*",contains:[s,n.HASH_COMMENT_MODE]},{begin:/\/(?![ *])(\\.|[^\\\n])*?\/[gim]*(?=\W)/}]},{begin:"@"+i},{begin:"``",end:"``",excludeBegin:!0,excludeEnd:!0,subLanguage:"javascript"}];s.contains=c;const d={className:"params",begin:"\\(",returnBegin:!0,contains:[{begin:/\(/,end:/\)/,keywords:a,contains:["self"].concat(c)}]},u={variants:[{match:[/class\s+/,i,/\s+extends\s+/,i]},{match:[/class\s+/,i]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:a};return{name:"LiveScript",aliases:["ls"],keywords:a,illegal:/\/\*/,contains:c.concat([n.COMMENT("\\/\\*","\\*\\/"),n.HASH_COMMENT_MODE,{begin:"(#=>|=>|\\|>>|-?->|!->)"},{className:"function",contains:[o,d],returnBegin:!0,variants:[{begin:"("+i+"\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B->\\*?",end:"->\\*?"},{begin:"("+i+"\\s*(?:=|:=)\\s*)?!?(\\(.*\\)\\s*)?\\B[-~]{1,2}>\\*?",end:"[-~]{1,2}>\\*?"},{begin:"("+i+"\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B!?[-~]{1,2}>\\*?",end:"!?[-~]{1,2}>\\*?"}]},u,{begin:i+":",end:":",returnBegin:!0,returnEnd:!0,relevance:0}])}},fm}()),zf.registerLanguage("llvm",(Sm||(Sm=1,bm=function(e){const t=e.regex,r=/([-a-zA-Z$._][\w$.-]*)/,n={className:"variable",variants:[{begin:t.concat(/%/,r)},{begin:/%\d+/},{begin:/#\d+/}]},a={className:"title",variants:[{begin:t.concat(/@/,r)},{begin:/@\d+/},{begin:t.concat(/!/,r)},{begin:t.concat(/!\d+/,r)},{begin:/!\d+/}]};return{name:"LLVM IR",keywords:{keyword:"begin end true false declare define global constant private linker_private internal available_externally linkonce linkonce_odr weak weak_odr appending dllimport dllexport common default hidden protected extern_weak external thread_local zeroinitializer undef null to tail target triple datalayout volatile nuw nsw nnan ninf nsz arcp fast exact inbounds align addrspace section alias module asm sideeffect gc dbg linker_private_weak attributes blockaddress initialexec localdynamic localexec prefix unnamed_addr ccc fastcc coldcc x86_stdcallcc x86_fastcallcc arm_apcscc arm_aapcscc arm_aapcs_vfpcc ptx_device ptx_kernel intel_ocl_bicc msp430_intrcc spir_func spir_kernel x86_64_sysvcc x86_64_win64cc x86_thiscallcc cc c signext zeroext inreg sret nounwind noreturn noalias nocapture byval nest readnone readonly inlinehint noinline alwaysinline optsize ssp sspreq noredzone noimplicitfloat naked builtin cold nobuiltin noduplicate nonlazybind optnone returns_twice sanitize_address sanitize_memory sanitize_thread sspstrong uwtable returned type opaque eq ne slt sgt sle sge ult ugt ule uge oeq one olt ogt ole oge ord uno ueq une x acq_rel acquire alignstack atomic catch cleanup filter inteldialect max min monotonic nand personality release seq_cst singlethread umax umin unordered xchg add fadd sub fsub mul fmul udiv sdiv fdiv urem srem frem shl lshr ashr and or xor icmp fcmp phi call trunc zext sext fptrunc fpext uitofp sitofp fptoui fptosi inttoptr ptrtoint bitcast addrspacecast select va_arg ret br switch invoke unwind unreachable indirectbr landingpad resume malloc alloca free load store getelementptr extractelement insertelement shufflevector getresult extractvalue insertvalue atomicrmw cmpxchg fence argmemonly",type:"void half bfloat float double fp128 x86_fp80 ppc_fp128 x86_amx x86_mmx ptr label token metadata opaque"},contains:[{className:"type",begin:/\bi\d+(?=\s|\b)/},e.COMMENT(/;\s*$/,null,{relevance:0}),e.COMMENT(/;/,/$/),{className:"string",begin:/"/,end:/"/,contains:[{className:"char.escape",match:/\\\d\d/}]},a,{className:"punctuation",relevance:0,begin:/,/},{className:"operator",relevance:0,begin:/=/},n,{className:"symbol",variants:[{begin:/^\s*[a-z]+:/}],relevance:0},{className:"number",variants:[{begin:/[su]?0[xX][KMLHR]?[a-fA-F0-9]+/},{begin:/[-+]?\d+(?:[.]\d+)?(?:[eE][-+]?\d+(?:[.]\d+)?)?/}],relevance:0}]}}),bm)),zf.registerLanguage("lsl",(Tm||(Tm=1,vm=function(e){const t={className:"string",begin:'"',end:'"',contains:[{className:"subst",begin:/\\[tn"\\]/}]},r={className:"number",relevance:0,begin:e.C_NUMBER_RE};return{name:"LSL (Linden Scripting Language)",illegal:":",contains:[t,{className:"comment",variants:[e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/")],relevance:0},r,{className:"section",variants:[{begin:"\\b(state|default)\\b"},{begin:"\\b(state_(entry|exit)|touch(_(start|end))?|(land_)?collision(_(start|end))?|timer|listen|(no_)?sensor|control|(not_)?at_(rot_)?target|money|email|experience_permissions(_denied)?|run_time_permissions|changed|attach|dataserver|moving_(start|end)|link_message|(on|object)_rez|remote_data|http_re(sponse|quest)|path_update|transaction_result)\\b"}]},{className:"built_in",begin:"\\b(ll(AgentInExperience|(Create|DataSize|Delete|KeyCount|Keys|Read|Update)KeyValue|GetExperience(Details|ErrorMessage)|ReturnObjectsBy(ID|Owner)|Json(2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(Mag|Norm|Dist)|Rot(Between|2(Euler|Fwd|Left|Up))|(Euler|Axes)2Rot|Whisper|(Region|Owner)?Say|Shout|Listen(Control|Remove)?|Sensor(Repeat|Remove)?|Detected(Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|([GS]et)(AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(Scale|Offset|Rotate)Texture|(Rot)?Target(Remove)?|(Stop)?MoveToTarget|Apply(Rotational)?Impulse|Set(KeyframedMotion|ContentType|RegionPos|(Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(Queueing|Radius)|Vehicle(Type|(Float|Vector|Rotation)Param)|(Touch|Sit)?Text|Camera(Eye|At)Offset|PrimitiveParams|ClickAction|Link(Alpha|Color|PrimitiveParams(Fast)?|Texture(Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get((Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(PrimitiveParams|Number(OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(Details|PermMask|PrimCount)|Parcel(MaxPrims|Details|Prim(Count|Owners))|Attached(List)?|(SPMax|Free|Used)Memory|Region(Name|TimeDilation|FPS|Corner|AgentCount)|Root(Position|Rotation)|UnixTime|(Parcel|Region)Flags|(Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(Prims|NotecardLines|Sides)|Animation(List)?|(Camera|Local)(Pos|Rot)|Vel|Accel|Omega|Time(stamp|OfDay)|(Object|CenterOf)?Mass|MassMKS|Energy|Owner|(Owner)?Key|SunDirection|Texture(Offset|Scale|Rot)|Inventory(Number|Name|Key|Type|Creator|PermMask)|Permissions(Key)?|StartParameter|List(Length|EntryType)|Date|Agent(Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(Name|State))|(Get|Reset|GetAndReset)Time|PlaySound(Slave)?|LoopSound(Master|Slave)?|(Trigger|Stop|Preload)Sound|((Get|Delete)Sub|Insert)String|To(Upper|Lower)|Give(InventoryList|Money)|RezObject|(Stop)?LookAt|Sleep|CollisionFilter|(Take|Release)Controls|DetachFromAvatar|AttachToAvatar(Temp)?|InstantMessage|(GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(Length|Trim)|(Start|Stop)Animation|TargetOmega|Request(Experience)?Permissions|(Create|Break)Link|BreakAllLinks|(Give|Remove)Inventory|Water|PassTouches|Request(Agent|Inventory)Data|TeleportAgent(Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(Axis|Angle)|A(cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(CSV|Integer|Json|Float|String|Key|Vector|Rot|List(Strided)?)|DeleteSubList|List(Statistics|Sort|Randomize|(Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(Slope|Normal|Contour)|GroundRepel|(Set|Remove)VehicleFlags|SitOnLink|(AvatarOn)?(Link)?SitTarget|Script(Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(Integer|String)ToBase64|XorBase64|Log(10)?|Base64To(String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(Load|Release|(E|Une)scape)URL|ParcelMedia(CommandList|Query)|ModPow|MapDestination|(RemoveFrom|AddTo|Reset)Land(Pass|Ban)List|(Set|Clear)CameraParams|HTTP(Request|Response)|TextBox|DetectedTouch(UV|Face|Pos|(N|Bin)ormal|ST)|(MD5|SHA1|DumpList2)String|Request(Secure)?URL|Clear(Prim|Link)Media|(Link)?ParticleSystem|(Get|Request)(Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\\b"},{className:"literal",variants:[{begin:"\\b(PI|TWO_PI|PI_BY_TWO|DEG_TO_RAD|RAD_TO_DEG|SQRT2)\\b"},{begin:"\\b(XP_ERROR_(EXPERIENCES_DISABLED|EXPERIENCE_(DISABLED|SUSPENDED)|INVALID_(EXPERIENCE|PARAMETERS)|KEY_NOT_FOUND|MATURITY_EXCEEDED|NONE|NOT_(FOUND|PERMITTED(_LAND)?)|NO_EXPERIENCE|QUOTA_EXCEEDED|RETRY_UPDATE|STORAGE_EXCEPTION|STORE_DISABLED|THROTTLED|UNKNOWN_ERROR)|JSON_APPEND|STATUS_(PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(_OBJECT)?|(DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(_(BY_(LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(PARCEL(_OWNER)?|REGION)))?|CAMERA_(PITCH|DISTANCE|BEHINDNESS_(ANGLE|LAG)|(FOCUS|POSITION)(_(THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(ROOT|SET|ALL_(OTHERS|CHILDREN)|THIS)|ACTIVE|PASS(IVE|_(ALWAYS|IF_NOT_HANDLED|NEVER))|SCRIPTED|CONTROL_(FWD|BACK|(ROT_)?(LEFT|RIGHT)|UP|DOWN|(ML_)?LBUTTON)|PERMISSION_(RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(_START)?|TELEPORT|MEDIA)|OBJECT_(CLICK_ACTION|HOVER_HEIGHT|LAST_OWNER_ID|(PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_(ATTACHED|ON_REZ)|NAME|DESC|POS|PRIM_(COUNT|EQUIVALENCE)|RETURN_(PARCEL(_OWNER)?|REGION)|REZZER_KEY|ROO?T|VELOCITY|OMEGA|OWNER|GROUP(_TAG)?|CREATOR|ATTACHED_(POINT|SLOTS_AVAILABLE)|RENDER_WEIGHT|(BODY_SHAPE|PATHFINDING)_TYPE|(RUNNING|TOTAL)_SCRIPT_COUNT|TOTAL_INVENTORY_COUNT|SCRIPT_(MEMORY|TIME))|TYPE_(INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(DEBUG|PUBLIC)_CHANNEL|ATTACH_(AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](SHOULDER|HAND|FOOT|EAR|EYE|[UL](ARM|LEG)|HIP)|(LEFT|RIGHT)_PEC|HUD_(CENTER_[12]|TOP_(RIGHT|CENTER|LEFT)|BOTTOM(_(RIGHT|LEFT))?)|[LR]HAND_RING1|TAIL_(BASE|TIP)|[LR]WING|FACE_(JAW|[LR]EAR|[LR]EYE|TOUNGE)|GROIN|HIND_[LR]FOOT)|LAND_(LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(ONLINE|NAME|BORN|SIM_(POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(ON_FILE|USED)|REMOTE_DATA_(CHANNEL|REQUEST|REPLY)|PSYS_(PART_(BF_(ZERO|ONE(_MINUS_(DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(START|END)_(COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(RIBBON|WIND|INTERP_(COLOR|SCALE)|BOUNCE|FOLLOW_(SRC|VELOCITY)|TARGET_(POS|LINEAR)|EMISSIVE)_MASK)|SRC_(MAX_AGE|PATTERN|ANGLE_(BEGIN|END)|BURST_(RATE|PART_COUNT|RADIUS|SPEED_(MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(DROP|EXPLODE|ANGLE(_CONE(_EMPTY)?)?)))|VEHICLE_(REFERENCE_FRAME|TYPE_(NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(LINEAR|ANGULAR)_(FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(LINEAR|ANGULAR)_(DEFLECTION_(EFFICIENCY|TIMESCALE)|MOTOR_(DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(EFFICIENCY|TIMESCALE)|BANKING_(EFFICIENCY|MIX|TIMESCALE)|FLAG_(NO_DEFLECTION_UP|LIMIT_(ROLL_ONLY|MOTOR_UP)|HOVER_((WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(ALLOW_UNSIT|ALPHA_MODE(_(BLEND|EMISSIVE|MASK|NONE))?|NORMAL|SPECULAR|TYPE(_(BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(_(STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(NONE|LOW|MEDIUM|HIGH)|BUMP_(NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(DEFAULT|PLANAR)|SCRIPTED_SIT_ONLY|SCULPT_(TYPE_(SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(MIRROR|INVERT))|PHYSICS(_(SHAPE_(CONVEX|NONE|PRIM|TYPE)))?|(POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIT_TARGET|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(ALT_IMAGE_ENABLE|CONTROLS|(CURRENT|HOME)_URL|AUTO_(LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(WIDTH|HEIGHT)_PIXELS|WHITELIST(_ENABLE)?|PERMS_(INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(STANDARD|MINI)|PERM_(NONE|OWNER|GROUP|ANYONE)|MAX_(URL_LENGTH|WHITELIST_(SIZE|COUNT)|(WIDTH|HEIGHT)_PIXELS)))|MASK_(BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(MEDIA_COMMAND_(STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(ALLOW_(FLY|(GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(GROUP_)?OBJECTS)|USE_(ACCESS_(GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(GROUP|ALL)_OBJECT_ENTRY)|COUNT_(TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(HIDE|DEFAULT)|REGION_FLAG_(ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(METHOD|MIMETYPE|BODY_(MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|SIT_(INVALID_(AGENT|LINK_OBJECT)|NO(T_EXPERIENCE|_(ACCESS|EXPERIENCE_PERMISSION|SIT_TARGET)))|STRING_(TRIM(_(HEAD|TAIL))?)|CLICK_ACTION_(NONE|TOUCH|SIT|BUY|PAY|OPEN(_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(NONE|SCRIPT_MEMORY)|RC_(DATA_FLAGS|DETECT_PHANTOM|GET_(LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(TYPES|AGENTS|(NON)?PHYSICAL|LAND))|RCERR_(CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(ALLOWED_(AGENT|GROUP)_(ADD|REMOVE)|BANNED_AGENT_(ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(COMMAND|CMD_(PLAY|STOP|PAUSE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(CMD_((SMOOTH_)?STOP|JUMP)|DESIRED_(TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(_([ABCD]|NONE))?|MAX_(DECEL|TURN_RADIUS|(ACCEL|SPEED)))|PURSUIT_(OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(EVADE_(HIDDEN|SPOTTED)|FAILURE_(DYNAMIC_PATHFINDING_DISABLED|INVALID_(GOAL|START)|NO_(NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(PARCEL_)?UNREACHABLE)|(GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(_(FAST|NONE|SLOW))?|CONTENT_TYPE_(ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(RADIUS|STATIC)|(PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\\b"},{begin:"\\b(FALSE|TRUE)\\b"},{begin:"\\b(ZERO_ROTATION)\\b"},{begin:"\\b(EOF|JSON_(ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(GRANTED|DENIED))\\b"},{begin:"\\b(ZERO_VECTOR|TOUCH_INVALID_(TEXCOORD|VECTOR))\\b"}]},{className:"type",begin:"\\b(integer|float|string|key|vector|quaternion|rotation|list)\\b"}]}}),vm)),zf.registerLanguage("lua",(Cm||(Cm=1,ym=function(e){const t="\\[=*\\[",r="\\]=*\\]",n={begin:t,end:r,contains:["self"]},a=[e.COMMENT("--(?!"+t+")","$"),e.COMMENT("--"+t,r,{contains:[n],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:e.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in local not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:a.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:a}].concat(a)},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:t,end:r,contains:[n],relevance:5}])}}),ym)),zf.registerLanguage("makefile",(Rm||(Rm=1,Nm=function(e){const t={className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)",contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%<?\^\+\*]/}]},r={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,t]},n={className:"variable",begin:/\$\([\w-]+\s/,end:/\)/,keywords:{built_in:"subst patsubst strip findstring filter filter-out sort word wordlist firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath error warning shell origin flavor foreach if or and call eval file value"},contains:[t,r]},a={begin:"^"+e.UNDERSCORE_IDENT_RE+"\\s*(?=[:+?]?=)"},i={className:"section",begin:/^[^\s]+:/,end:/$/,contains:[t]};return{name:"Makefile",aliases:["mk","mak","make"],keywords:{$pattern:/[\w-]+/,keyword:"define endef undefine ifdef ifndef ifeq ifneq else endif include -include sinclude override export unexport private vpath"},contains:[e.HASH_COMMENT_MODE,t,r,n,a,{className:"meta",begin:/^\.PHONY:/,end:/$/,keywords:{$pattern:/[\.\w]+/,keyword:".PHONY"}},i]}}),Nm)),zf.registerLanguage("mathematica",function(){if(Om)return Am;Om=1;const e=["AASTriangle","AbelianGroup","Abort","AbortKernels","AbortProtect","AbortScheduledTask","Above","Abs","AbsArg","AbsArgPlot","Absolute","AbsoluteCorrelation","AbsoluteCorrelationFunction","AbsoluteCurrentValue","AbsoluteDashing","AbsoluteFileName","AbsoluteOptions","AbsolutePointSize","AbsoluteThickness","AbsoluteTime","AbsoluteTiming","AcceptanceThreshold","AccountingForm","Accumulate","Accuracy","AccuracyGoal","AcousticAbsorbingValue","AcousticImpedanceValue","AcousticNormalVelocityValue","AcousticPDEComponent","AcousticPressureCondition","AcousticRadiationValue","AcousticSoundHardValue","AcousticSoundSoftCondition","ActionDelay","ActionMenu","ActionMenuBox","ActionMenuBoxOptions","Activate","Active","ActiveClassification","ActiveClassificationObject","ActiveItem","ActivePrediction","ActivePredictionObject","ActiveStyle","AcyclicGraphQ","AddOnHelpPath","AddSides","AddTo","AddToSearchIndex","AddUsers","AdjacencyGraph","AdjacencyList","AdjacencyMatrix","AdjacentMeshCells","Adjugate","AdjustmentBox","AdjustmentBoxOptions","AdjustTimeSeriesForecast","AdministrativeDivisionData","AffineHalfSpace","AffineSpace","AffineStateSpaceModel","AffineTransform","After","AggregatedEntityClass","AggregationLayer","AircraftData","AirportData","AirPressureData","AirSoundAttenuation","AirTemperatureData","AiryAi","AiryAiPrime","AiryAiZero","AiryBi","AiryBiPrime","AiryBiZero","AlgebraicIntegerQ","AlgebraicNumber","AlgebraicNumberDenominator","AlgebraicNumberNorm","AlgebraicNumberPolynomial","AlgebraicNumberTrace","AlgebraicRules","AlgebraicRulesData","Algebraics","AlgebraicUnitQ","Alignment","AlignmentMarker","AlignmentPoint","All","AllowAdultContent","AllowChatServices","AllowedCloudExtraParameters","AllowedCloudParameterExtensions","AllowedDimensions","AllowedFrequencyRange","AllowedHeads","AllowGroupClose","AllowIncomplete","AllowInlineCells","AllowKernelInitialization","AllowLooseGrammar","AllowReverseGroupClose","AllowScriptLevelChange","AllowVersionUpdate","AllTrue","Alphabet","AlphabeticOrder","AlphabeticSort","AlphaChannel","AlternateImage","AlternatingFactorial","AlternatingGroup","AlternativeHypothesis","Alternatives","AltitudeMethod","AmbientLight","AmbiguityFunction","AmbiguityList","Analytic","AnatomyData","AnatomyForm","AnatomyPlot3D","AnatomySkinStyle","AnatomyStyling","AnchoredSearch","And","AndersonDarlingTest","AngerJ","AngleBisector","AngleBracket","AnglePath","AnglePath3D","AngleVector","AngularGauge","Animate","AnimatedImage","AnimationCycleOffset","AnimationCycleRepetitions","AnimationDirection","AnimationDisplayTime","AnimationRate","AnimationRepetitions","AnimationRunning","AnimationRunTime","AnimationTimeIndex","AnimationVideo","Animator","AnimatorBox","AnimatorBoxOptions","AnimatorElements","Annotate","Annotation","AnnotationDelete","AnnotationKeys","AnnotationRules","AnnotationValue","Annuity","AnnuityDue","Annulus","AnomalyDetection","AnomalyDetector","AnomalyDetectorFunction","Anonymous","Antialiasing","Antihermitian","AntihermitianMatrixQ","Antisymmetric","AntisymmetricMatrixQ","Antonyms","AnyOrder","AnySubset","AnyTrue","Apart","ApartSquareFree","APIFunction","Appearance","AppearanceElements","AppearanceRules","AppellF1","Append","AppendCheck","AppendLayer","AppendTo","Application","Apply","ApplyReaction","ApplySides","ApplyTo","ArcCos","ArcCosh","ArcCot","ArcCoth","ArcCsc","ArcCsch","ArcCurvature","ARCHProcess","ArcLength","ArcSec","ArcSech","ArcSin","ArcSinDistribution","ArcSinh","ArcTan","ArcTanh","Area","Arg","ArgMax","ArgMin","ArgumentCountQ","ArgumentsOptions","ARIMAProcess","ArithmeticGeometricMean","ARMAProcess","Around","AroundReplace","ARProcess","Array","ArrayComponents","ArrayDepth","ArrayFilter","ArrayFlatten","ArrayMesh","ArrayPad","ArrayPlot","ArrayPlot3D","ArrayQ","ArrayReduce","ArrayResample","ArrayReshape","ArrayRules","Arrays","Arrow","Arrow3DBox","ArrowBox","Arrowheads","ASATriangle","Ask","AskAppend","AskConfirm","AskDisplay","AskedQ","AskedValue","AskFunction","AskState","AskTemplateDisplay","AspectRatio","AspectRatioFixed","Assert","AssessmentFunction","AssessmentResultObject","AssociateTo","Association","AssociationFormat","AssociationMap","AssociationQ","AssociationThread","AssumeDeterministic","Assuming","Assumptions","AstroAngularSeparation","AstroBackground","AstroCenter","AstroDistance","AstroGraphics","AstroGridLines","AstroGridLinesStyle","AstronomicalData","AstroPosition","AstroProjection","AstroRange","AstroRangePadding","AstroReferenceFrame","AstroStyling","AstroZoomLevel","Asymptotic","AsymptoticDSolveValue","AsymptoticEqual","AsymptoticEquivalent","AsymptoticExpectation","AsymptoticGreater","AsymptoticGreaterEqual","AsymptoticIntegrate","AsymptoticLess","AsymptoticLessEqual","AsymptoticOutputTracker","AsymptoticProbability","AsymptoticProduct","AsymptoticRSolveValue","AsymptoticSolve","AsymptoticSum","Asynchronous","AsynchronousTaskObject","AsynchronousTasks","Atom","AtomCoordinates","AtomCount","AtomDiagramCoordinates","AtomLabels","AtomLabelStyle","AtomList","AtomQ","AttachCell","AttachedCell","AttentionLayer","Attributes","Audio","AudioAmplify","AudioAnnotate","AudioAnnotationLookup","AudioBlockMap","AudioCapture","AudioChannelAssignment","AudioChannelCombine","AudioChannelMix","AudioChannels","AudioChannelSeparate","AudioData","AudioDelay","AudioDelete","AudioDevice","AudioDistance","AudioEncoding","AudioFade","AudioFrequencyShift","AudioGenerator","AudioIdentify","AudioInputDevice","AudioInsert","AudioInstanceQ","AudioIntervals","AudioJoin","AudioLabel","AudioLength","AudioLocalMeasurements","AudioLooping","AudioLoudness","AudioMeasurements","AudioNormalize","AudioOutputDevice","AudioOverlay","AudioPad","AudioPan","AudioPartition","AudioPause","AudioPitchShift","AudioPlay","AudioPlot","AudioQ","AudioRecord","AudioReplace","AudioResample","AudioReverb","AudioReverse","AudioSampleRate","AudioSpectralMap","AudioSpectralTransformation","AudioSplit","AudioStop","AudioStream","AudioStreams","AudioTimeStretch","AudioTrackApply","AudioTrackSelection","AudioTrim","AudioType","AugmentedPolyhedron","AugmentedSymmetricPolynomial","Authenticate","Authentication","AuthenticationDialog","AutoAction","Autocomplete","AutocompletionFunction","AutoCopy","AutocorrelationTest","AutoDelete","AutoEvaluateEvents","AutoGeneratedPackage","AutoIndent","AutoIndentSpacings","AutoItalicWords","AutoloadPath","AutoMatch","Automatic","AutomaticImageSize","AutoMultiplicationSymbol","AutoNumberFormatting","AutoOpenNotebooks","AutoOpenPalettes","AutoOperatorRenderings","AutoQuoteCharacters","AutoRefreshed","AutoRemove","AutorunSequencing","AutoScaling","AutoScroll","AutoSpacing","AutoStyleOptions","AutoStyleWords","AutoSubmitting","Axes","AxesEdge","AxesLabel","AxesOrigin","AxesStyle","AxiomaticTheory","Axis","Axis3DBox","Axis3DBoxOptions","AxisBox","AxisBoxOptions","AxisLabel","AxisObject","AxisStyle","BabyMonsterGroupB","Back","BackFaceColor","BackFaceGlowColor","BackFaceOpacity","BackFaceSpecularColor","BackFaceSpecularExponent","BackFaceSurfaceAppearance","BackFaceTexture","Background","BackgroundAppearance","BackgroundTasksSettings","Backslash","Backsubstitution","Backward","Ball","Band","BandpassFilter","BandstopFilter","BarabasiAlbertGraphDistribution","BarChart","BarChart3D","BarcodeImage","BarcodeRecognize","BaringhausHenzeTest","BarLegend","BarlowProschanImportance","BarnesG","BarOrigin","BarSpacing","BartlettHannWindow","BartlettWindow","BaseDecode","BaseEncode","BaseForm","Baseline","BaselinePosition","BaseStyle","BasicRecurrentLayer","BatchNormalizationLayer","BatchSize","BatesDistribution","BattleLemarieWavelet","BayesianMaximization","BayesianMaximizationObject","BayesianMinimization","BayesianMinimizationObject","Because","BeckmannDistribution","Beep","Before","Begin","BeginDialogPacket","BeginPackage","BellB","BellY","Below","BenfordDistribution","BeniniDistribution","BenktanderGibratDistribution","BenktanderWeibullDistribution","BernoulliB","BernoulliDistribution","BernoulliGraphDistribution","BernoulliProcess","BernsteinBasis","BesagL","BesselFilterModel","BesselI","BesselJ","BesselJZero","BesselK","BesselY","BesselYZero","Beta","BetaBinomialDistribution","BetaDistribution","BetaNegativeBinomialDistribution","BetaPrimeDistribution","BetaRegularized","Between","BetweennessCentrality","Beveled","BeveledPolyhedron","BezierCurve","BezierCurve3DBox","BezierCurve3DBoxOptions","BezierCurveBox","BezierCurveBoxOptions","BezierFunction","BilateralFilter","BilateralLaplaceTransform","BilateralZTransform","Binarize","BinaryDeserialize","BinaryDistance","BinaryFormat","BinaryImageQ","BinaryRead","BinaryReadList","BinarySerialize","BinaryWrite","BinCounts","BinLists","BinnedVariogramList","Binomial","BinomialDistribution","BinomialPointProcess","BinomialProcess","BinormalDistribution","BiorthogonalSplineWavelet","BioSequence","BioSequenceBackTranslateList","BioSequenceComplement","BioSequenceInstances","BioSequenceModify","BioSequencePlot","BioSequenceQ","BioSequenceReverseComplement","BioSequenceTranscribe","BioSequenceTranslate","BipartiteGraphQ","BiquadraticFilterModel","BirnbaumImportance","BirnbaumSaundersDistribution","BitAnd","BitClear","BitGet","BitLength","BitNot","BitOr","BitRate","BitSet","BitShiftLeft","BitShiftRight","BitXor","BiweightLocation","BiweightMidvariance","Black","BlackmanHarrisWindow","BlackmanNuttallWindow","BlackmanWindow","Blank","BlankForm","BlankNullSequence","BlankSequence","Blend","Block","BlockchainAddressData","BlockchainBase","BlockchainBlockData","BlockchainContractValue","BlockchainData","BlockchainGet","BlockchainKeyEncode","BlockchainPut","BlockchainTokenData","BlockchainTransaction","BlockchainTransactionData","BlockchainTransactionSign","BlockchainTransactionSubmit","BlockDiagonalMatrix","BlockLowerTriangularMatrix","BlockMap","BlockRandom","BlockUpperTriangularMatrix","BlomqvistBeta","BlomqvistBetaTest","Blue","Blur","Blurring","BodePlot","BohmanWindow","Bold","Bond","BondCount","BondLabels","BondLabelStyle","BondList","BondQ","Bookmarks","Boole","BooleanConsecutiveFunction","BooleanConvert","BooleanCountingFunction","BooleanFunction","BooleanGraph","BooleanMaxterms","BooleanMinimize","BooleanMinterms","BooleanQ","BooleanRegion","Booleans","BooleanStrings","BooleanTable","BooleanVariables","BorderDimensions","BorelTannerDistribution","Bottom","BottomHatTransform","BoundaryDiscretizeGraphics","BoundaryDiscretizeRegion","BoundaryMesh","BoundaryMeshRegion","BoundaryMeshRegionQ","BoundaryStyle","BoundedRegionQ","BoundingRegion","Bounds","Box","BoxBaselineShift","BoxData","BoxDimensions","Boxed","Boxes","BoxForm","BoxFormFormatTypes","BoxFrame","BoxID","BoxMargins","BoxMatrix","BoxObject","BoxRatios","BoxRotation","BoxRotationPoint","BoxStyle","BoxWhiskerChart","Bra","BracketingBar","BraKet","BrayCurtisDistance","BreadthFirstScan","Break","BridgeData","BrightnessEqualize","BroadcastStationData","Brown","BrownForsytheTest","BrownianBridgeProcess","BrowserCategory","BSplineBasis","BSplineCurve","BSplineCurve3DBox","BSplineCurve3DBoxOptions","BSplineCurveBox","BSplineCurveBoxOptions","BSplineFunction","BSplineSurface","BSplineSurface3DBox","BSplineSurface3DBoxOptions","BubbleChart","BubbleChart3D","BubbleScale","BubbleSizes","BuckyballGraph","BuildCompiledComponent","BuildingData","BulletGauge","BusinessDayQ","ButterflyGraph","ButterworthFilterModel","Button","ButtonBar","ButtonBox","ButtonBoxOptions","ButtonCell","ButtonContents","ButtonData","ButtonEvaluator","ButtonExpandable","ButtonFrame","ButtonFunction","ButtonMargins","ButtonMinHeight","ButtonNote","ButtonNotebook","ButtonSource","ButtonStyle","ButtonStyleMenuListing","Byte","ByteArray","ByteArrayFormat","ByteArrayFormatQ","ByteArrayQ","ByteArrayToString","ByteCount","ByteOrdering","C","CachedValue","CacheGraphics","CachePersistence","CalendarConvert","CalendarData","CalendarType","Callout","CalloutMarker","CalloutStyle","CallPacket","CanberraDistance","Cancel","CancelButton","CandlestickChart","CanonicalGraph","CanonicalizePolygon","CanonicalizePolyhedron","CanonicalizeRegion","CanonicalName","CanonicalWarpingCorrespondence","CanonicalWarpingDistance","CantorMesh","CantorStaircase","Canvas","Cap","CapForm","CapitalDifferentialD","Capitalize","CapsuleShape","CaptureRunning","CaputoD","CardinalBSplineBasis","CarlemanLinearize","CarlsonRC","CarlsonRD","CarlsonRE","CarlsonRF","CarlsonRG","CarlsonRJ","CarlsonRK","CarlsonRM","CarmichaelLambda","CaseOrdering","Cases","CaseSensitive","Cashflow","Casoratian","Cast","Catalan","CatalanNumber","Catch","CategoricalDistribution","Catenate","CatenateLayer","CauchyDistribution","CauchyMatrix","CauchyPointProcess","CauchyWindow","CayleyGraph","CDF","CDFDeploy","CDFInformation","CDFWavelet","Ceiling","CelestialSystem","Cell","CellAutoOverwrite","CellBaseline","CellBoundingBox","CellBracketOptions","CellChangeTimes","CellContents","CellContext","CellDingbat","CellDingbatMargin","CellDynamicExpression","CellEditDuplicate","CellElementsBoundingBox","CellElementSpacings","CellEpilog","CellEvaluationDuplicate","CellEvaluationFunction","CellEvaluationLanguage","CellEventActions","CellFrame","CellFrameColor","CellFrameLabelMargins","CellFrameLabels","CellFrameMargins","CellFrameStyle","CellGroup","CellGroupData","CellGrouping","CellGroupingRules","CellHorizontalScrolling","CellID","CellInsertionPointCell","CellLabel","CellLabelAutoDelete","CellLabelMargins","CellLabelPositioning","CellLabelStyle","CellLabelTemplate","CellMargins","CellObject","CellOpen","CellPrint","CellProlog","Cells","CellSize","CellStyle","CellTags","CellTrayPosition","CellTrayWidgets","CellularAutomaton","CensoredDistribution","Censoring","Center","CenterArray","CenterDot","CenteredInterval","CentralFeature","CentralMoment","CentralMomentGeneratingFunction","Cepstrogram","CepstrogramArray","CepstrumArray","CForm","ChampernowneNumber","ChangeOptions","ChannelBase","ChannelBrokerAction","ChannelDatabin","ChannelHistoryLength","ChannelListen","ChannelListener","ChannelListeners","ChannelListenerWait","ChannelObject","ChannelPreSendFunction","ChannelReceiverFunction","ChannelSend","ChannelSubscribers","ChanVeseBinarize","Character","CharacterCounts","CharacterEncoding","CharacterEncodingsPath","CharacteristicFunction","CharacteristicPolynomial","CharacterName","CharacterNormalize","CharacterRange","Characters","ChartBaseStyle","ChartElementData","ChartElementDataFunction","ChartElementFunction","ChartElements","ChartLabels","ChartLayout","ChartLegends","ChartStyle","Chebyshev1FilterModel","Chebyshev2FilterModel","ChebyshevDistance","ChebyshevT","ChebyshevU","Check","CheckAbort","CheckAll","CheckArguments","Checkbox","CheckboxBar","CheckboxBox","CheckboxBoxOptions","ChemicalConvert","ChemicalData","ChemicalFormula","ChemicalInstance","ChemicalReaction","ChessboardDistance","ChiDistribution","ChineseRemainder","ChiSquareDistribution","ChoiceButtons","ChoiceDialog","CholeskyDecomposition","Chop","ChromaticityPlot","ChromaticityPlot3D","ChromaticPolynomial","Circle","CircleBox","CircleDot","CircleMinus","CirclePlus","CirclePoints","CircleThrough","CircleTimes","CirculantGraph","CircularArcThrough","CircularOrthogonalMatrixDistribution","CircularQuaternionMatrixDistribution","CircularRealMatrixDistribution","CircularSymplecticMatrixDistribution","CircularUnitaryMatrixDistribution","Circumsphere","CityData","ClassifierFunction","ClassifierInformation","ClassifierMeasurements","ClassifierMeasurementsObject","Classify","ClassPriors","Clear","ClearAll","ClearAttributes","ClearCookies","ClearPermissions","ClearSystemCache","ClebschGordan","ClickPane","ClickToCopy","ClickToCopyEnabled","Clip","ClipboardNotebook","ClipFill","ClippingStyle","ClipPlanes","ClipPlanesStyle","ClipRange","Clock","ClockGauge","ClockwiseContourIntegral","Close","Closed","CloseKernels","ClosenessCentrality","Closing","ClosingAutoSave","ClosingEvent","CloudAccountData","CloudBase","CloudConnect","CloudConnections","CloudDeploy","CloudDirectory","CloudDisconnect","CloudEvaluate","CloudExport","CloudExpression","CloudExpressions","CloudFunction","CloudGet","CloudImport","CloudLoggingData","CloudObject","CloudObjectInformation","CloudObjectInformationData","CloudObjectNameFormat","CloudObjects","CloudObjectURLType","CloudPublish","CloudPut","CloudRenderingMethod","CloudSave","CloudShare","CloudSubmit","CloudSymbol","CloudUnshare","CloudUserID","ClusterClassify","ClusterDissimilarityFunction","ClusteringComponents","ClusteringMeasurements","ClusteringTree","CMYKColor","Coarse","CodeAssistOptions","Coefficient","CoefficientArrays","CoefficientDomain","CoefficientList","CoefficientRules","CoifletWavelet","Collect","CollinearPoints","Colon","ColonForm","ColorBalance","ColorCombine","ColorConvert","ColorCoverage","ColorData","ColorDataFunction","ColorDetect","ColorDistance","ColorFunction","ColorFunctionBinning","ColorFunctionScaling","Colorize","ColorNegate","ColorOutput","ColorProfileData","ColorQ","ColorQuantize","ColorReplace","ColorRules","ColorSelectorSettings","ColorSeparate","ColorSetter","ColorSetterBox","ColorSetterBoxOptions","ColorSlider","ColorsNear","ColorSpace","ColorToneMapping","Column","ColumnAlignments","ColumnBackgrounds","ColumnForm","ColumnLines","ColumnsEqual","ColumnSpacings","ColumnWidths","CombinatorB","CombinatorC","CombinatorI","CombinatorK","CombinatorS","CombinatorW","CombinatorY","CombinedEntityClass","CombinerFunction","CometData","CommonDefaultFormatTypes","Commonest","CommonestFilter","CommonName","CommonUnits","CommunityBoundaryStyle","CommunityGraphPlot","CommunityLabels","CommunityRegionStyle","CompanyData","CompatibleUnitQ","CompilationOptions","CompilationTarget","Compile","Compiled","CompiledCodeFunction","CompiledComponent","CompiledExpressionDeclaration","CompiledFunction","CompiledLayer","CompilerCallback","CompilerEnvironment","CompilerEnvironmentAppend","CompilerEnvironmentAppendTo","CompilerEnvironmentObject","CompilerOptions","Complement","ComplementedEntityClass","CompleteGraph","CompleteGraphQ","CompleteIntegral","CompleteKaryTree","CompletionsListPacket","Complex","ComplexArrayPlot","ComplexContourPlot","Complexes","ComplexExpand","ComplexInfinity","ComplexityFunction","ComplexListPlot","ComplexPlot","ComplexPlot3D","ComplexRegionPlot","ComplexStreamPlot","ComplexVectorPlot","ComponentMeasurements","ComponentwiseContextMenu","Compose","ComposeList","ComposeSeries","CompositeQ","Composition","CompoundElement","CompoundExpression","CompoundPoissonDistribution","CompoundPoissonProcess","CompoundRenewalProcess","Compress","CompressedData","CompressionLevel","ComputeUncertainty","ConcaveHullMesh","Condition","ConditionalExpression","Conditioned","Cone","ConeBox","ConfidenceLevel","ConfidenceRange","ConfidenceTransform","ConfigurationPath","Confirm","ConfirmAssert","ConfirmBy","ConfirmMatch","ConfirmQuiet","ConformationMethod","ConformAudio","ConformImages","Congruent","ConicGradientFilling","ConicHullRegion","ConicHullRegion3DBox","ConicHullRegion3DBoxOptions","ConicHullRegionBox","ConicHullRegionBoxOptions","ConicOptimization","Conjugate","ConjugateTranspose","Conjunction","Connect","ConnectedComponents","ConnectedGraphComponents","ConnectedGraphQ","ConnectedMeshComponents","ConnectedMoleculeComponents","ConnectedMoleculeQ","ConnectionSettings","ConnectLibraryCallbackFunction","ConnectSystemModelComponents","ConnectSystemModelController","ConnesWindow","ConoverTest","ConservativeConvectionPDETerm","ConsoleMessage","Constant","ConstantArray","ConstantArrayLayer","ConstantImage","ConstantPlusLayer","ConstantRegionQ","Constants","ConstantTimesLayer","ConstellationData","ConstrainedMax","ConstrainedMin","Construct","Containing","ContainsAll","ContainsAny","ContainsExactly","ContainsNone","ContainsOnly","ContentDetectorFunction","ContentFieldOptions","ContentLocationFunction","ContentObject","ContentPadding","ContentsBoundingBox","ContentSelectable","ContentSize","Context","ContextMenu","Contexts","ContextToFileName","Continuation","Continue","ContinuedFraction","ContinuedFractionK","ContinuousAction","ContinuousMarkovProcess","ContinuousTask","ContinuousTimeModelQ","ContinuousWaveletData","ContinuousWaveletTransform","ContourDetect","ContourGraphics","ContourIntegral","ContourLabels","ContourLines","ContourPlot","ContourPlot3D","Contours","ContourShading","ContourSmoothing","ContourStyle","ContraharmonicMean","ContrastiveLossLayer","Control","ControlActive","ControlAlignment","ControlGroupContentsBox","ControllabilityGramian","ControllabilityMatrix","ControllableDecomposition","ControllableModelQ","ControllerDuration","ControllerInformation","ControllerInformationData","ControllerLinking","ControllerManipulate","ControllerMethod","ControllerPath","ControllerState","ControlPlacement","ControlsRendering","ControlType","ConvectionPDETerm","Convergents","ConversionOptions","ConversionRules","ConvertToPostScript","ConvertToPostScriptPacket","ConvexHullMesh","ConvexHullRegion","ConvexOptimization","ConvexPolygonQ","ConvexPolyhedronQ","ConvexRegionQ","ConvolutionLayer","Convolve","ConwayGroupCo1","ConwayGroupCo2","ConwayGroupCo3","CookieFunction","Cookies","CoordinateBoundingBox","CoordinateBoundingBoxArray","CoordinateBounds","CoordinateBoundsArray","CoordinateChartData","CoordinatesToolOptions","CoordinateTransform","CoordinateTransformData","CoplanarPoints","CoprimeQ","Coproduct","CopulaDistribution","Copyable","CopyDatabin","CopyDirectory","CopyFile","CopyFunction","CopyTag","CopyToClipboard","CoreNilpotentDecomposition","CornerFilter","CornerNeighbors","Correlation","CorrelationDistance","CorrelationFunction","CorrelationTest","Cos","Cosh","CoshIntegral","CosineDistance","CosineWindow","CosIntegral","Cot","Coth","CoulombF","CoulombG","CoulombH1","CoulombH2","Count","CountDistinct","CountDistinctBy","CounterAssignments","CounterBox","CounterBoxOptions","CounterClockwiseContourIntegral","CounterEvaluator","CounterFunction","CounterIncrements","CounterStyle","CounterStyleMenuListing","CountRoots","CountryData","Counts","CountsBy","Covariance","CovarianceEstimatorFunction","CovarianceFunction","CoxianDistribution","CoxIngersollRossProcess","CoxModel","CoxModelFit","CramerVonMisesTest","CreateArchive","CreateCellID","CreateChannel","CreateCloudExpression","CreateCompilerEnvironment","CreateDatabin","CreateDataStructure","CreateDataSystemModel","CreateDialog","CreateDirectory","CreateDocument","CreateFile","CreateIntermediateDirectories","CreateLicenseEntitlement","CreateManagedLibraryExpression","CreateNotebook","CreatePacletArchive","CreatePalette","CreatePermissionsGroup","CreateScheduledTask","CreateSearchIndex","CreateSystemModel","CreateTemporary","CreateTypeInstance","CreateUUID","CreateWindow","CriterionFunction","CriticalityFailureImportance","CriticalitySuccessImportance","CriticalSection","Cross","CrossEntropyLossLayer","CrossingCount","CrossingDetect","CrossingPolygon","CrossMatrix","Csc","Csch","CSGRegion","CSGRegionQ","CSGRegionTree","CTCLossLayer","Cube","CubeRoot","Cubics","Cuboid","CuboidBox","CuboidBoxOptions","Cumulant","CumulantGeneratingFunction","CumulativeFeatureImpactPlot","Cup","CupCap","Curl","CurlyDoubleQuote","CurlyQuote","CurrencyConvert","CurrentDate","CurrentImage","CurrentNotebookImage","CurrentScreenImage","CurrentValue","Curry","CurryApplied","CurvatureFlowFilter","CurveClosed","Cyan","CycleGraph","CycleIndexPolynomial","Cycles","CyclicGroup","Cyclotomic","Cylinder","CylinderBox","CylinderBoxOptions","CylindricalDecomposition","CylindricalDecompositionFunction","D","DagumDistribution","DamData","DamerauLevenshteinDistance","DampingFactor","Darker","Dashed","Dashing","DatabaseConnect","DatabaseDisconnect","DatabaseReference","Databin","DatabinAdd","DatabinRemove","Databins","DatabinSubmit","DatabinUpload","DataCompression","DataDistribution","DataRange","DataReversed","Dataset","DatasetDisplayPanel","DatasetTheme","DataStructure","DataStructureQ","Date","DateBounds","Dated","DateDelimiters","DateDifference","DatedUnit","DateFormat","DateFunction","DateGranularity","DateHistogram","DateInterval","DateList","DateListLogPlot","DateListPlot","DateListStepPlot","DateObject","DateObjectQ","DateOverlapsQ","DatePattern","DatePlus","DateRange","DateReduction","DateScale","DateSelect","DateString","DateTicksFormat","DateValue","DateWithinQ","DaubechiesWavelet","DavisDistribution","DawsonF","DayCount","DayCountConvention","DayHemisphere","DaylightQ","DayMatchQ","DayName","DayNightTerminator","DayPlus","DayRange","DayRound","DeBruijnGraph","DeBruijnSequence","Debug","DebugTag","Decapitalize","Decimal","DecimalForm","DeclareCompiledComponent","DeclareKnownSymbols","DeclarePackage","Decompose","DeconvolutionLayer","Decrement","Decrypt","DecryptFile","DedekindEta","DeepSpaceProbeData","Default","Default2DTool","Default3DTool","DefaultAttachedCellStyle","DefaultAxesStyle","DefaultBaseStyle","DefaultBoxStyle","DefaultButton","DefaultColor","DefaultControlPlacement","DefaultDockedCellStyle","DefaultDuplicateCellStyle","DefaultDuration","DefaultElement","DefaultFaceGridsStyle","DefaultFieldHintStyle","DefaultFont","DefaultFontProperties","DefaultFormatType","DefaultFrameStyle","DefaultFrameTicksStyle","DefaultGridLinesStyle","DefaultInlineFormatType","DefaultInputFormatType","DefaultLabelStyle","DefaultMenuStyle","DefaultNaturalLanguage","DefaultNewCellStyle","DefaultNewInlineCellStyle","DefaultNotebook","DefaultOptions","DefaultOutputFormatType","DefaultPrintPrecision","DefaultStyle","DefaultStyleDefinitions","DefaultTextFormatType","DefaultTextInlineFormatType","DefaultTicksStyle","DefaultTooltipStyle","DefaultValue","DefaultValues","Defer","DefineExternal","DefineInputStreamMethod","DefineOutputStreamMethod","DefineResourceFunction","Definition","Degree","DegreeCentrality","DegreeGraphDistribution","DegreeLexicographic","DegreeReverseLexicographic","DEigensystem","DEigenvalues","Deinitialization","Del","DelaunayMesh","Delayed","Deletable","Delete","DeleteAdjacentDuplicates","DeleteAnomalies","DeleteBorderComponents","DeleteCases","DeleteChannel","DeleteCloudExpression","DeleteContents","DeleteDirectory","DeleteDuplicates","DeleteDuplicatesBy","DeleteElements","DeleteFile","DeleteMissing","DeleteObject","DeletePermissionsKey","DeleteSearchIndex","DeleteSmallComponents","DeleteStopwords","DeleteWithContents","DeletionWarning","DelimitedArray","DelimitedSequence","Delimiter","DelimiterAutoMatching","DelimiterFlashTime","DelimiterMatching","Delimiters","DeliveryFunction","Dendrogram","Denominator","DensityGraphics","DensityHistogram","DensityPlot","DensityPlot3D","DependentVariables","Deploy","Deployed","Depth","DepthFirstScan","Derivative","DerivativeFilter","DerivativePDETerm","DerivedKey","DescriptorStateSpace","DesignMatrix","DestroyAfterEvaluation","Det","DeviceClose","DeviceConfigure","DeviceExecute","DeviceExecuteAsynchronous","DeviceObject","DeviceOpen","DeviceOpenQ","DeviceRead","DeviceReadBuffer","DeviceReadLatest","DeviceReadList","DeviceReadTimeSeries","Devices","DeviceStreams","DeviceWrite","DeviceWriteBuffer","DGaussianWavelet","DiacriticalPositioning","Diagonal","DiagonalizableMatrixQ","DiagonalMatrix","DiagonalMatrixQ","Dialog","DialogIndent","DialogInput","DialogLevel","DialogNotebook","DialogProlog","DialogReturn","DialogSymbols","Diamond","DiamondMatrix","DiceDissimilarity","DictionaryLookup","DictionaryWordQ","DifferenceDelta","DifferenceOrder","DifferenceQuotient","DifferenceRoot","DifferenceRootReduce","Differences","DifferentialD","DifferentialRoot","DifferentialRootReduce","DifferentiatorFilter","DiffusionPDETerm","DiggleGatesPointProcess","DiggleGrattonPointProcess","DigitalSignature","DigitBlock","DigitBlockMinimum","DigitCharacter","DigitCount","DigitQ","DihedralAngle","DihedralGroup","Dilation","DimensionalCombinations","DimensionalMeshComponents","DimensionReduce","DimensionReducerFunction","DimensionReduction","Dimensions","DiracComb","DiracDelta","DirectedEdge","DirectedEdges","DirectedGraph","DirectedGraphQ","DirectedInfinity","Direction","DirectionalLight","Directive","Directory","DirectoryName","DirectoryQ","DirectoryStack","DirichletBeta","DirichletCharacter","DirichletCondition","DirichletConvolve","DirichletDistribution","DirichletEta","DirichletL","DirichletLambda","DirichletTransform","DirichletWindow","DisableConsolePrintPacket","DisableFormatting","DiscreteAsymptotic","DiscreteChirpZTransform","DiscreteConvolve","DiscreteDelta","DiscreteHadamardTransform","DiscreteIndicator","DiscreteInputOutputModel","DiscreteLimit","DiscreteLQEstimatorGains","DiscreteLQRegulatorGains","DiscreteLyapunovSolve","DiscreteMarkovProcess","DiscreteMaxLimit","DiscreteMinLimit","DiscretePlot","DiscretePlot3D","DiscreteRatio","DiscreteRiccatiSolve","DiscreteShift","DiscreteTimeModelQ","DiscreteUniformDistribution","DiscreteVariables","DiscreteWaveletData","DiscreteWaveletPacketTransform","DiscreteWaveletTransform","DiscretizeGraphics","DiscretizeRegion","Discriminant","DisjointQ","Disjunction","Disk","DiskBox","DiskBoxOptions","DiskMatrix","DiskSegment","Dispatch","DispatchQ","DispersionEstimatorFunction","Display","DisplayAllSteps","DisplayEndPacket","DisplayForm","DisplayFunction","DisplayPacket","DisplayRules","DisplayString","DisplayTemporary","DisplayWith","DisplayWithRef","DisplayWithVariable","DistanceFunction","DistanceMatrix","DistanceTransform","Distribute","Distributed","DistributedContexts","DistributeDefinitions","DistributionChart","DistributionDomain","DistributionFitTest","DistributionParameterAssumptions","DistributionParameterQ","Dithering","Div","Divergence","Divide","DivideBy","Dividers","DivideSides","Divisible","Divisors","DivisorSigma","DivisorSum","DMSList","DMSString","Do","DockedCell","DockedCells","DocumentGenerator","DocumentGeneratorInformation","DocumentGeneratorInformationData","DocumentGenerators","DocumentNotebook","DocumentWeightingRules","Dodecahedron","DomainRegistrationInformation","DominantColors","DominatorTreeGraph","DominatorVertexList","DOSTextFormat","Dot","DotDashed","DotEqual","DotLayer","DotPlusLayer","Dotted","DoubleBracketingBar","DoubleContourIntegral","DoubleDownArrow","DoubleLeftArrow","DoubleLeftRightArrow","DoubleLeftTee","DoubleLongLeftArrow","DoubleLongLeftRightArrow","DoubleLongRightArrow","DoubleRightArrow","DoubleRightTee","DoubleUpArrow","DoubleUpDownArrow","DoubleVerticalBar","DoublyInfinite","Down","DownArrow","DownArrowBar","DownArrowUpArrow","DownLeftRightVector","DownLeftTeeVector","DownLeftVector","DownLeftVectorBar","DownRightTeeVector","DownRightVector","DownRightVectorBar","Downsample","DownTee","DownTeeArrow","DownValues","DownValuesFunction","DragAndDrop","DrawBackFaces","DrawEdges","DrawFrontFaces","DrawHighlighted","DrazinInverse","Drop","DropoutLayer","DropShadowing","DSolve","DSolveChangeVariables","DSolveValue","Dt","DualLinearProgramming","DualPlanarGraph","DualPolyhedron","DualSystemsModel","DumpGet","DumpSave","DuplicateFreeQ","Duration","Dynamic","DynamicBox","DynamicBoxOptions","DynamicEvaluationTimeout","DynamicGeoGraphics","DynamicImage","DynamicLocation","DynamicModule","DynamicModuleBox","DynamicModuleBoxOptions","DynamicModuleParent","DynamicModuleValues","DynamicName","DynamicNamespace","DynamicReference","DynamicSetting","DynamicUpdating","DynamicWrapper","DynamicWrapperBox","DynamicWrapperBoxOptions","E","EarthImpactData","EarthquakeData","EccentricityCentrality","Echo","EchoEvaluation","EchoFunction","EchoLabel","EchoTiming","EclipseType","EdgeAdd","EdgeBetweennessCentrality","EdgeCapacity","EdgeCapForm","EdgeChromaticNumber","EdgeColor","EdgeConnectivity","EdgeContract","EdgeCost","EdgeCount","EdgeCoverQ","EdgeCycleMatrix","EdgeDashing","EdgeDelete","EdgeDetect","EdgeForm","EdgeIndex","EdgeJoinForm","EdgeLabeling","EdgeLabels","EdgeLabelStyle","EdgeList","EdgeOpacity","EdgeQ","EdgeRenderingFunction","EdgeRules","EdgeShapeFunction","EdgeStyle","EdgeTaggedGraph","EdgeTaggedGraphQ","EdgeTags","EdgeThickness","EdgeTransitiveGraphQ","EdgeValueRange","EdgeValueSizes","EdgeWeight","EdgeWeightedGraphQ","Editable","EditButtonSettings","EditCellTagsSettings","EditDistance","EffectiveInterest","Eigensystem","Eigenvalues","EigenvectorCentrality","Eigenvectors","Element","ElementData","ElementwiseLayer","ElidedForms","Eliminate","EliminationOrder","Ellipsoid","EllipticE","EllipticExp","EllipticExpPrime","EllipticF","EllipticFilterModel","EllipticK","EllipticLog","EllipticNomeQ","EllipticPi","EllipticReducedHalfPeriods","EllipticTheta","EllipticThetaPrime","EmbedCode","EmbeddedHTML","EmbeddedService","EmbeddedSQLEntityClass","EmbeddedSQLExpression","EmbeddingLayer","EmbeddingObject","EmitSound","EmphasizeSyntaxErrors","EmpiricalDistribution","Empty","EmptyGraphQ","EmptyRegion","EmptySpaceF","EnableConsolePrintPacket","Enabled","Enclose","Encode","Encrypt","EncryptedObject","EncryptFile","End","EndAdd","EndDialogPacket","EndOfBuffer","EndOfFile","EndOfLine","EndOfString","EndPackage","EngineEnvironment","EngineeringForm","Enter","EnterExpressionPacket","EnterTextPacket","Entity","EntityClass","EntityClassList","EntityCopies","EntityFunction","EntityGroup","EntityInstance","EntityList","EntityPrefetch","EntityProperties","EntityProperty","EntityPropertyClass","EntityRegister","EntityStore","EntityStores","EntityTypeName","EntityUnregister","EntityValue","Entropy","EntropyFilter","Environment","Epilog","EpilogFunction","Equal","EqualColumns","EqualRows","EqualTilde","EqualTo","EquatedTo","Equilibrium","EquirippleFilterKernel","Equivalent","Erf","Erfc","Erfi","ErlangB","ErlangC","ErlangDistribution","Erosion","ErrorBox","ErrorBoxOptions","ErrorNorm","ErrorPacket","ErrorsDialogSettings","EscapeRadius","EstimatedBackground","EstimatedDistribution","EstimatedPointNormals","EstimatedPointProcess","EstimatedProcess","EstimatedVariogramModel","EstimatorGains","EstimatorRegulator","EuclideanDistance","EulerAngles","EulerCharacteristic","EulerE","EulerGamma","EulerianGraphQ","EulerMatrix","EulerPhi","Evaluatable","Evaluate","Evaluated","EvaluatePacket","EvaluateScheduledTask","EvaluationBox","EvaluationCell","EvaluationCompletionAction","EvaluationData","EvaluationElements","EvaluationEnvironment","EvaluationMode","EvaluationMonitor","EvaluationNotebook","EvaluationObject","EvaluationOrder","EvaluationPrivileges","EvaluationRateLimit","Evaluator","EvaluatorNames","EvenQ","EventData","EventEvaluator","EventHandler","EventHandlerTag","EventLabels","EventSeries","ExactBlackmanWindow","ExactNumberQ","ExactRootIsolation","ExampleData","Except","ExcludedContexts","ExcludedForms","ExcludedLines","ExcludedPhysicalQuantities","ExcludePods","Exclusions","ExclusionsStyle","Exists","Exit","ExitDialog","ExoplanetData","Exp","Expand","ExpandAll","ExpandDenominator","ExpandFileName","ExpandNumerator","Expectation","ExpectationE","ExpectedValue","ExpGammaDistribution","ExpIntegralE","ExpIntegralEi","ExpirationDate","Exponent","ExponentFunction","ExponentialDistribution","ExponentialFamily","ExponentialGeneratingFunction","ExponentialMovingAverage","ExponentialPowerDistribution","ExponentPosition","ExponentStep","Export","ExportAutoReplacements","ExportByteArray","ExportForm","ExportPacket","ExportString","Expression","ExpressionCell","ExpressionGraph","ExpressionPacket","ExpressionTree","ExpressionUUID","ExpToTrig","ExtendedEntityClass","ExtendedGCD","Extension","ExtentElementFunction","ExtentMarkers","ExtentSize","ExternalBundle","ExternalCall","ExternalDataCharacterEncoding","ExternalEvaluate","ExternalFunction","ExternalFunctionName","ExternalIdentifier","ExternalObject","ExternalOptions","ExternalSessionObject","ExternalSessions","ExternalStorageBase","ExternalStorageDownload","ExternalStorageGet","ExternalStorageObject","ExternalStoragePut","ExternalStorageUpload","ExternalTypeSignature","ExternalValue","Extract","ExtractArchive","ExtractLayer","ExtractPacletArchive","ExtremeValueDistribution","FaceAlign","FaceForm","FaceGrids","FaceGridsStyle","FaceRecognize","FacialFeatures","Factor","FactorComplete","Factorial","Factorial2","FactorialMoment","FactorialMomentGeneratingFunction","FactorialPower","FactorInteger","FactorList","FactorSquareFree","FactorSquareFreeList","FactorTerms","FactorTermsList","Fail","Failure","FailureAction","FailureDistribution","FailureQ","False","FareySequence","FARIMAProcess","FeatureDistance","FeatureExtract","FeatureExtraction","FeatureExtractor","FeatureExtractorFunction","FeatureImpactPlot","FeatureNames","FeatureNearest","FeatureSpacePlot","FeatureSpacePlot3D","FeatureTypes","FeatureValueDependencyPlot","FeatureValueImpactPlot","FEDisableConsolePrintPacket","FeedbackLinearize","FeedbackSector","FeedbackSectorStyle","FeedbackType","FEEnableConsolePrintPacket","FetalGrowthData","Fibonacci","Fibonorial","FieldCompletionFunction","FieldHint","FieldHintStyle","FieldMasked","FieldSize","File","FileBaseName","FileByteCount","FileConvert","FileDate","FileExistsQ","FileExtension","FileFormat","FileFormatProperties","FileFormatQ","FileHandler","FileHash","FileInformation","FileName","FileNameDepth","FileNameDialogSettings","FileNameDrop","FileNameForms","FileNameJoin","FileNames","FileNameSetter","FileNameSplit","FileNameTake","FileNameToFormatList","FilePrint","FileSize","FileSystemMap","FileSystemScan","FileSystemTree","FileTemplate","FileTemplateApply","FileType","FilledCurve","FilledCurveBox","FilledCurveBoxOptions","FilledTorus","FillForm","Filling","FillingStyle","FillingTransform","FilteredEntityClass","FilterRules","FinancialBond","FinancialData","FinancialDerivative","FinancialIndicator","Find","FindAnomalies","FindArgMax","FindArgMin","FindChannels","FindClique","FindClusters","FindCookies","FindCurvePath","FindCycle","FindDevices","FindDistribution","FindDistributionParameters","FindDivisions","FindEdgeColoring","FindEdgeCover","FindEdgeCut","FindEdgeIndependentPaths","FindEquationalProof","FindEulerianCycle","FindExternalEvaluators","FindFaces","FindFile","FindFit","FindFormula","FindFundamentalCycles","FindGeneratingFunction","FindGeoLocation","FindGeometricConjectures","FindGeometricTransform","FindGraphCommunities","FindGraphIsomorphism","FindGraphPartition","FindHamiltonianCycle","FindHamiltonianPath","FindHiddenMarkovStates","FindImageText","FindIndependentEdgeSet","FindIndependentVertexSet","FindInstance","FindIntegerNullVector","FindIsomers","FindIsomorphicSubgraph","FindKClan","FindKClique","FindKClub","FindKPlex","FindLibrary","FindLinearRecurrence","FindList","FindMatchingColor","FindMaximum","FindMaximumCut","FindMaximumFlow","FindMaxValue","FindMeshDefects","FindMinimum","FindMinimumCostFlow","FindMinimumCut","FindMinValue","FindMoleculeSubstructure","FindPath","FindPeaks","FindPermutation","FindPlanarColoring","FindPointProcessParameters","FindPostmanTour","FindProcessParameters","FindRegionTransform","FindRepeat","FindRoot","FindSequenceFunction","FindSettings","FindShortestPath","FindShortestTour","FindSpanningTree","FindSubgraphIsomorphism","FindSystemModelEquilibrium","FindTextualAnswer","FindThreshold","FindTransientRepeat","FindVertexColoring","FindVertexCover","FindVertexCut","FindVertexIndependentPaths","Fine","FinishDynamic","FiniteAbelianGroupCount","FiniteGroupCount","FiniteGroupData","First","FirstCase","FirstPassageTimeDistribution","FirstPosition","FischerGroupFi22","FischerGroupFi23","FischerGroupFi24Prime","FisherHypergeometricDistribution","FisherRatioTest","FisherZDistribution","Fit","FitAll","FitRegularization","FittedModel","FixedOrder","FixedPoint","FixedPointList","FlashSelection","Flat","FlatShading","Flatten","FlattenAt","FlattenLayer","FlatTopWindow","FlightData","FlipView","Floor","FlowPolynomial","Fold","FoldList","FoldPair","FoldPairList","FoldWhile","FoldWhileList","FollowRedirects","Font","FontColor","FontFamily","FontForm","FontName","FontOpacity","FontPostScriptName","FontProperties","FontReencoding","FontSize","FontSlant","FontSubstitutions","FontTracking","FontVariations","FontWeight","For","ForAll","ForAllType","ForceVersionInstall","Format","FormatRules","FormatType","FormatTypeAutoConvert","FormatValues","FormBox","FormBoxOptions","FormControl","FormFunction","FormLayoutFunction","FormObject","FormPage","FormProtectionMethod","FormTheme","FormulaData","FormulaLookup","FortranForm","Forward","ForwardBackward","ForwardCloudCredentials","Fourier","FourierCoefficient","FourierCosCoefficient","FourierCosSeries","FourierCosTransform","FourierDCT","FourierDCTFilter","FourierDCTMatrix","FourierDST","FourierDSTMatrix","FourierMatrix","FourierParameters","FourierSequenceTransform","FourierSeries","FourierSinCoefficient","FourierSinSeries","FourierSinTransform","FourierTransform","FourierTrigSeries","FoxH","FoxHReduce","FractionalBrownianMotionProcess","FractionalD","FractionalGaussianNoiseProcess","FractionalPart","FractionBox","FractionBoxOptions","FractionLine","Frame","FrameBox","FrameBoxOptions","Framed","FrameInset","FrameLabel","Frameless","FrameListVideo","FrameMargins","FrameRate","FrameStyle","FrameTicks","FrameTicksStyle","FRatioDistribution","FrechetDistribution","FreeQ","FrenetSerretSystem","FrequencySamplingFilterKernel","FresnelC","FresnelF","FresnelG","FresnelS","Friday","FrobeniusNumber","FrobeniusSolve","FromAbsoluteTime","FromCharacterCode","FromCoefficientRules","FromContinuedFraction","FromDate","FromDateString","FromDigits","FromDMS","FromEntity","FromJulianDate","FromLetterNumber","FromPolarCoordinates","FromRawPointer","FromRomanNumeral","FromSphericalCoordinates","FromUnixTime","Front","FrontEndDynamicExpression","FrontEndEventActions","FrontEndExecute","FrontEndObject","FrontEndResource","FrontEndResourceString","FrontEndStackSize","FrontEndToken","FrontEndTokenExecute","FrontEndValueCache","FrontEndVersion","FrontFaceColor","FrontFaceGlowColor","FrontFaceOpacity","FrontFaceSpecularColor","FrontFaceSpecularExponent","FrontFaceSurfaceAppearance","FrontFaceTexture","Full","FullAxes","FullDefinition","FullForm","FullGraphics","FullInformationOutputRegulator","FullOptions","FullRegion","FullSimplify","Function","FunctionAnalytic","FunctionBijective","FunctionCompile","FunctionCompileExport","FunctionCompileExportByteArray","FunctionCompileExportLibrary","FunctionCompileExportString","FunctionContinuous","FunctionConvexity","FunctionDeclaration","FunctionDiscontinuities","FunctionDomain","FunctionExpand","FunctionInjective","FunctionInterpolation","FunctionLayer","FunctionMeromorphic","FunctionMonotonicity","FunctionPeriod","FunctionPoles","FunctionRange","FunctionSign","FunctionSingularities","FunctionSpace","FunctionSurjective","FussellVeselyImportance","GaborFilter","GaborMatrix","GaborWavelet","GainMargins","GainPhaseMargins","GalaxyData","GalleryView","Gamma","GammaDistribution","GammaRegularized","GapPenalty","GARCHProcess","GatedRecurrentLayer","Gather","GatherBy","GaugeFaceElementFunction","GaugeFaceStyle","GaugeFrameElementFunction","GaugeFrameSize","GaugeFrameStyle","GaugeLabels","GaugeMarkers","GaugeStyle","GaussianFilter","GaussianIntegers","GaussianMatrix","GaussianOrthogonalMatrixDistribution","GaussianSymplecticMatrixDistribution","GaussianUnitaryMatrixDistribution","GaussianWindow","GCD","GegenbauerC","General","GeneralizedLinearModelFit","GenerateAsymmetricKeyPair","GenerateConditions","GeneratedAssetFormat","GeneratedAssetLocation","GeneratedCell","GeneratedCellStyles","GeneratedDocumentBinding","GenerateDerivedKey","GenerateDigitalSignature","GenerateDocument","GeneratedParameters","GeneratedQuantityMagnitudes","GenerateFileSignature","GenerateHTTPResponse","GenerateSecuredAuthenticationKey","GenerateSymmetricKey","GeneratingFunction","GeneratorDescription","GeneratorHistoryLength","GeneratorOutputType","Generic","GenericCylindricalDecomposition","GenomeData","GenomeLookup","GeoAntipode","GeoArea","GeoArraySize","GeoBackground","GeoBoundary","GeoBoundingBox","GeoBounds","GeoBoundsRegion","GeoBoundsRegionBoundary","GeoBubbleChart","GeoCenter","GeoCircle","GeoContourPlot","GeoDensityPlot","GeodesicClosing","GeodesicDilation","GeodesicErosion","GeodesicOpening","GeodesicPolyhedron","GeoDestination","GeodesyData","GeoDirection","GeoDisk","GeoDisplacement","GeoDistance","GeoDistanceList","GeoElevationData","GeoEntities","GeoGraphics","GeoGraphPlot","GeoGraphValuePlot","GeogravityModelData","GeoGridDirectionDifference","GeoGridLines","GeoGridLinesStyle","GeoGridPosition","GeoGridRange","GeoGridRangePadding","GeoGridUnitArea","GeoGridUnitDistance","GeoGridVector","GeoGroup","GeoHemisphere","GeoHemisphereBoundary","GeoHistogram","GeoIdentify","GeoImage","GeoLabels","GeoLength","GeoListPlot","GeoLocation","GeologicalPeriodData","GeomagneticModelData","GeoMarker","GeometricAssertion","GeometricBrownianMotionProcess","GeometricDistribution","GeometricMean","GeometricMeanFilter","GeometricOptimization","GeometricScene","GeometricStep","GeometricStylingRules","GeometricTest","GeometricTransformation","GeometricTransformation3DBox","GeometricTransformation3DBoxOptions","GeometricTransformationBox","GeometricTransformationBoxOptions","GeoModel","GeoNearest","GeoOrientationData","GeoPath","GeoPolygon","GeoPosition","GeoPositionENU","GeoPositionXYZ","GeoProjection","GeoProjectionData","GeoRange","GeoRangePadding","GeoRegionValuePlot","GeoResolution","GeoScaleBar","GeoServer","GeoSmoothHistogram","GeoStreamPlot","GeoStyling","GeoStylingImageFunction","GeoVariant","GeoVector","GeoVectorENU","GeoVectorPlot","GeoVectorXYZ","GeoVisibleRegion","GeoVisibleRegionBoundary","GeoWithinQ","GeoZoomLevel","GestureHandler","GestureHandlerTag","Get","GetContext","GetEnvironment","GetFileName","GetLinebreakInformationPacket","GibbsPointProcess","Glaisher","GlobalClusteringCoefficient","GlobalPreferences","GlobalSession","Glow","GoldenAngle","GoldenRatio","GompertzMakehamDistribution","GoochShading","GoodmanKruskalGamma","GoodmanKruskalGammaTest","Goto","GouraudShading","Grad","Gradient","GradientFilter","GradientFittedMesh","GradientOrientationFilter","GrammarApply","GrammarRules","GrammarToken","Graph","Graph3D","GraphAssortativity","GraphAutomorphismGroup","GraphCenter","GraphComplement","GraphData","GraphDensity","GraphDiameter","GraphDifference","GraphDisjointUnion","GraphDistance","GraphDistanceMatrix","GraphEmbedding","GraphHighlight","GraphHighlightStyle","GraphHub","Graphics","Graphics3D","Graphics3DBox","Graphics3DBoxOptions","GraphicsArray","GraphicsBaseline","GraphicsBox","GraphicsBoxOptions","GraphicsColor","GraphicsColumn","GraphicsComplex","GraphicsComplex3DBox","GraphicsComplex3DBoxOptions","GraphicsComplexBox","GraphicsComplexBoxOptions","GraphicsContents","GraphicsData","GraphicsGrid","GraphicsGridBox","GraphicsGroup","GraphicsGroup3DBox","GraphicsGroup3DBoxOptions","GraphicsGroupBox","GraphicsGroupBoxOptions","GraphicsGrouping","GraphicsHighlightColor","GraphicsRow","GraphicsSpacing","GraphicsStyle","GraphIntersection","GraphJoin","GraphLayerLabels","GraphLayers","GraphLayerStyle","GraphLayout","GraphLinkEfficiency","GraphPeriphery","GraphPlot","GraphPlot3D","GraphPower","GraphProduct","GraphPropertyDistribution","GraphQ","GraphRadius","GraphReciprocity","GraphRoot","GraphStyle","GraphSum","GraphTree","GraphUnion","Gray","GrayLevel","Greater","GreaterEqual","GreaterEqualLess","GreaterEqualThan","GreaterFullEqual","GreaterGreater","GreaterLess","GreaterSlantEqual","GreaterThan","GreaterTilde","GreekStyle","Green","GreenFunction","Grid","GridBaseline","GridBox","GridBoxAlignment","GridBoxBackground","GridBoxDividers","GridBoxFrame","GridBoxItemSize","GridBoxItemStyle","GridBoxOptions","GridBoxSpacings","GridCreationSettings","GridDefaultElement","GridElementStyleOptions","GridFrame","GridFrameMargins","GridGraph","GridLines","GridLinesStyle","GridVideo","GroebnerBasis","GroupActionBase","GroupBy","GroupCentralizer","GroupElementFromWord","GroupElementPosition","GroupElementQ","GroupElements","GroupElementToWord","GroupGenerators","Groupings","GroupMultiplicationTable","GroupOpenerColor","GroupOpenerInsideFrame","GroupOrbits","GroupOrder","GroupPageBreakWithin","GroupSetwiseStabilizer","GroupStabilizer","GroupStabilizerChain","GroupTogetherGrouping","GroupTogetherNestedGrouping","GrowCutComponents","Gudermannian","GuidedFilter","GumbelDistribution","HaarWavelet","HadamardMatrix","HalfLine","HalfNormalDistribution","HalfPlane","HalfSpace","HalftoneShading","HamiltonianGraphQ","HammingDistance","HammingWindow","HandlerFunctions","HandlerFunctionsKeys","HankelH1","HankelH2","HankelMatrix","HankelTransform","HannPoissonWindow","HannWindow","HaradaNortonGroupHN","HararyGraph","HardcorePointProcess","HarmonicMean","HarmonicMeanFilter","HarmonicNumber","Hash","HatchFilling","HatchShading","Haversine","HazardFunction","Head","HeadCompose","HeaderAlignment","HeaderBackground","HeaderDisplayFunction","HeaderLines","Headers","HeaderSize","HeaderStyle","Heads","HeatFluxValue","HeatInsulationValue","HeatOutflowValue","HeatRadiationValue","HeatSymmetryValue","HeatTemperatureCondition","HeatTransferPDEComponent","HeatTransferValue","HeavisideLambda","HeavisidePi","HeavisideTheta","HeldGroupHe","HeldPart","HelmholtzPDEComponent","HelpBrowserLookup","HelpBrowserNotebook","HelpBrowserSettings","HelpViewerSettings","Here","HermiteDecomposition","HermiteH","Hermitian","HermitianMatrixQ","HessenbergDecomposition","Hessian","HeunB","HeunBPrime","HeunC","HeunCPrime","HeunD","HeunDPrime","HeunG","HeunGPrime","HeunT","HeunTPrime","HexadecimalCharacter","Hexahedron","HexahedronBox","HexahedronBoxOptions","HiddenItems","HiddenMarkovProcess","HiddenSurface","Highlighted","HighlightGraph","HighlightImage","HighlightMesh","HighlightString","HighpassFilter","HigmanSimsGroupHS","HilbertCurve","HilbertFilter","HilbertMatrix","Histogram","Histogram3D","HistogramDistribution","HistogramList","HistogramPointDensity","HistogramTransform","HistogramTransformInterpolation","HistoricalPeriodData","HitMissTransform","HITSCentrality","HjorthDistribution","HodgeDual","HoeffdingD","HoeffdingDTest","Hold","HoldAll","HoldAllComplete","HoldComplete","HoldFirst","HoldForm","HoldPattern","HoldRest","HolidayCalendar","HomeDirectory","HomePage","Horizontal","HorizontalForm","HorizontalGauge","HorizontalScrollPosition","HornerForm","HostLookup","HotellingTSquareDistribution","HoytDistribution","HTMLSave","HTTPErrorResponse","HTTPRedirect","HTTPRequest","HTTPRequestData","HTTPResponse","Hue","HumanGrowthData","HumpDownHump","HumpEqual","HurwitzLerchPhi","HurwitzZeta","HyperbolicDistribution","HypercubeGraph","HyperexponentialDistribution","Hyperfactorial","Hypergeometric0F1","Hypergeometric0F1Regularized","Hypergeometric1F1","Hypergeometric1F1Regularized","Hypergeometric2F1","Hypergeometric2F1Regularized","HypergeometricDistribution","HypergeometricPFQ","HypergeometricPFQRegularized","HypergeometricU","Hyperlink","HyperlinkAction","HyperlinkCreationSettings","Hyperplane","Hyphenation","HyphenationOptions","HypoexponentialDistribution","HypothesisTestData","I","IconData","Iconize","IconizedObject","IconRules","Icosahedron","Identity","IdentityMatrix","If","IfCompiled","IgnoreCase","IgnoreDiacritics","IgnoreIsotopes","IgnorePunctuation","IgnoreSpellCheck","IgnoreStereochemistry","IgnoringInactive","Im","Image","Image3D","Image3DProjection","Image3DSlices","ImageAccumulate","ImageAdd","ImageAdjust","ImageAlign","ImageApply","ImageApplyIndexed","ImageAspectRatio","ImageAssemble","ImageAugmentationLayer","ImageBoundingBoxes","ImageCache","ImageCacheValid","ImageCapture","ImageCaptureFunction","ImageCases","ImageChannels","ImageClip","ImageCollage","ImageColorSpace","ImageCompose","ImageContainsQ","ImageContents","ImageConvolve","ImageCooccurrence","ImageCorners","ImageCorrelate","ImageCorrespondingPoints","ImageCrop","ImageData","ImageDeconvolve","ImageDemosaic","ImageDifference","ImageDimensions","ImageDisplacements","ImageDistance","ImageEditMode","ImageEffect","ImageExposureCombine","ImageFeatureTrack","ImageFileApply","ImageFileFilter","ImageFileScan","ImageFilter","ImageFocusCombine","ImageForestingComponents","ImageFormattingWidth","ImageForwardTransformation","ImageGraphics","ImageHistogram","ImageIdentify","ImageInstanceQ","ImageKeypoints","ImageLabels","ImageLegends","ImageLevels","ImageLines","ImageMargins","ImageMarker","ImageMarkers","ImageMeasurements","ImageMesh","ImageMultiply","ImageOffset","ImagePad","ImagePadding","ImagePartition","ImagePeriodogram","ImagePerspectiveTransformation","ImagePosition","ImagePreviewFunction","ImagePyramid","ImagePyramidApply","ImageQ","ImageRangeCache","ImageRecolor","ImageReflect","ImageRegion","ImageResize","ImageResolution","ImageRestyle","ImageRotate","ImageRotated","ImageSaliencyFilter","ImageScaled","ImageScan","ImageSize","ImageSizeAction","ImageSizeCache","ImageSizeMultipliers","ImageSizeRaw","ImageStitch","ImageSubtract","ImageTake","ImageTransformation","ImageTrim","ImageType","ImageValue","ImageValuePositions","ImageVectorscopePlot","ImageWaveformPlot","ImagingDevice","ImplicitD","ImplicitRegion","Implies","Import","ImportAutoReplacements","ImportByteArray","ImportedObject","ImportOptions","ImportString","ImprovementImportance","In","Inactivate","Inactive","InactiveStyle","IncidenceGraph","IncidenceList","IncidenceMatrix","IncludeAromaticBonds","IncludeConstantBasis","IncludedContexts","IncludeDefinitions","IncludeDirectories","IncludeFileExtension","IncludeGeneratorTasks","IncludeHydrogens","IncludeInflections","IncludeMetaInformation","IncludePods","IncludeQuantities","IncludeRelatedTables","IncludeSingularSolutions","IncludeSingularTerm","IncludeWindowTimes","Increment","IndefiniteMatrixQ","Indent","IndentingNewlineSpacings","IndentMaxFraction","IndependenceTest","IndependentEdgeSetQ","IndependentPhysicalQuantity","IndependentUnit","IndependentUnitDimension","IndependentVertexSetQ","Indeterminate","IndeterminateThreshold","IndexCreationOptions","Indexed","IndexEdgeTaggedGraph","IndexGraph","IndexTag","Inequality","InertEvaluate","InertExpression","InexactNumberQ","InexactNumbers","InfiniteFuture","InfiniteLine","InfiniteLineThrough","InfinitePast","InfinitePlane","Infinity","Infix","InflationAdjust","InflationMethod","Information","InformationData","InformationDataGrid","Inherited","InheritScope","InhomogeneousPoissonPointProcess","InhomogeneousPoissonProcess","InitialEvaluationHistory","Initialization","InitializationCell","InitializationCellEvaluation","InitializationCellWarning","InitializationObject","InitializationObjects","InitializationValue","Initialize","InitialSeeding","InlineCounterAssignments","InlineCounterIncrements","InlineRules","Inner","InnerPolygon","InnerPolyhedron","Inpaint","Input","InputAliases","InputAssumptions","InputAutoReplacements","InputField","InputFieldBox","InputFieldBoxOptions","InputForm","InputGrouping","InputNamePacket","InputNotebook","InputPacket","InputPorts","InputSettings","InputStream","InputString","InputStringPacket","InputToBoxFormPacket","Insert","InsertionFunction","InsertionPointObject","InsertLinebreaks","InsertResults","Inset","Inset3DBox","Inset3DBoxOptions","InsetBox","InsetBoxOptions","Insphere","Install","InstallService","InstanceNormalizationLayer","InString","Integer","IntegerDigits","IntegerExponent","IntegerLength","IntegerName","IntegerPart","IntegerPartitions","IntegerQ","IntegerReverse","Integers","IntegerString","Integral","Integrate","IntegrateChangeVariables","Interactive","InteractiveTradingChart","InterfaceSwitched","Interlaced","Interleaving","InternallyBalancedDecomposition","InterpolatingFunction","InterpolatingPolynomial","Interpolation","InterpolationOrder","InterpolationPoints","InterpolationPrecision","Interpretation","InterpretationBox","InterpretationBoxOptions","InterpretationFunction","Interpreter","InterpretTemplate","InterquartileRange","Interrupt","InterruptSettings","IntersectedEntityClass","IntersectingQ","Intersection","Interval","IntervalIntersection","IntervalMarkers","IntervalMarkersStyle","IntervalMemberQ","IntervalSlider","IntervalUnion","Into","Inverse","InverseBetaRegularized","InverseBilateralLaplaceTransform","InverseBilateralZTransform","InverseCDF","InverseChiSquareDistribution","InverseContinuousWaveletTransform","InverseDistanceTransform","InverseEllipticNomeQ","InverseErf","InverseErfc","InverseFourier","InverseFourierCosTransform","InverseFourierSequenceTransform","InverseFourierSinTransform","InverseFourierTransform","InverseFunction","InverseFunctions","InverseGammaDistribution","InverseGammaRegularized","InverseGaussianDistribution","InverseGudermannian","InverseHankelTransform","InverseHaversine","InverseImagePyramid","InverseJacobiCD","InverseJacobiCN","InverseJacobiCS","InverseJacobiDC","InverseJacobiDN","InverseJacobiDS","InverseJacobiNC","InverseJacobiND","InverseJacobiNS","InverseJacobiSC","InverseJacobiSD","InverseJacobiSN","InverseLaplaceTransform","InverseMellinTransform","InversePermutation","InverseRadon","InverseRadonTransform","InverseSeries","InverseShortTimeFourier","InverseSpectrogram","InverseSurvivalFunction","InverseTransformedRegion","InverseWaveletTransform","InverseWeierstrassP","InverseWishartMatrixDistribution","InverseZTransform","Invisible","InvisibleApplication","InvisibleTimes","IPAddress","IrreduciblePolynomialQ","IslandData","IsolatingInterval","IsomorphicGraphQ","IsomorphicSubgraphQ","IsotopeData","Italic","Item","ItemAspectRatio","ItemBox","ItemBoxOptions","ItemDisplayFunction","ItemSize","ItemStyle","ItoProcess","JaccardDissimilarity","JacobiAmplitude","Jacobian","JacobiCD","JacobiCN","JacobiCS","JacobiDC","JacobiDN","JacobiDS","JacobiEpsilon","JacobiNC","JacobiND","JacobiNS","JacobiP","JacobiSC","JacobiSD","JacobiSN","JacobiSymbol","JacobiZeta","JacobiZN","JankoGroupJ1","JankoGroupJ2","JankoGroupJ3","JankoGroupJ4","JarqueBeraALMTest","JohnsonDistribution","Join","JoinAcross","Joined","JoinedCurve","JoinedCurveBox","JoinedCurveBoxOptions","JoinForm","JordanDecomposition","JordanModelDecomposition","JulianDate","JuliaSetBoettcher","JuliaSetIterationCount","JuliaSetPlot","JuliaSetPoints","K","KagiChart","KaiserBesselWindow","KaiserWindow","KalmanEstimator","KalmanFilter","KarhunenLoeveDecomposition","KaryTree","KatzCentrality","KCoreComponents","KDistribution","KEdgeConnectedComponents","KEdgeConnectedGraphQ","KeepExistingVersion","KelvinBei","KelvinBer","KelvinKei","KelvinKer","KendallTau","KendallTauTest","KernelConfiguration","KernelExecute","KernelFunction","KernelMixtureDistribution","KernelObject","Kernels","Ket","Key","KeyCollisionFunction","KeyComplement","KeyDrop","KeyDropFrom","KeyExistsQ","KeyFreeQ","KeyIntersection","KeyMap","KeyMemberQ","KeypointStrength","Keys","KeySelect","KeySort","KeySortBy","KeyTake","KeyUnion","KeyValueMap","KeyValuePattern","Khinchin","KillProcess","KirchhoffGraph","KirchhoffMatrix","KleinInvariantJ","KnapsackSolve","KnightTourGraph","KnotData","KnownUnitQ","KochCurve","KolmogorovSmirnovTest","KroneckerDelta","KroneckerModelDecomposition","KroneckerProduct","KroneckerSymbol","KuiperTest","KumaraswamyDistribution","Kurtosis","KuwaharaFilter","KVertexConnectedComponents","KVertexConnectedGraphQ","LABColor","Label","Labeled","LabeledSlider","LabelingFunction","LabelingSize","LabelStyle","LabelVisibility","LaguerreL","LakeData","LambdaComponents","LambertW","LameC","LameCPrime","LameEigenvalueA","LameEigenvalueB","LameS","LameSPrime","LaminaData","LanczosWindow","LandauDistribution","Language","LanguageCategory","LanguageData","LanguageIdentify","LanguageOptions","LaplaceDistribution","LaplaceTransform","Laplacian","LaplacianFilter","LaplacianGaussianFilter","LaplacianPDETerm","Large","Larger","Last","Latitude","LatitudeLongitude","LatticeData","LatticeReduce","Launch","LaunchKernels","LayeredGraphPlot","LayeredGraphPlot3D","LayerSizeFunction","LayoutInformation","LCHColor","LCM","LeaderSize","LeafCount","LeapVariant","LeapYearQ","LearnDistribution","LearnedDistribution","LearningRate","LearningRateMultipliers","LeastSquares","LeastSquaresFilterKernel","Left","LeftArrow","LeftArrowBar","LeftArrowRightArrow","LeftDownTeeVector","LeftDownVector","LeftDownVectorBar","LeftRightArrow","LeftRightVector","LeftTee","LeftTeeArrow","LeftTeeVector","LeftTriangle","LeftTriangleBar","LeftTriangleEqual","LeftUpDownVector","LeftUpTeeVector","LeftUpVector","LeftUpVectorBar","LeftVector","LeftVectorBar","LegendAppearance","Legended","LegendFunction","LegendLabel","LegendLayout","LegendMargins","LegendMarkers","LegendMarkerSize","LegendreP","LegendreQ","LegendreType","Length","LengthWhile","LerchPhi","Less","LessEqual","LessEqualGreater","LessEqualThan","LessFullEqual","LessGreater","LessLess","LessSlantEqual","LessThan","LessTilde","LetterCharacter","LetterCounts","LetterNumber","LetterQ","Level","LeveneTest","LeviCivitaTensor","LevyDistribution","Lexicographic","LexicographicOrder","LexicographicSort","LibraryDataType","LibraryFunction","LibraryFunctionDeclaration","LibraryFunctionError","LibraryFunctionInformation","LibraryFunctionLoad","LibraryFunctionUnload","LibraryLoad","LibraryUnload","LicenseEntitlementObject","LicenseEntitlements","LicenseID","LicensingSettings","LiftingFilterData","LiftingWaveletTransform","LightBlue","LightBrown","LightCyan","Lighter","LightGray","LightGreen","Lighting","LightingAngle","LightMagenta","LightOrange","LightPink","LightPurple","LightRed","LightSources","LightYellow","Likelihood","Limit","LimitsPositioning","LimitsPositioningTokens","LindleyDistribution","Line","Line3DBox","Line3DBoxOptions","LinearFilter","LinearFractionalOptimization","LinearFractionalTransform","LinearGradientFilling","LinearGradientImage","LinearizingTransformationData","LinearLayer","LinearModelFit","LinearOffsetFunction","LinearOptimization","LinearProgramming","LinearRecurrence","LinearSolve","LinearSolveFunction","LineBox","LineBoxOptions","LineBreak","LinebreakAdjustments","LineBreakChart","LinebreakSemicolonWeighting","LineBreakWithin","LineColor","LineGraph","LineIndent","LineIndentMaxFraction","LineIntegralConvolutionPlot","LineIntegralConvolutionScale","LineLegend","LineOpacity","LineSpacing","LineWrapParts","LinkActivate","LinkClose","LinkConnect","LinkConnectedQ","LinkCreate","LinkError","LinkFlush","LinkFunction","LinkHost","LinkInterrupt","LinkLaunch","LinkMode","LinkObject","LinkOpen","LinkOptions","LinkPatterns","LinkProtocol","LinkRankCentrality","LinkRead","LinkReadHeld","LinkReadyQ","Links","LinkService","LinkWrite","LinkWriteHeld","LiouvilleLambda","List","Listable","ListAnimate","ListContourPlot","ListContourPlot3D","ListConvolve","ListCorrelate","ListCurvePathPlot","ListDeconvolve","ListDensityPlot","ListDensityPlot3D","Listen","ListFormat","ListFourierSequenceTransform","ListInterpolation","ListLineIntegralConvolutionPlot","ListLinePlot","ListLinePlot3D","ListLogLinearPlot","ListLogLogPlot","ListLogPlot","ListPicker","ListPickerBox","ListPickerBoxBackground","ListPickerBoxOptions","ListPlay","ListPlot","ListPlot3D","ListPointPlot3D","ListPolarPlot","ListQ","ListSliceContourPlot3D","ListSliceDensityPlot3D","ListSliceVectorPlot3D","ListStepPlot","ListStreamDensityPlot","ListStreamPlot","ListStreamPlot3D","ListSurfacePlot3D","ListVectorDensityPlot","ListVectorDisplacementPlot","ListVectorDisplacementPlot3D","ListVectorPlot","ListVectorPlot3D","ListZTransform","Literal","LiteralSearch","LiteralType","LoadCompiledComponent","LocalAdaptiveBinarize","LocalCache","LocalClusteringCoefficient","LocalEvaluate","LocalizeDefinitions","LocalizeVariables","LocalObject","LocalObjects","LocalResponseNormalizationLayer","LocalSubmit","LocalSymbol","LocalTime","LocalTimeZone","LocationEquivalenceTest","LocationTest","Locator","LocatorAutoCreate","LocatorBox","LocatorBoxOptions","LocatorCentering","LocatorPane","LocatorPaneBox","LocatorPaneBoxOptions","LocatorRegion","Locked","Log","Log10","Log2","LogBarnesG","LogGamma","LogGammaDistribution","LogicalExpand","LogIntegral","LogisticDistribution","LogisticSigmoid","LogitModelFit","LogLikelihood","LogLinearPlot","LogLogisticDistribution","LogLogPlot","LogMultinormalDistribution","LogNormalDistribution","LogPlot","LogRankTest","LogSeriesDistribution","LongEqual","Longest","LongestCommonSequence","LongestCommonSequencePositions","LongestCommonSubsequence","LongestCommonSubsequencePositions","LongestMatch","LongestOrderedSequence","LongForm","Longitude","LongLeftArrow","LongLeftRightArrow","LongRightArrow","LongShortTermMemoryLayer","Lookup","Loopback","LoopFreeGraphQ","Looping","LossFunction","LowerCaseQ","LowerLeftArrow","LowerRightArrow","LowerTriangularize","LowerTriangularMatrix","LowerTriangularMatrixQ","LowpassFilter","LQEstimatorGains","LQGRegulator","LQOutputRegulatorGains","LQRegulatorGains","LUBackSubstitution","LucasL","LuccioSamiComponents","LUDecomposition","LunarEclipse","LUVColor","LyapunovSolve","LyonsGroupLy","MachineID","MachineName","MachineNumberQ","MachinePrecision","MacintoshSystemPageSetup","Magenta","Magnification","Magnify","MailAddressValidation","MailExecute","MailFolder","MailItem","MailReceiverFunction","MailResponseFunction","MailSearch","MailServerConnect","MailServerConnection","MailSettings","MainSolve","MaintainDynamicCaches","Majority","MakeBoxes","MakeExpression","MakeRules","ManagedLibraryExpressionID","ManagedLibraryExpressionQ","MandelbrotSetBoettcher","MandelbrotSetDistance","MandelbrotSetIterationCount","MandelbrotSetMemberQ","MandelbrotSetPlot","MangoldtLambda","ManhattanDistance","Manipulate","Manipulator","MannedSpaceMissionData","MannWhitneyTest","MantissaExponent","Manual","Map","MapAll","MapApply","MapAt","MapIndexed","MAProcess","MapThread","MarchenkoPasturDistribution","MarcumQ","MardiaCombinedTest","MardiaKurtosisTest","MardiaSkewnessTest","MarginalDistribution","MarkovProcessProperties","Masking","MassConcentrationCondition","MassFluxValue","MassImpermeableBoundaryValue","MassOutflowValue","MassSymmetryValue","MassTransferValue","MassTransportPDEComponent","MatchingDissimilarity","MatchLocalNameQ","MatchLocalNames","MatchQ","Material","MaterialShading","MaternPointProcess","MathematicalFunctionData","MathematicaNotation","MathieuC","MathieuCharacteristicA","MathieuCharacteristicB","MathieuCharacteristicExponent","MathieuCPrime","MathieuGroupM11","MathieuGroupM12","MathieuGroupM22","MathieuGroupM23","MathieuGroupM24","MathieuS","MathieuSPrime","MathMLForm","MathMLText","Matrices","MatrixExp","MatrixForm","MatrixFunction","MatrixLog","MatrixNormalDistribution","MatrixPlot","MatrixPower","MatrixPropertyDistribution","MatrixQ","MatrixRank","MatrixTDistribution","Max","MaxBend","MaxCellMeasure","MaxColorDistance","MaxDate","MaxDetect","MaxDisplayedChildren","MaxDuration","MaxExtraBandwidths","MaxExtraConditions","MaxFeatureDisplacement","MaxFeatures","MaxFilter","MaximalBy","Maximize","MaxItems","MaxIterations","MaxLimit","MaxMemoryUsed","MaxMixtureKernels","MaxOverlapFraction","MaxPlotPoints","MaxPoints","MaxRecursion","MaxStableDistribution","MaxStepFraction","MaxSteps","MaxStepSize","MaxTrainingRounds","MaxValue","MaxwellDistribution","MaxWordGap","McLaughlinGroupMcL","Mean","MeanAbsoluteLossLayer","MeanAround","MeanClusteringCoefficient","MeanDegreeConnectivity","MeanDeviation","MeanFilter","MeanGraphDistance","MeanNeighborDegree","MeanPointDensity","MeanShift","MeanShiftFilter","MeanSquaredLossLayer","Median","MedianDeviation","MedianFilter","MedicalTestData","Medium","MeijerG","MeijerGReduce","MeixnerDistribution","MellinConvolve","MellinTransform","MemberQ","MemoryAvailable","MemoryConstrained","MemoryConstraint","MemoryInUse","MengerMesh","Menu","MenuAppearance","MenuCommandKey","MenuEvaluator","MenuItem","MenuList","MenuPacket","MenuSortingValue","MenuStyle","MenuView","Merge","MergeDifferences","MergingFunction","MersennePrimeExponent","MersennePrimeExponentQ","Mesh","MeshCellCentroid","MeshCellCount","MeshCellHighlight","MeshCellIndex","MeshCellLabel","MeshCellMarker","MeshCellMeasure","MeshCellQuality","MeshCells","MeshCellShapeFunction","MeshCellStyle","MeshConnectivityGraph","MeshCoordinates","MeshFunctions","MeshPrimitives","MeshQualityGoal","MeshRange","MeshRefinementFunction","MeshRegion","MeshRegionQ","MeshShading","MeshStyle","Message","MessageDialog","MessageList","MessageName","MessageObject","MessageOptions","MessagePacket","Messages","MessagesNotebook","MetaCharacters","MetaInformation","MeteorShowerData","Method","MethodOptions","MexicanHatWavelet","MeyerWavelet","Midpoint","MIMETypeToFormatList","Min","MinColorDistance","MinDate","MinDetect","MineralData","MinFilter","MinimalBy","MinimalPolynomial","MinimalStateSpaceModel","Minimize","MinimumTimeIncrement","MinIntervalSize","MinkowskiQuestionMark","MinLimit","MinMax","MinorPlanetData","Minors","MinPointSeparation","MinRecursion","MinSize","MinStableDistribution","Minus","MinusPlus","MinValue","Missing","MissingBehavior","MissingDataMethod","MissingDataRules","MissingQ","MissingString","MissingStyle","MissingValuePattern","MissingValueSynthesis","MittagLefflerE","MixedFractionParts","MixedGraphQ","MixedMagnitude","MixedRadix","MixedRadixQuantity","MixedUnit","MixtureDistribution","Mod","Modal","Mode","ModelPredictiveController","Modular","ModularInverse","ModularLambda","Module","Modulus","MoebiusMu","Molecule","MoleculeAlign","MoleculeContainsQ","MoleculeDraw","MoleculeEquivalentQ","MoleculeFreeQ","MoleculeGraph","MoleculeMatchQ","MoleculeMaximumCommonSubstructure","MoleculeModify","MoleculeName","MoleculePattern","MoleculePlot","MoleculePlot3D","MoleculeProperty","MoleculeQ","MoleculeRecognize","MoleculeSubstructureCount","MoleculeValue","Moment","MomentConvert","MomentEvaluate","MomentGeneratingFunction","MomentOfInertia","Monday","Monitor","MonomialList","MonomialOrder","MonsterGroupM","MoonPhase","MoonPosition","MorletWavelet","MorphologicalBinarize","MorphologicalBranchPoints","MorphologicalComponents","MorphologicalEulerNumber","MorphologicalGraph","MorphologicalPerimeter","MorphologicalTransform","MortalityData","Most","MountainData","MouseAnnotation","MouseAppearance","MouseAppearanceTag","MouseButtons","Mouseover","MousePointerNote","MousePosition","MovieData","MovingAverage","MovingMap","MovingMedian","MoyalDistribution","MultiaxisArrangement","Multicolumn","MultiedgeStyle","MultigraphQ","MultilaunchWarning","MultiLetterItalics","MultiLetterStyle","MultilineFunction","Multinomial","MultinomialDistribution","MultinormalDistribution","MultiplicativeOrder","Multiplicity","MultiplySides","MultiscriptBoxOptions","Multiselection","MultivariateHypergeometricDistribution","MultivariatePoissonDistribution","MultivariateTDistribution","N","NakagamiDistribution","NameQ","Names","NamespaceBox","NamespaceBoxOptions","Nand","NArgMax","NArgMin","NBernoulliB","NBodySimulation","NBodySimulationData","NCache","NCaputoD","NDEigensystem","NDEigenvalues","NDSolve","NDSolveValue","Nearest","NearestFunction","NearestMeshCells","NearestNeighborG","NearestNeighborGraph","NearestTo","NebulaData","NeedlemanWunschSimilarity","Needs","Negative","NegativeBinomialDistribution","NegativeDefiniteMatrixQ","NegativeIntegers","NegativelyOrientedPoints","NegativeMultinomialDistribution","NegativeRationals","NegativeReals","NegativeSemidefiniteMatrixQ","NeighborhoodData","NeighborhoodGraph","Nest","NestedGreaterGreater","NestedLessLess","NestedScriptRules","NestGraph","NestList","NestTree","NestWhile","NestWhileList","NetAppend","NetArray","NetArrayLayer","NetBidirectionalOperator","NetChain","NetDecoder","NetDelete","NetDrop","NetEncoder","NetEvaluationMode","NetExternalObject","NetExtract","NetFlatten","NetFoldOperator","NetGANOperator","NetGraph","NetInformation","NetInitialize","NetInsert","NetInsertSharedArrays","NetJoin","NetMapOperator","NetMapThreadOperator","NetMeasurements","NetModel","NetNestOperator","NetPairEmbeddingOperator","NetPort","NetPortGradient","NetPrepend","NetRename","NetReplace","NetReplacePart","NetSharedArray","NetStateObject","NetTake","NetTrain","NetTrainResultsObject","NetUnfold","NetworkPacketCapture","NetworkPacketRecording","NetworkPacketRecordingDuring","NetworkPacketTrace","NeumannValue","NevilleThetaC","NevilleThetaD","NevilleThetaN","NevilleThetaS","NewPrimitiveStyle","NExpectation","Next","NextCell","NextDate","NextPrime","NextScheduledTaskTime","NeymanScottPointProcess","NFractionalD","NHoldAll","NHoldFirst","NHoldRest","NicholsGridLines","NicholsPlot","NightHemisphere","NIntegrate","NMaximize","NMaxValue","NMinimize","NMinValue","NominalScale","NominalVariables","NonAssociative","NoncentralBetaDistribution","NoncentralChiSquareDistribution","NoncentralFRatioDistribution","NoncentralStudentTDistribution","NonCommutativeMultiply","NonConstants","NondimensionalizationTransform","None","NoneTrue","NonlinearModelFit","NonlinearStateSpaceModel","NonlocalMeansFilter","NonNegative","NonNegativeIntegers","NonNegativeRationals","NonNegativeReals","NonPositive","NonPositiveIntegers","NonPositiveRationals","NonPositiveReals","Nor","NorlundB","Norm","Normal","NormalDistribution","NormalGrouping","NormalizationLayer","Normalize","Normalized","NormalizedSquaredEuclideanDistance","NormalMatrixQ","NormalsFunction","NormFunction","Not","NotCongruent","NotCupCap","NotDoubleVerticalBar","Notebook","NotebookApply","NotebookAutoSave","NotebookBrowseDirectory","NotebookClose","NotebookConvertSettings","NotebookCreate","NotebookDefault","NotebookDelete","NotebookDirectory","NotebookDynamicExpression","NotebookEvaluate","NotebookEventActions","NotebookFileName","NotebookFind","NotebookGet","NotebookImport","NotebookInformation","NotebookInterfaceObject","NotebookLocate","NotebookObject","NotebookOpen","NotebookPath","NotebookPrint","NotebookPut","NotebookRead","Notebooks","NotebookSave","NotebookSelection","NotebooksMenu","NotebookTemplate","NotebookWrite","NotElement","NotEqualTilde","NotExists","NotGreater","NotGreaterEqual","NotGreaterFullEqual","NotGreaterGreater","NotGreaterLess","NotGreaterSlantEqual","NotGreaterTilde","Nothing","NotHumpDownHump","NotHumpEqual","NotificationFunction","NotLeftTriangle","NotLeftTriangleBar","NotLeftTriangleEqual","NotLess","NotLessEqual","NotLessFullEqual","NotLessGreater","NotLessLess","NotLessSlantEqual","NotLessTilde","NotNestedGreaterGreater","NotNestedLessLess","NotPrecedes","NotPrecedesEqual","NotPrecedesSlantEqual","NotPrecedesTilde","NotReverseElement","NotRightTriangle","NotRightTriangleBar","NotRightTriangleEqual","NotSquareSubset","NotSquareSubsetEqual","NotSquareSuperset","NotSquareSupersetEqual","NotSubset","NotSubsetEqual","NotSucceeds","NotSucceedsEqual","NotSucceedsSlantEqual","NotSucceedsTilde","NotSuperset","NotSupersetEqual","NotTilde","NotTildeEqual","NotTildeFullEqual","NotTildeTilde","NotVerticalBar","Now","NoWhitespace","NProbability","NProduct","NProductFactors","NRoots","NSolve","NSolveValues","NSum","NSumTerms","NuclearExplosionData","NuclearReactorData","Null","NullRecords","NullSpace","NullWords","Number","NumberCompose","NumberDecompose","NumberDigit","NumberExpand","NumberFieldClassNumber","NumberFieldDiscriminant","NumberFieldFundamentalUnits","NumberFieldIntegralBasis","NumberFieldNormRepresentatives","NumberFieldRegulator","NumberFieldRootsOfUnity","NumberFieldSignature","NumberForm","NumberFormat","NumberLinePlot","NumberMarks","NumberMultiplier","NumberPadding","NumberPoint","NumberQ","NumberSeparator","NumberSigns","NumberString","Numerator","NumeratorDenominator","NumericalOrder","NumericalSort","NumericArray","NumericArrayQ","NumericArrayType","NumericFunction","NumericQ","NuttallWindow","NValues","NyquistGridLines","NyquistPlot","O","ObjectExistsQ","ObservabilityGramian","ObservabilityMatrix","ObservableDecomposition","ObservableModelQ","OceanData","Octahedron","OddQ","Off","Offset","OLEData","On","ONanGroupON","Once","OneIdentity","Opacity","OpacityFunction","OpacityFunctionScaling","Open","OpenAppend","Opener","OpenerBox","OpenerBoxOptions","OpenerView","OpenFunctionInspectorPacket","Opening","OpenRead","OpenSpecialOptions","OpenTemporary","OpenWrite","Operate","OperatingSystem","OperatorApplied","OptimumFlowData","Optional","OptionalElement","OptionInspectorSettings","OptionQ","Options","OptionsPacket","OptionsPattern","OptionValue","OptionValueBox","OptionValueBoxOptions","Or","Orange","Order","OrderDistribution","OrderedQ","Ordering","OrderingBy","OrderingLayer","Orderless","OrderlessPatternSequence","OrdinalScale","OrnsteinUhlenbeckProcess","Orthogonalize","OrthogonalMatrixQ","Out","Outer","OuterPolygon","OuterPolyhedron","OutputAutoOverwrite","OutputControllabilityMatrix","OutputControllableModelQ","OutputForm","OutputFormData","OutputGrouping","OutputMathEditExpression","OutputNamePacket","OutputPorts","OutputResponse","OutputSizeLimit","OutputStream","Over","OverBar","OverDot","Overflow","OverHat","Overlaps","Overlay","OverlayBox","OverlayBoxOptions","OverlayVideo","Overscript","OverscriptBox","OverscriptBoxOptions","OverTilde","OverVector","OverwriteTarget","OwenT","OwnValues","Package","PackingMethod","PackPaclet","PacletDataRebuild","PacletDirectoryAdd","PacletDirectoryLoad","PacletDirectoryRemove","PacletDirectoryUnload","PacletDisable","PacletEnable","PacletFind","PacletFindRemote","PacletInformation","PacletInstall","PacletInstallSubmit","PacletNewerQ","PacletObject","PacletObjectQ","PacletSite","PacletSiteObject","PacletSiteRegister","PacletSites","PacletSiteUnregister","PacletSiteUpdate","PacletSymbol","PacletUninstall","PacletUpdate","PaddedForm","Padding","PaddingLayer","PaddingSize","PadeApproximant","PadLeft","PadRight","PageBreakAbove","PageBreakBelow","PageBreakWithin","PageFooterLines","PageFooters","PageHeaderLines","PageHeaders","PageHeight","PageRankCentrality","PageTheme","PageWidth","Pagination","PairCorrelationG","PairedBarChart","PairedHistogram","PairedSmoothHistogram","PairedTTest","PairedZTest","PaletteNotebook","PalettePath","PalettesMenuSettings","PalindromeQ","Pane","PaneBox","PaneBoxOptions","Panel","PanelBox","PanelBoxOptions","Paneled","PaneSelector","PaneSelectorBox","PaneSelectorBoxOptions","PaperWidth","ParabolicCylinderD","ParagraphIndent","ParagraphSpacing","ParallelArray","ParallelAxisPlot","ParallelCombine","ParallelDo","Parallelepiped","ParallelEvaluate","Parallelization","Parallelize","ParallelKernels","ParallelMap","ParallelNeeds","Parallelogram","ParallelProduct","ParallelSubmit","ParallelSum","ParallelTable","ParallelTry","Parameter","ParameterEstimator","ParameterMixtureDistribution","ParameterVariables","ParametricConvexOptimization","ParametricFunction","ParametricNDSolve","ParametricNDSolveValue","ParametricPlot","ParametricPlot3D","ParametricRampLayer","ParametricRegion","ParentBox","ParentCell","ParentConnect","ParentDirectory","ParentEdgeLabel","ParentEdgeLabelFunction","ParentEdgeLabelStyle","ParentEdgeShapeFunction","ParentEdgeStyle","ParentEdgeStyleFunction","ParentForm","Parenthesize","ParentList","ParentNotebook","ParetoDistribution","ParetoPickandsDistribution","ParkData","Part","PartBehavior","PartialCorrelationFunction","PartialD","ParticleAcceleratorData","ParticleData","Partition","PartitionGranularity","PartitionsP","PartitionsQ","PartLayer","PartOfSpeech","PartProtection","ParzenWindow","PascalDistribution","PassEventsDown","PassEventsUp","Paste","PasteAutoQuoteCharacters","PasteBoxFormInlineCells","PasteButton","Path","PathGraph","PathGraphQ","Pattern","PatternFilling","PatternReaction","PatternSequence","PatternTest","PauliMatrix","PaulWavelet","Pause","PausedTime","PDF","PeakDetect","PeanoCurve","PearsonChiSquareTest","PearsonCorrelationTest","PearsonDistribution","PenttinenPointProcess","PercentForm","PerfectNumber","PerfectNumberQ","PerformanceGoal","Perimeter","PeriodicBoundaryCondition","PeriodicInterpolation","Periodogram","PeriodogramArray","Permanent","Permissions","PermissionsGroup","PermissionsGroupMemberQ","PermissionsGroups","PermissionsKey","PermissionsKeys","PermutationCycles","PermutationCyclesQ","PermutationGroup","PermutationLength","PermutationList","PermutationListQ","PermutationMatrix","PermutationMax","PermutationMin","PermutationOrder","PermutationPower","PermutationProduct","PermutationReplace","Permutations","PermutationSupport","Permute","PeronaMalikFilter","Perpendicular","PerpendicularBisector","PersistenceLocation","PersistenceTime","PersistentObject","PersistentObjects","PersistentSymbol","PersistentValue","PersonData","PERTDistribution","PetersenGraph","PhaseMargins","PhaseRange","PhongShading","PhysicalSystemData","Pi","Pick","PickedElements","PickMode","PIDData","PIDDerivativeFilter","PIDFeedforward","PIDTune","Piecewise","PiecewiseExpand","PieChart","PieChart3D","PillaiTrace","PillaiTraceTest","PingTime","Pink","PitchRecognize","Pivoting","PixelConstrained","PixelValue","PixelValuePositions","Placed","Placeholder","PlaceholderLayer","PlaceholderReplace","Plain","PlanarAngle","PlanarFaceList","PlanarGraph","PlanarGraphQ","PlanckRadiationLaw","PlaneCurveData","PlanetaryMoonData","PlanetData","PlantData","Play","PlaybackSettings","PlayRange","Plot","Plot3D","Plot3Matrix","PlotDivision","PlotJoined","PlotLabel","PlotLabels","PlotLayout","PlotLegends","PlotMarkers","PlotPoints","PlotRange","PlotRangeClipping","PlotRangeClipPlanesStyle","PlotRangePadding","PlotRegion","PlotStyle","PlotTheme","Pluralize","Plus","PlusMinus","Pochhammer","PodStates","PodWidth","Point","Point3DBox","Point3DBoxOptions","PointBox","PointBoxOptions","PointCountDistribution","PointDensity","PointDensityFunction","PointFigureChart","PointLegend","PointLight","PointProcessEstimator","PointProcessFitTest","PointProcessParameterAssumptions","PointProcessParameterQ","PointSize","PointStatisticFunction","PointValuePlot","PoissonConsulDistribution","PoissonDistribution","PoissonPDEComponent","PoissonPointProcess","PoissonProcess","PoissonWindow","PolarAxes","PolarAxesOrigin","PolarGridLines","PolarPlot","PolarTicks","PoleZeroMarkers","PolyaAeppliDistribution","PolyGamma","Polygon","Polygon3DBox","Polygon3DBoxOptions","PolygonalNumber","PolygonAngle","PolygonBox","PolygonBoxOptions","PolygonCoordinates","PolygonDecomposition","PolygonHoleScale","PolygonIntersections","PolygonScale","Polyhedron","PolyhedronAngle","PolyhedronBox","PolyhedronBoxOptions","PolyhedronCoordinates","PolyhedronData","PolyhedronDecomposition","PolyhedronGenus","PolyLog","PolynomialExpressionQ","PolynomialExtendedGCD","PolynomialForm","PolynomialGCD","PolynomialLCM","PolynomialMod","PolynomialQ","PolynomialQuotient","PolynomialQuotientRemainder","PolynomialReduce","PolynomialRemainder","Polynomials","PolynomialSumOfSquaresList","PoolingLayer","PopupMenu","PopupMenuBox","PopupMenuBoxOptions","PopupView","PopupWindow","Position","PositionIndex","PositionLargest","PositionSmallest","Positive","PositiveDefiniteMatrixQ","PositiveIntegers","PositivelyOrientedPoints","PositiveRationals","PositiveReals","PositiveSemidefiniteMatrixQ","PossibleZeroQ","Postfix","PostScript","Power","PowerDistribution","PowerExpand","PowerMod","PowerModList","PowerRange","PowerSpectralDensity","PowersRepresentations","PowerSymmetricPolynomial","Precedence","PrecedenceForm","Precedes","PrecedesEqual","PrecedesSlantEqual","PrecedesTilde","Precision","PrecisionGoal","PreDecrement","Predict","PredictionRoot","PredictorFunction","PredictorInformation","PredictorMeasurements","PredictorMeasurementsObject","PreemptProtect","PreferencesPath","PreferencesSettings","Prefix","PreIncrement","Prepend","PrependLayer","PrependTo","PreprocessingRules","PreserveColor","PreserveImageOptions","Previous","PreviousCell","PreviousDate","PriceGraphDistribution","PrimaryPlaceholder","Prime","PrimeNu","PrimeOmega","PrimePi","PrimePowerQ","PrimeQ","Primes","PrimeZetaP","PrimitivePolynomialQ","PrimitiveRoot","PrimitiveRootList","PrincipalComponents","PrincipalValue","Print","PrintableASCIIQ","PrintAction","PrintForm","PrintingCopies","PrintingOptions","PrintingPageRange","PrintingStartingPageNumber","PrintingStyleEnvironment","Printout3D","Printout3DPreviewer","PrintPrecision","PrintTemporary","Prism","PrismBox","PrismBoxOptions","PrivateCellOptions","PrivateEvaluationOptions","PrivateFontOptions","PrivateFrontEndOptions","PrivateKey","PrivateNotebookOptions","PrivatePaths","Probability","ProbabilityDistribution","ProbabilityPlot","ProbabilityPr","ProbabilityScalePlot","ProbitModelFit","ProcessConnection","ProcessDirectory","ProcessEnvironment","Processes","ProcessEstimator","ProcessInformation","ProcessObject","ProcessParameterAssumptions","ProcessParameterQ","ProcessStateDomain","ProcessStatus","ProcessTimeDomain","Product","ProductDistribution","ProductLog","ProgressIndicator","ProgressIndicatorBox","ProgressIndicatorBoxOptions","ProgressReporting","Projection","Prolog","PromptForm","ProofObject","PropagateAborts","Properties","Property","PropertyList","PropertyValue","Proportion","Proportional","Protect","Protected","ProteinData","Pruning","PseudoInverse","PsychrometricPropertyData","PublicKey","PublisherID","PulsarData","PunctuationCharacter","Purple","Put","PutAppend","Pyramid","PyramidBox","PyramidBoxOptions","QBinomial","QFactorial","QGamma","QHypergeometricPFQ","QnDispersion","QPochhammer","QPolyGamma","QRDecomposition","QuadraticIrrationalQ","QuadraticOptimization","Quantile","QuantilePlot","Quantity","QuantityArray","QuantityDistribution","QuantityForm","QuantityMagnitude","QuantityQ","QuantityUnit","QuantityVariable","QuantityVariableCanonicalUnit","QuantityVariableDimensions","QuantityVariableIdentifier","QuantityVariablePhysicalQuantity","Quartics","QuartileDeviation","Quartiles","QuartileSkewness","Query","QuestionGenerator","QuestionInterface","QuestionObject","QuestionSelector","QueueingNetworkProcess","QueueingProcess","QueueProperties","Quiet","QuietEcho","Quit","Quotient","QuotientRemainder","RadialAxisPlot","RadialGradientFilling","RadialGradientImage","RadialityCentrality","RadicalBox","RadicalBoxOptions","RadioButton","RadioButtonBar","RadioButtonBox","RadioButtonBoxOptions","Radon","RadonTransform","RamanujanTau","RamanujanTauL","RamanujanTauTheta","RamanujanTauZ","Ramp","Random","RandomArrayLayer","RandomChoice","RandomColor","RandomComplex","RandomDate","RandomEntity","RandomFunction","RandomGeneratorState","RandomGeoPosition","RandomGraph","RandomImage","RandomInstance","RandomInteger","RandomPermutation","RandomPoint","RandomPointConfiguration","RandomPolygon","RandomPolyhedron","RandomPrime","RandomReal","RandomSample","RandomSeed","RandomSeeding","RandomTime","RandomTree","RandomVariate","RandomWalkProcess","RandomWord","Range","RangeFilter","RangeSpecification","RankedMax","RankedMin","RarerProbability","Raster","Raster3D","Raster3DBox","Raster3DBoxOptions","RasterArray","RasterBox","RasterBoxOptions","Rasterize","RasterSize","Rational","RationalExpressionQ","RationalFunctions","Rationalize","Rationals","Ratios","RawArray","RawBoxes","RawData","RawMedium","RayleighDistribution","Re","ReactionBalance","ReactionBalancedQ","ReactionPDETerm","Read","ReadByteArray","ReadLine","ReadList","ReadProtected","ReadString","Real","RealAbs","RealBlockDiagonalForm","RealDigits","RealExponent","Reals","RealSign","Reap","RebuildPacletData","RecalibrationFunction","RecognitionPrior","RecognitionThreshold","ReconstructionMesh","Record","RecordLists","RecordSeparators","Rectangle","RectangleBox","RectangleBoxOptions","RectangleChart","RectangleChart3D","RectangularRepeatingElement","RecurrenceFilter","RecurrenceTable","RecurringDigitsForm","Red","Reduce","RefBox","ReferenceLineStyle","ReferenceMarkers","ReferenceMarkerStyle","Refine","ReflectionMatrix","ReflectionTransform","Refresh","RefreshRate","Region","RegionBinarize","RegionBoundary","RegionBoundaryStyle","RegionBounds","RegionCentroid","RegionCongruent","RegionConvert","RegionDifference","RegionDilation","RegionDimension","RegionDisjoint","RegionDistance","RegionDistanceFunction","RegionEmbeddingDimension","RegionEqual","RegionErosion","RegionFillingStyle","RegionFit","RegionFunction","RegionImage","RegionIntersection","RegionMeasure","RegionMember","RegionMemberFunction","RegionMoment","RegionNearest","RegionNearestFunction","RegionPlot","RegionPlot3D","RegionProduct","RegionQ","RegionResize","RegionSimilar","RegionSize","RegionSymmetricDifference","RegionUnion","RegionWithin","RegisterExternalEvaluator","RegularExpression","Regularization","RegularlySampledQ","RegularPolygon","ReIm","ReImLabels","ReImPlot","ReImStyle","Reinstall","RelationalDatabase","RelationGraph","Release","ReleaseHold","ReliabilityDistribution","ReliefImage","ReliefPlot","RemoteAuthorizationCaching","RemoteBatchJobAbort","RemoteBatchJobObject","RemoteBatchJobs","RemoteBatchMapSubmit","RemoteBatchSubmissionEnvironment","RemoteBatchSubmit","RemoteConnect","RemoteConnectionObject","RemoteEvaluate","RemoteFile","RemoteInputFiles","RemoteKernelObject","RemoteProviderSettings","RemoteRun","RemoteRunProcess","RemovalConditions","Remove","RemoveAlphaChannel","RemoveAsynchronousTask","RemoveAudioStream","RemoveBackground","RemoveChannelListener","RemoveChannelSubscribers","Removed","RemoveDiacritics","RemoveInputStreamMethod","RemoveOutputStreamMethod","RemoveProperty","RemoveScheduledTask","RemoveUsers","RemoveVideoStream","RenameDirectory","RenameFile","RenderAll","RenderingOptions","RenewalProcess","RenkoChart","RepairMesh","Repeated","RepeatedNull","RepeatedString","RepeatedTiming","RepeatingElement","Replace","ReplaceAll","ReplaceAt","ReplaceHeldPart","ReplaceImageValue","ReplaceList","ReplacePart","ReplacePixelValue","ReplaceRepeated","ReplicateLayer","RequiredPhysicalQuantities","Resampling","ResamplingAlgorithmData","ResamplingMethod","Rescale","RescalingTransform","ResetDirectory","ResetScheduledTask","ReshapeLayer","Residue","ResidueSum","ResizeLayer","Resolve","ResolveContextAliases","ResourceAcquire","ResourceData","ResourceFunction","ResourceObject","ResourceRegister","ResourceRemove","ResourceSearch","ResourceSubmissionObject","ResourceSubmit","ResourceSystemBase","ResourceSystemPath","ResourceUpdate","ResourceVersion","ResponseForm","Rest","RestartInterval","Restricted","Resultant","ResumePacket","Return","ReturnCreatesNewCell","ReturnEntersInput","ReturnExpressionPacket","ReturnInputFormPacket","ReturnPacket","ReturnReceiptFunction","ReturnTextPacket","Reverse","ReverseApplied","ReverseBiorthogonalSplineWavelet","ReverseElement","ReverseEquilibrium","ReverseGraph","ReverseSort","ReverseSortBy","ReverseUpEquilibrium","RevolutionAxis","RevolutionPlot3D","RGBColor","RiccatiSolve","RiceDistribution","RidgeFilter","RiemannR","RiemannSiegelTheta","RiemannSiegelZ","RiemannXi","Riffle","Right","RightArrow","RightArrowBar","RightArrowLeftArrow","RightComposition","RightCosetRepresentative","RightDownTeeVector","RightDownVector","RightDownVectorBar","RightTee","RightTeeArrow","RightTeeVector","RightTriangle","RightTriangleBar","RightTriangleEqual","RightUpDownVector","RightUpTeeVector","RightUpVector","RightUpVectorBar","RightVector","RightVectorBar","RipleyK","RipleyRassonRegion","RiskAchievementImportance","RiskReductionImportance","RobustConvexOptimization","RogersTanimotoDissimilarity","RollPitchYawAngles","RollPitchYawMatrix","RomanNumeral","Root","RootApproximant","RootIntervals","RootLocusPlot","RootMeanSquare","RootOfUnityQ","RootReduce","Roots","RootSum","RootTree","Rotate","RotateLabel","RotateLeft","RotateRight","RotationAction","RotationBox","RotationBoxOptions","RotationMatrix","RotationTransform","Round","RoundImplies","RoundingRadius","Row","RowAlignments","RowBackgrounds","RowBox","RowHeights","RowLines","RowMinHeight","RowReduce","RowsEqual","RowSpacings","RSolve","RSolveValue","RudinShapiro","RudvalisGroupRu","Rule","RuleCondition","RuleDelayed","RuleForm","RulePlot","RulerUnits","RulesTree","Run","RunProcess","RunScheduledTask","RunThrough","RuntimeAttributes","RuntimeOptions","RussellRaoDissimilarity","SameAs","SameQ","SameTest","SameTestProperties","SampledEntityClass","SampleDepth","SampledSoundFunction","SampledSoundList","SampleRate","SamplingPeriod","SARIMAProcess","SARMAProcess","SASTriangle","SatelliteData","SatisfiabilityCount","SatisfiabilityInstances","SatisfiableQ","Saturday","Save","Saveable","SaveAutoDelete","SaveConnection","SaveDefinitions","SavitzkyGolayMatrix","SawtoothWave","Scale","Scaled","ScaleDivisions","ScaledMousePosition","ScaleOrigin","ScalePadding","ScaleRanges","ScaleRangeStyle","ScalingFunctions","ScalingMatrix","ScalingTransform","Scan","ScheduledTask","ScheduledTaskActiveQ","ScheduledTaskInformation","ScheduledTaskInformationData","ScheduledTaskObject","ScheduledTasks","SchurDecomposition","ScientificForm","ScientificNotationThreshold","ScorerGi","ScorerGiPrime","ScorerHi","ScorerHiPrime","ScreenRectangle","ScreenStyleEnvironment","ScriptBaselineShifts","ScriptForm","ScriptLevel","ScriptMinSize","ScriptRules","ScriptSizeMultipliers","Scrollbars","ScrollingOptions","ScrollPosition","SearchAdjustment","SearchIndexObject","SearchIndices","SearchQueryString","SearchResultObject","Sec","Sech","SechDistribution","SecondOrderConeOptimization","SectionGrouping","SectorChart","SectorChart3D","SectorOrigin","SectorSpacing","SecuredAuthenticationKey","SecuredAuthenticationKeys","SecurityCertificate","SeedRandom","Select","Selectable","SelectComponents","SelectedCells","SelectedNotebook","SelectFirst","Selection","SelectionAnimate","SelectionCell","SelectionCellCreateCell","SelectionCellDefaultStyle","SelectionCellParentStyle","SelectionCreateCell","SelectionDebuggerTag","SelectionEvaluate","SelectionEvaluateCreateCell","SelectionMove","SelectionPlaceholder","SelectWithContents","SelfLoops","SelfLoopStyle","SemanticImport","SemanticImportString","SemanticInterpretation","SemialgebraicComponentInstances","SemidefiniteOptimization","SendMail","SendMessage","Sequence","SequenceAlignment","SequenceAttentionLayer","SequenceCases","SequenceCount","SequenceFold","SequenceFoldList","SequenceForm","SequenceHold","SequenceIndicesLayer","SequenceLastLayer","SequenceMostLayer","SequencePosition","SequencePredict","SequencePredictorFunction","SequenceReplace","SequenceRestLayer","SequenceReverseLayer","SequenceSplit","Series","SeriesCoefficient","SeriesData","SeriesTermGoal","ServiceConnect","ServiceDisconnect","ServiceExecute","ServiceObject","ServiceRequest","ServiceResponse","ServiceSubmit","SessionSubmit","SessionTime","Set","SetAccuracy","SetAlphaChannel","SetAttributes","Setbacks","SetCloudDirectory","SetCookies","SetDelayed","SetDirectory","SetEnvironment","SetFileDate","SetFileFormatProperties","SetOptions","SetOptionsPacket","SetPermissions","SetPrecision","SetProperty","SetSecuredAuthenticationKey","SetSelectedNotebook","SetSharedFunction","SetSharedVariable","SetStreamPosition","SetSystemModel","SetSystemOptions","Setter","SetterBar","SetterBox","SetterBoxOptions","Setting","SetUsers","Shading","Shallow","ShannonWavelet","ShapiroWilkTest","Share","SharingList","Sharpen","ShearingMatrix","ShearingTransform","ShellRegion","ShenCastanMatrix","ShiftedGompertzDistribution","ShiftRegisterSequence","Short","ShortDownArrow","Shortest","ShortestMatch","ShortestPathFunction","ShortLeftArrow","ShortRightArrow","ShortTimeFourier","ShortTimeFourierData","ShortUpArrow","Show","ShowAutoConvert","ShowAutoSpellCheck","ShowAutoStyles","ShowCellBracket","ShowCellLabel","ShowCellTags","ShowClosedCellArea","ShowCodeAssist","ShowContents","ShowControls","ShowCursorTracker","ShowGroupOpenCloseIcon","ShowGroupOpener","ShowInvisibleCharacters","ShowPageBreaks","ShowPredictiveInterface","ShowSelection","ShowShortBoxForm","ShowSpecialCharacters","ShowStringCharacters","ShowSyntaxStyles","ShrinkingDelay","ShrinkWrapBoundingBox","SiderealTime","SiegelTheta","SiegelTukeyTest","SierpinskiCurve","SierpinskiMesh","Sign","Signature","SignedRankTest","SignedRegionDistance","SignificanceLevel","SignPadding","SignTest","SimilarityRules","SimpleGraph","SimpleGraphQ","SimplePolygonQ","SimplePolyhedronQ","Simplex","Simplify","Sin","Sinc","SinghMaddalaDistribution","SingleEvaluation","SingleLetterItalics","SingleLetterStyle","SingularValueDecomposition","SingularValueList","SingularValuePlot","SingularValues","Sinh","SinhIntegral","SinIntegral","SixJSymbol","Skeleton","SkeletonTransform","SkellamDistribution","Skewness","SkewNormalDistribution","SkinStyle","Skip","SliceContourPlot3D","SliceDensityPlot3D","SliceDistribution","SliceVectorPlot3D","Slider","Slider2D","Slider2DBox","Slider2DBoxOptions","SliderBox","SliderBoxOptions","SlideShowVideo","SlideView","Slot","SlotSequence","Small","SmallCircle","Smaller","SmithDecomposition","SmithDelayCompensator","SmithWatermanSimilarity","SmoothDensityHistogram","SmoothHistogram","SmoothHistogram3D","SmoothKernelDistribution","SmoothPointDensity","SnDispersion","Snippet","SnippetsVideo","SnubPolyhedron","SocialMediaData","Socket","SocketConnect","SocketListen","SocketListener","SocketObject","SocketOpen","SocketReadMessage","SocketReadyQ","Sockets","SocketWaitAll","SocketWaitNext","SoftmaxLayer","SokalSneathDissimilarity","SolarEclipse","SolarSystemFeatureData","SolarTime","SolidAngle","SolidBoundaryLoadValue","SolidData","SolidDisplacementCondition","SolidFixedCondition","SolidMechanicsPDEComponent","SolidMechanicsStrain","SolidMechanicsStress","SolidRegionQ","Solve","SolveAlways","SolveDelayed","SolveValues","Sort","SortBy","SortedBy","SortedEntityClass","Sound","SoundAndGraphics","SoundNote","SoundVolume","SourceLink","SourcePDETerm","Sow","Space","SpaceCurveData","SpaceForm","Spacer","Spacings","Span","SpanAdjustments","SpanCharacterRounding","SpanFromAbove","SpanFromBoth","SpanFromLeft","SpanLineThickness","SpanMaxSize","SpanMinSize","SpanningCharacters","SpanSymmetric","SparseArray","SparseArrayQ","SpatialBinnedPointData","SpatialBoundaryCorrection","SpatialEstimate","SpatialEstimatorFunction","SpatialGraphDistribution","SpatialJ","SpatialMedian","SpatialNoiseLevel","SpatialObservationRegionQ","SpatialPointData","SpatialPointSelect","SpatialRandomnessTest","SpatialTransformationLayer","SpatialTrendFunction","Speak","SpeakerMatchQ","SpearmanRankTest","SpearmanRho","SpeciesData","SpecificityGoal","SpectralLineData","Spectrogram","SpectrogramArray","Specularity","SpeechCases","SpeechInterpreter","SpeechRecognize","SpeechSynthesize","SpellingCorrection","SpellingCorrectionList","SpellingDictionaries","SpellingDictionariesPath","SpellingOptions","Sphere","SphereBox","SphereBoxOptions","SpherePoints","SphericalBesselJ","SphericalBesselY","SphericalHankelH1","SphericalHankelH2","SphericalHarmonicY","SphericalPlot3D","SphericalRegion","SphericalShell","SpheroidalEigenvalue","SpheroidalJoiningFactor","SpheroidalPS","SpheroidalPSPrime","SpheroidalQS","SpheroidalQSPrime","SpheroidalRadialFactor","SpheroidalS1","SpheroidalS1Prime","SpheroidalS2","SpheroidalS2Prime","Splice","SplicedDistribution","SplineClosed","SplineDegree","SplineKnots","SplineWeights","Split","SplitBy","SpokenString","SpotLight","Sqrt","SqrtBox","SqrtBoxOptions","Square","SquaredEuclideanDistance","SquareFreeQ","SquareIntersection","SquareMatrixQ","SquareRepeatingElement","SquaresR","SquareSubset","SquareSubsetEqual","SquareSuperset","SquareSupersetEqual","SquareUnion","SquareWave","SSSTriangle","StabilityMargins","StabilityMarginsStyle","StableDistribution","Stack","StackBegin","StackComplete","StackedDateListPlot","StackedListPlot","StackInhibit","StadiumShape","StandardAtmosphereData","StandardDeviation","StandardDeviationFilter","StandardForm","Standardize","Standardized","StandardOceanData","StandbyDistribution","Star","StarClusterData","StarData","StarGraph","StartAsynchronousTask","StartExternalSession","StartingStepSize","StartOfLine","StartOfString","StartProcess","StartScheduledTask","StartupSound","StartWebSession","StateDimensions","StateFeedbackGains","StateOutputEstimator","StateResponse","StateSpaceModel","StateSpaceRealization","StateSpaceTransform","StateTransformationLinearize","StationaryDistribution","StationaryWaveletPacketTransform","StationaryWaveletTransform","StatusArea","StatusCentrality","StepMonitor","StereochemistryElements","StieltjesGamma","StippleShading","StirlingS1","StirlingS2","StopAsynchronousTask","StoppingPowerData","StopScheduledTask","StrataVariables","StratonovichProcess","StraussHardcorePointProcess","StraussPointProcess","StreamColorFunction","StreamColorFunctionScaling","StreamDensityPlot","StreamMarkers","StreamPlot","StreamPlot3D","StreamPoints","StreamPosition","Streams","StreamScale","StreamStyle","StrictInequalities","String","StringBreak","StringByteCount","StringCases","StringContainsQ","StringCount","StringDelete","StringDrop","StringEndsQ","StringExpression","StringExtract","StringForm","StringFormat","StringFormatQ","StringFreeQ","StringInsert","StringJoin","StringLength","StringMatchQ","StringPadLeft","StringPadRight","StringPart","StringPartition","StringPosition","StringQ","StringRepeat","StringReplace","StringReplaceList","StringReplacePart","StringReverse","StringRiffle","StringRotateLeft","StringRotateRight","StringSkeleton","StringSplit","StringStartsQ","StringTake","StringTakeDrop","StringTemplate","StringToByteArray","StringToStream","StringTrim","StripBoxes","StripOnInput","StripStyleOnPaste","StripWrapperBoxes","StrokeForm","Struckthrough","StructuralImportance","StructuredArray","StructuredArrayHeadQ","StructuredSelection","StruveH","StruveL","Stub","StudentTDistribution","Style","StyleBox","StyleBoxAutoDelete","StyleData","StyleDefinitions","StyleForm","StyleHints","StyleKeyMapping","StyleMenuListing","StyleNameDialogSettings","StyleNames","StylePrint","StyleSheetPath","Subdivide","Subfactorial","Subgraph","SubMinus","SubPlus","SubresultantPolynomialRemainders","SubresultantPolynomials","Subresultants","Subscript","SubscriptBox","SubscriptBoxOptions","Subscripted","Subsequences","Subset","SubsetCases","SubsetCount","SubsetEqual","SubsetMap","SubsetPosition","SubsetQ","SubsetReplace","Subsets","SubStar","SubstitutionSystem","Subsuperscript","SubsuperscriptBox","SubsuperscriptBoxOptions","SubtitleEncoding","SubtitleTrackSelection","Subtract","SubtractFrom","SubtractSides","SubValues","Succeeds","SucceedsEqual","SucceedsSlantEqual","SucceedsTilde","Success","SuchThat","Sum","SumConvergence","SummationLayer","Sunday","SunPosition","Sunrise","Sunset","SuperDagger","SuperMinus","SupernovaData","SuperPlus","Superscript","SuperscriptBox","SuperscriptBoxOptions","Superset","SupersetEqual","SuperStar","Surd","SurdForm","SurfaceAppearance","SurfaceArea","SurfaceColor","SurfaceData","SurfaceGraphics","SurvivalDistribution","SurvivalFunction","SurvivalModel","SurvivalModelFit","SuspendPacket","SuzukiDistribution","SuzukiGroupSuz","SwatchLegend","Switch","Symbol","SymbolName","SymletWavelet","Symmetric","SymmetricDifference","SymmetricGroup","SymmetricKey","SymmetricMatrixQ","SymmetricPolynomial","SymmetricReduction","Symmetrize","SymmetrizedArray","SymmetrizedArrayRules","SymmetrizedDependentComponents","SymmetrizedIndependentComponents","SymmetrizedReplacePart","SynchronousInitialization","SynchronousUpdating","Synonyms","Syntax","SyntaxForm","SyntaxInformation","SyntaxLength","SyntaxPacket","SyntaxQ","SynthesizeMissingValues","SystemCredential","SystemCredentialData","SystemCredentialKey","SystemCredentialKeys","SystemCredentialStoreObject","SystemDialogInput","SystemException","SystemGet","SystemHelpPath","SystemInformation","SystemInformationData","SystemInstall","SystemModel","SystemModeler","SystemModelExamples","SystemModelLinearize","SystemModelMeasurements","SystemModelParametricSimulate","SystemModelPlot","SystemModelProgressReporting","SystemModelReliability","SystemModels","SystemModelSimulate","SystemModelSimulateSensitivity","SystemModelSimulationData","SystemOpen","SystemOptions","SystemProcessData","SystemProcesses","SystemsConnectionsModel","SystemsModelControllerData","SystemsModelDelay","SystemsModelDelayApproximate","SystemsModelDelete","SystemsModelDimensions","SystemsModelExtract","SystemsModelFeedbackConnect","SystemsModelLabels","SystemsModelLinearity","SystemsModelMerge","SystemsModelOrder","SystemsModelParallelConnect","SystemsModelSeriesConnect","SystemsModelStateFeedbackConnect","SystemsModelVectorRelativeOrders","SystemStub","SystemTest","Tab","TabFilling","Table","TableAlignments","TableDepth","TableDirections","TableForm","TableHeadings","TableSpacing","TableView","TableViewBox","TableViewBoxAlignment","TableViewBoxBackground","TableViewBoxHeaders","TableViewBoxItemSize","TableViewBoxItemStyle","TableViewBoxOptions","TabSpacings","TabView","TabViewBox","TabViewBoxOptions","TagBox","TagBoxNote","TagBoxOptions","TaggingRules","TagSet","TagSetDelayed","TagStyle","TagUnset","Take","TakeDrop","TakeLargest","TakeLargestBy","TakeList","TakeSmallest","TakeSmallestBy","TakeWhile","Tally","Tan","Tanh","TargetDevice","TargetFunctions","TargetSystem","TargetUnits","TaskAbort","TaskExecute","TaskObject","TaskRemove","TaskResume","Tasks","TaskSuspend","TaskWait","TautologyQ","TelegraphProcess","TemplateApply","TemplateArgBox","TemplateBox","TemplateBoxOptions","TemplateEvaluate","TemplateExpression","TemplateIf","TemplateObject","TemplateSequence","TemplateSlot","TemplateSlotSequence","TemplateUnevaluated","TemplateVerbatim","TemplateWith","TemporalData","TemporalRegularity","Temporary","TemporaryVariable","TensorContract","TensorDimensions","TensorExpand","TensorProduct","TensorQ","TensorRank","TensorReduce","TensorSymmetry","TensorTranspose","TensorWedge","TerminatedEvaluation","TernaryListPlot","TernaryPlotCorners","TestID","TestReport","TestReportObject","TestResultObject","Tetrahedron","TetrahedronBox","TetrahedronBoxOptions","TeXForm","TeXSave","Text","Text3DBox","Text3DBoxOptions","TextAlignment","TextBand","TextBoundingBox","TextBox","TextCases","TextCell","TextClipboardType","TextContents","TextData","TextElement","TextForm","TextGrid","TextJustification","TextLine","TextPacket","TextParagraph","TextPosition","TextRecognize","TextSearch","TextSearchReport","TextSentences","TextString","TextStructure","TextStyle","TextTranslation","Texture","TextureCoordinateFunction","TextureCoordinateScaling","TextWords","Therefore","ThermodynamicData","ThermometerGauge","Thick","Thickness","Thin","Thinning","ThisLink","ThomasPointProcess","ThompsonGroupTh","Thread","Threaded","ThreadingLayer","ThreeJSymbol","Threshold","Through","Throw","ThueMorse","Thumbnail","Thursday","TickDirection","TickLabelOrientation","TickLabelPositioning","TickLabels","TickLengths","TickPositions","Ticks","TicksStyle","TideData","Tilde","TildeEqual","TildeFullEqual","TildeTilde","TimeConstrained","TimeConstraint","TimeDirection","TimeFormat","TimeGoal","TimelinePlot","TimeObject","TimeObjectQ","TimeRemaining","Times","TimesBy","TimeSeries","TimeSeriesAggregate","TimeSeriesForecast","TimeSeriesInsert","TimeSeriesInvertibility","TimeSeriesMap","TimeSeriesMapThread","TimeSeriesModel","TimeSeriesModelFit","TimeSeriesResample","TimeSeriesRescale","TimeSeriesShift","TimeSeriesThread","TimeSeriesWindow","TimeSystem","TimeSystemConvert","TimeUsed","TimeValue","TimeWarpingCorrespondence","TimeWarpingDistance","TimeZone","TimeZoneConvert","TimeZoneOffset","Timing","Tiny","TitleGrouping","TitsGroupT","ToBoxes","ToCharacterCode","ToColor","ToContinuousTimeModel","ToDate","Today","ToDiscreteTimeModel","ToEntity","ToeplitzMatrix","ToExpression","ToFileName","Together","Toggle","ToggleFalse","Toggler","TogglerBar","TogglerBox","TogglerBoxOptions","ToHeldExpression","ToInvertibleTimeSeries","TokenWords","Tolerance","ToLowerCase","Tomorrow","ToNumberField","TooBig","Tooltip","TooltipBox","TooltipBoxOptions","TooltipDelay","TooltipStyle","ToonShading","Top","TopHatTransform","ToPolarCoordinates","TopologicalSort","ToRadicals","ToRawPointer","ToRules","Torus","TorusGraph","ToSphericalCoordinates","ToString","Total","TotalHeight","TotalLayer","TotalVariationFilter","TotalWidth","TouchPosition","TouchscreenAutoZoom","TouchscreenControlPlacement","ToUpperCase","TourVideo","Tr","Trace","TraceAbove","TraceAction","TraceBackward","TraceDepth","TraceDialog","TraceForward","TraceInternal","TraceLevel","TraceOff","TraceOn","TraceOriginal","TracePrint","TraceScan","TrackCellChangeTimes","TrackedSymbols","TrackingFunction","TracyWidomDistribution","TradingChart","TraditionalForm","TraditionalFunctionNotation","TraditionalNotation","TraditionalOrder","TrainImageContentDetector","TrainingProgressCheckpointing","TrainingProgressFunction","TrainingProgressMeasurements","TrainingProgressReporting","TrainingStoppingCriterion","TrainingUpdateSchedule","TrainTextContentDetector","TransferFunctionCancel","TransferFunctionExpand","TransferFunctionFactor","TransferFunctionModel","TransferFunctionPoles","TransferFunctionTransform","TransferFunctionZeros","TransformationClass","TransformationFunction","TransformationFunctions","TransformationMatrix","TransformedDistribution","TransformedField","TransformedProcess","TransformedRegion","TransitionDirection","TransitionDuration","TransitionEffect","TransitiveClosureGraph","TransitiveReductionGraph","Translate","TranslationOptions","TranslationTransform","Transliterate","Transparent","TransparentColor","Transpose","TransposeLayer","TrapEnterKey","TrapSelection","TravelDirections","TravelDirectionsData","TravelDistance","TravelDistanceList","TravelMethod","TravelTime","Tree","TreeCases","TreeChildren","TreeCount","TreeData","TreeDelete","TreeDepth","TreeElementCoordinates","TreeElementLabel","TreeElementLabelFunction","TreeElementLabelStyle","TreeElementShape","TreeElementShapeFunction","TreeElementSize","TreeElementSizeFunction","TreeElementStyle","TreeElementStyleFunction","TreeExpression","TreeExtract","TreeFold","TreeForm","TreeGraph","TreeGraphQ","TreeInsert","TreeLayout","TreeLeafCount","TreeLeafQ","TreeLeaves","TreeLevel","TreeMap","TreeMapAt","TreeOutline","TreePlot","TreePosition","TreeQ","TreeReplacePart","TreeRules","TreeScan","TreeSelect","TreeSize","TreeTraversalOrder","TrendStyle","Triangle","TriangleCenter","TriangleConstruct","TriangleMeasurement","TriangleWave","TriangularDistribution","TriangulateMesh","Trig","TrigExpand","TrigFactor","TrigFactorList","Trigger","TrigReduce","TrigToExp","TrimmedMean","TrimmedVariance","TropicalStormData","True","TrueQ","TruncatedDistribution","TruncatedPolyhedron","TsallisQExponentialDistribution","TsallisQGaussianDistribution","TTest","Tube","TubeBezierCurveBox","TubeBezierCurveBoxOptions","TubeBox","TubeBoxOptions","TubeBSplineCurveBox","TubeBSplineCurveBoxOptions","Tuesday","TukeyLambdaDistribution","TukeyWindow","TunnelData","Tuples","TuranGraph","TuringMachine","TuttePolynomial","TwoWayRule","Typed","TypeDeclaration","TypeEvaluate","TypeHint","TypeOf","TypeSpecifier","UnateQ","Uncompress","UnconstrainedParameters","Undefined","UnderBar","Underflow","Underlined","Underoverscript","UnderoverscriptBox","UnderoverscriptBoxOptions","Underscript","UnderscriptBox","UnderscriptBoxOptions","UnderseaFeatureData","UndirectedEdge","UndirectedGraph","UndirectedGraphQ","UndoOptions","UndoTrackedVariables","Unequal","UnequalTo","Unevaluated","UniformDistribution","UniformGraphDistribution","UniformPolyhedron","UniformSumDistribution","Uninstall","Union","UnionedEntityClass","UnionPlus","Unique","UniqueElements","UnitaryMatrixQ","UnitBox","UnitConvert","UnitDimensions","Unitize","UnitRootTest","UnitSimplify","UnitStep","UnitSystem","UnitTriangle","UnitVector","UnitVectorLayer","UnityDimensions","UniverseModelData","UniversityData","UnixTime","UnlabeledTree","UnmanageObject","Unprotect","UnregisterExternalEvaluator","UnsameQ","UnsavedVariables","Unset","UnsetShared","Until","UntrackedVariables","Up","UpArrow","UpArrowBar","UpArrowDownArrow","Update","UpdateDynamicObjects","UpdateDynamicObjectsSynchronous","UpdateInterval","UpdatePacletSites","UpdateSearchIndex","UpDownArrow","UpEquilibrium","UpperCaseQ","UpperLeftArrow","UpperRightArrow","UpperTriangularize","UpperTriangularMatrix","UpperTriangularMatrixQ","Upsample","UpSet","UpSetDelayed","UpTee","UpTeeArrow","UpTo","UpValues","URL","URLBuild","URLDecode","URLDispatcher","URLDownload","URLDownloadSubmit","URLEncode","URLExecute","URLExpand","URLFetch","URLFetchAsynchronous","URLParse","URLQueryDecode","URLQueryEncode","URLRead","URLResponseTime","URLSave","URLSaveAsynchronous","URLShorten","URLSubmit","UseEmbeddedLibrary","UseGraphicsRange","UserDefinedWavelet","Using","UsingFrontEnd","UtilityFunction","V2Get","ValenceErrorHandling","ValenceFilling","ValidationLength","ValidationSet","ValueBox","ValueBoxOptions","ValueDimensions","ValueForm","ValuePreprocessingFunction","ValueQ","Values","ValuesData","VandermondeMatrix","Variables","Variance","VarianceEquivalenceTest","VarianceEstimatorFunction","VarianceGammaDistribution","VarianceGammaPointProcess","VarianceTest","VariogramFunction","VariogramModel","VectorAngle","VectorAround","VectorAspectRatio","VectorColorFunction","VectorColorFunctionScaling","VectorDensityPlot","VectorDisplacementPlot","VectorDisplacementPlot3D","VectorGlyphData","VectorGreater","VectorGreaterEqual","VectorLess","VectorLessEqual","VectorMarkers","VectorPlot","VectorPlot3D","VectorPoints","VectorQ","VectorRange","Vectors","VectorScale","VectorScaling","VectorSizes","VectorStyle","Vee","Verbatim","Verbose","VerificationTest","VerifyConvergence","VerifyDerivedKey","VerifyDigitalSignature","VerifyFileSignature","VerifyInterpretation","VerifySecurityCertificates","VerifySolutions","VerifyTestAssumptions","VersionedPreferences","VertexAdd","VertexCapacity","VertexChromaticNumber","VertexColors","VertexComponent","VertexConnectivity","VertexContract","VertexCoordinateRules","VertexCoordinates","VertexCorrelationSimilarity","VertexCosineSimilarity","VertexCount","VertexCoverQ","VertexDataCoordinates","VertexDegree","VertexDelete","VertexDiceSimilarity","VertexEccentricity","VertexInComponent","VertexInComponentGraph","VertexInDegree","VertexIndex","VertexJaccardSimilarity","VertexLabeling","VertexLabels","VertexLabelStyle","VertexList","VertexNormals","VertexOutComponent","VertexOutComponentGraph","VertexOutDegree","VertexQ","VertexRenderingFunction","VertexReplace","VertexShape","VertexShapeFunction","VertexSize","VertexStyle","VertexTextureCoordinates","VertexTransitiveGraphQ","VertexWeight","VertexWeightedGraphQ","Vertical","VerticalBar","VerticalForm","VerticalGauge","VerticalSeparator","VerticalSlider","VerticalTilde","Video","VideoCapture","VideoCombine","VideoDelete","VideoEncoding","VideoExtractFrames","VideoFrameList","VideoFrameMap","VideoGenerator","VideoInsert","VideoIntervals","VideoJoin","VideoMap","VideoMapList","VideoMapTimeSeries","VideoPadding","VideoPause","VideoPlay","VideoQ","VideoRecord","VideoReplace","VideoScreenCapture","VideoSplit","VideoStop","VideoStream","VideoStreams","VideoTimeStretch","VideoTrackSelection","VideoTranscode","VideoTransparency","VideoTrim","ViewAngle","ViewCenter","ViewMatrix","ViewPoint","ViewPointSelectorSettings","ViewPort","ViewProjection","ViewRange","ViewVector","ViewVertical","VirtualGroupData","Visible","VisibleCell","VoiceStyleData","VoigtDistribution","VolcanoData","Volume","VonMisesDistribution","VoronoiMesh","WaitAll","WaitAsynchronousTask","WaitNext","WaitUntil","WakebyDistribution","WalleniusHypergeometricDistribution","WaringYuleDistribution","WarpingCorrespondence","WarpingDistance","WatershedComponents","WatsonUSquareTest","WattsStrogatzGraphDistribution","WaveletBestBasis","WaveletFilterCoefficients","WaveletImagePlot","WaveletListPlot","WaveletMapIndexed","WaveletMatrixPlot","WaveletPhi","WaveletPsi","WaveletScale","WaveletScalogram","WaveletThreshold","WavePDEComponent","WeaklyConnectedComponents","WeaklyConnectedGraphComponents","WeaklyConnectedGraphQ","WeakStationarity","WeatherData","WeatherForecastData","WebAudioSearch","WebColumn","WebElementObject","WeberE","WebExecute","WebImage","WebImageSearch","WebItem","WebPageMetaInformation","WebRow","WebSearch","WebSessionObject","WebSessions","WebWindowObject","Wedge","Wednesday","WeibullDistribution","WeierstrassE1","WeierstrassE2","WeierstrassE3","WeierstrassEta1","WeierstrassEta2","WeierstrassEta3","WeierstrassHalfPeriods","WeierstrassHalfPeriodW1","WeierstrassHalfPeriodW2","WeierstrassHalfPeriodW3","WeierstrassInvariantG2","WeierstrassInvariantG3","WeierstrassInvariants","WeierstrassP","WeierstrassPPrime","WeierstrassSigma","WeierstrassZeta","WeightedAdjacencyGraph","WeightedAdjacencyMatrix","WeightedData","WeightedGraphQ","Weights","WelchWindow","WheelGraph","WhenEvent","Which","While","White","WhiteNoiseProcess","WhitePoint","Whitespace","WhitespaceCharacter","WhittakerM","WhittakerW","WholeCellGroupOpener","WienerFilter","WienerProcess","WignerD","WignerSemicircleDistribution","WikidataData","WikidataSearch","WikipediaData","WikipediaSearch","WilksW","WilksWTest","WindDirectionData","WindingCount","WindingPolygon","WindowClickSelect","WindowElements","WindowFloating","WindowFrame","WindowFrameElements","WindowMargins","WindowMovable","WindowOpacity","WindowPersistentStyles","WindowSelected","WindowSize","WindowStatusArea","WindowTitle","WindowToolbars","WindowWidth","WindSpeedData","WindVectorData","WinsorizedMean","WinsorizedVariance","WishartMatrixDistribution","With","WithCleanup","WithLock","WolframAlpha","WolframAlphaDate","WolframAlphaQuantity","WolframAlphaResult","WolframCloudSettings","WolframLanguageData","Word","WordBoundary","WordCharacter","WordCloud","WordCount","WordCounts","WordData","WordDefinition","WordFrequency","WordFrequencyData","WordList","WordOrientation","WordSearch","WordSelectionFunction","WordSeparators","WordSpacings","WordStem","WordTranslation","WorkingPrecision","WrapAround","Write","WriteLine","WriteString","Wronskian","XMLElement","XMLObject","XMLTemplate","Xnor","Xor","XYZColor","Yellow","Yesterday","YuleDissimilarity","ZernikeR","ZeroSymmetric","ZeroTest","ZeroWidthTimes","Zeta","ZetaZero","ZIPCodeData","ZipfDistribution","ZoomCenter","ZoomFactor","ZTest","ZTransform","$Aborted","$ActivationGroupID","$ActivationKey","$ActivationUserRegistered","$AddOnsDirectory","$AllowDataUpdates","$AllowExternalChannelFunctions","$AllowInternet","$AssertFunction","$Assumptions","$AsynchronousTask","$AudioDecoders","$AudioEncoders","$AudioInputDevices","$AudioOutputDevices","$BaseDirectory","$BasePacletsDirectory","$BatchInput","$BatchOutput","$BlockchainBase","$BoxForms","$ByteOrdering","$CacheBaseDirectory","$Canceled","$ChannelBase","$CharacterEncoding","$CharacterEncodings","$CloudAccountName","$CloudBase","$CloudConnected","$CloudConnection","$CloudCreditsAvailable","$CloudEvaluation","$CloudExpressionBase","$CloudObjectNameFormat","$CloudObjectURLType","$CloudRootDirectory","$CloudSymbolBase","$CloudUserID","$CloudUserUUID","$CloudVersion","$CloudVersionNumber","$CloudWolframEngineVersionNumber","$CommandLine","$CompilationTarget","$CompilerEnvironment","$ConditionHold","$ConfiguredKernels","$Context","$ContextAliases","$ContextPath","$ControlActiveSetting","$Cookies","$CookieStore","$CreationDate","$CryptographicEllipticCurveNames","$CurrentLink","$CurrentTask","$CurrentWebSession","$DataStructures","$DateStringFormat","$DefaultAudioInputDevice","$DefaultAudioOutputDevice","$DefaultFont","$DefaultFrontEnd","$DefaultImagingDevice","$DefaultKernels","$DefaultLocalBase","$DefaultLocalKernel","$DefaultMailbox","$DefaultNetworkInterface","$DefaultPath","$DefaultProxyRules","$DefaultRemoteBatchSubmissionEnvironment","$DefaultRemoteKernel","$DefaultSystemCredentialStore","$Display","$DisplayFunction","$DistributedContexts","$DynamicEvaluation","$Echo","$EmbedCodeEnvironments","$EmbeddableServices","$EntityStores","$Epilog","$EvaluationCloudBase","$EvaluationCloudObject","$EvaluationEnvironment","$ExportFormats","$ExternalIdentifierTypes","$ExternalStorageBase","$Failed","$FinancialDataSource","$FontFamilies","$FormatType","$FrontEnd","$FrontEndSession","$GeneratedAssetLocation","$GeoEntityTypes","$GeoLocation","$GeoLocationCity","$GeoLocationCountry","$GeoLocationPrecision","$GeoLocationSource","$HistoryLength","$HomeDirectory","$HTMLExportRules","$HTTPCookies","$HTTPRequest","$IgnoreEOF","$ImageFormattingWidth","$ImageResolution","$ImagingDevice","$ImagingDevices","$ImportFormats","$IncomingMailSettings","$InitialDirectory","$Initialization","$InitializationContexts","$Input","$InputFileName","$InputStreamMethods","$Inspector","$InstallationDate","$InstallationDirectory","$InterfaceEnvironment","$InterpreterTypes","$IterationLimit","$KernelCount","$KernelID","$Language","$LaunchDirectory","$LibraryPath","$LicenseExpirationDate","$LicenseID","$LicenseProcesses","$LicenseServer","$LicenseSubprocesses","$LicenseType","$Line","$Linked","$LinkSupported","$LoadedFiles","$LocalBase","$LocalSymbolBase","$MachineAddresses","$MachineDomain","$MachineDomains","$MachineEpsilon","$MachineID","$MachineName","$MachinePrecision","$MachineType","$MaxDisplayedChildren","$MaxExtraPrecision","$MaxLicenseProcesses","$MaxLicenseSubprocesses","$MaxMachineNumber","$MaxNumber","$MaxPiecewiseCases","$MaxPrecision","$MaxRootDegree","$MessageGroups","$MessageList","$MessagePrePrint","$Messages","$MinMachineNumber","$MinNumber","$MinorReleaseNumber","$MinPrecision","$MobilePhone","$ModuleNumber","$NetworkConnected","$NetworkInterfaces","$NetworkLicense","$NewMessage","$NewSymbol","$NotebookInlineStorageLimit","$Notebooks","$NoValue","$NumberMarks","$Off","$OperatingSystem","$Output","$OutputForms","$OutputSizeLimit","$OutputStreamMethods","$Packages","$ParentLink","$ParentProcessID","$PasswordFile","$PatchLevelID","$Path","$PathnameSeparator","$PerformanceGoal","$Permissions","$PermissionsGroupBase","$PersistenceBase","$PersistencePath","$PipeSupported","$PlotTheme","$Post","$Pre","$PreferencesDirectory","$PreInitialization","$PrePrint","$PreRead","$PrintForms","$PrintLiteral","$Printout3DPreviewer","$ProcessID","$ProcessorCount","$ProcessorType","$ProductInformation","$ProgramName","$ProgressReporting","$PublisherID","$RandomGeneratorState","$RandomState","$RecursionLimit","$RegisteredDeviceClasses","$RegisteredUserName","$ReleaseNumber","$RequesterAddress","$RequesterCloudUserID","$RequesterCloudUserUUID","$RequesterWolframID","$RequesterWolframUUID","$ResourceSystemBase","$ResourceSystemPath","$RootDirectory","$ScheduledTask","$ScriptCommandLine","$ScriptInputString","$SecuredAuthenticationKeyTokens","$ServiceCreditsAvailable","$Services","$SessionID","$SetParentLink","$SharedFunctions","$SharedVariables","$SoundDisplay","$SoundDisplayFunction","$SourceLink","$SSHAuthentication","$SubtitleDecoders","$SubtitleEncoders","$SummaryBoxDataSizeLimit","$SuppressInputFormHeads","$SynchronousEvaluation","$SyntaxHandler","$System","$SystemCharacterEncoding","$SystemCredentialStore","$SystemID","$SystemMemory","$SystemShell","$SystemTimeZone","$SystemWordLength","$TargetSystems","$TemplatePath","$TemporaryDirectory","$TemporaryPrefix","$TestFileName","$TextStyle","$TimedOut","$TimeUnit","$TimeZone","$TimeZoneEntity","$TopDirectory","$TraceOff","$TraceOn","$TracePattern","$TracePostAction","$TracePreAction","$UnitSystem","$Urgent","$UserAddOnsDirectory","$UserAgentLanguages","$UserAgentMachine","$UserAgentName","$UserAgentOperatingSystem","$UserAgentString","$UserAgentVersion","$UserBaseDirectory","$UserBasePacletsDirectory","$UserDocumentsDirectory","$Username","$UserName","$UserURLBase","$Version","$VersionNumber","$VideoDecoders","$VideoEncoders","$VoiceStyles","$WolframDocumentsDirectory","$WolframID","$WolframUUID"];return Am=function(t){const r=t.regex,n=r.either(r.concat(/([2-9]|[1-2]\d|[3][0-5])\^\^/,/(\w*\.\w+|\w+\.\w*|\w+)/),/(\d*\.\d+|\d+\.\d*|\d+)/),a=r.either(/``[+-]?(\d*\.\d+|\d+\.\d*|\d+)/,/`([+-]?(\d*\.\d+|\d+\.\d*|\d+))?/),i={className:"number",relevance:0,begin:r.concat(n,r.optional(a),r.optional(/\*\^[+-]?\d+/))},o=/[a-zA-Z$][a-zA-Z0-9$]*/,s=new Set(e),l={variants:[{className:"builtin-symbol",begin:o,"on:begin":(e,t)=>{s.has(e[0])||t.ignoreMatch()}},{className:"symbol",relevance:0,begin:o}]},c={className:"message-name",relevance:0,begin:r.concat("::",o)};return{name:"Mathematica",aliases:["mma","wl"],classNameAliases:{brace:"punctuation",pattern:"type",slot:"type",symbol:"variable","named-character":"variable","builtin-symbol":"built_in","message-name":"string"},contains:[t.COMMENT(/\(\*/,/\*\)/,{contains:["self"]}),{className:"pattern",relevance:0,begin:/([a-zA-Z$][a-zA-Z0-9$]*)?_+([a-zA-Z$][a-zA-Z0-9$]*)?/},{className:"slot",relevance:0,begin:/#[a-zA-Z$][a-zA-Z0-9$]*|#+[0-9]?/},c,l,{className:"named-character",begin:/\\\[[$a-zA-Z][$a-zA-Z0-9]+\]/},t.QUOTE_STRING_MODE,i,{className:"operator",relevance:0,begin:/[+\-*/,;.:@~=><&|_`'^?!%]+/},{className:"brace",relevance:0,begin:/[[\](){}]/}]}},Am}()),zf.registerLanguage("matlab",(xm||(xm=1,Im=function(e){const t="('|\\.')+",r={relevance:0,contains:[{begin:t}]};return{name:"Matlab",keywords:{keyword:"arguments break case catch classdef continue else elseif end enumeration events for function global if methods otherwise parfor persistent properties return spmd switch try while",built_in:"sin sind sinh asin asind asinh cos cosd cosh acos acosd acosh tan tand tanh atan atand atan2 atanh sec secd sech asec asecd asech csc cscd csch acsc acscd acsch cot cotd coth acot acotd acoth hypot exp expm1 log log1p log10 log2 pow2 realpow reallog realsqrt sqrt nthroot nextpow2 abs angle complex conj imag real unwrap isreal cplxpair fix floor ceil round mod rem sign airy besselj bessely besselh besseli besselk beta betainc betaln ellipj ellipke erf erfc erfcx erfinv expint gamma gammainc gammaln psi legendre cross dot factor isprime primes gcd lcm rat rats perms nchoosek factorial cart2sph cart2pol pol2cart sph2cart hsv2rgb rgb2hsv zeros ones eye repmat rand randn linspace logspace freqspace meshgrid accumarray size length ndims numel disp isempty isequal isequalwithequalnans cat reshape diag blkdiag tril triu fliplr flipud flipdim rot90 find sub2ind ind2sub bsxfun ndgrid permute ipermute shiftdim circshift squeeze isscalar isvector ans eps realmax realmin pi i|0 inf nan isnan isinf isfinite j|0 why compan gallery hadamard hankel hilb invhilb magic pascal rosser toeplitz vander wilkinson max min nanmax nanmin mean nanmean type table readtable writetable sortrows sort figure plot plot3 scatter scatter3 cellfun legend intersect ismember procrustes hold num2cell "},illegal:'(//|"|#|/\\*|\\s+/\\w+)',contains:[{className:"function",beginKeywords:"function",end:"$",contains:[e.UNDERSCORE_TITLE_MODE,{className:"params",variants:[{begin:"\\(",end:"\\)"},{begin:"\\[",end:"\\]"}]}]},{className:"built_in",begin:/true|false/,relevance:0,starts:r},{begin:"[a-zA-Z][a-zA-Z_0-9]*"+t,relevance:0},{className:"number",begin:e.C_NUMBER_RE,relevance:0,starts:r},{className:"string",begin:"'",end:"'",contains:[{begin:"''"}]},{begin:/\]|\}|\)/,relevance:0,starts:r},{className:"string",begin:'"',end:'"',contains:[{begin:'""'}],starts:r},e.COMMENT("^\\s*%\\{\\s*$","^\\s*%\\}\\s*$"),e.COMMENT("%","$")]}}),Im)),zf.registerLanguage("maxima",(Dm||(Dm=1,wm=function(e){return{name:"Maxima",keywords:{$pattern:"[A-Za-z_%][0-9A-Za-z_%]*",keyword:"if then else elseif for thru do while unless step in and or not",literal:"true false unknown inf minf ind und %e %i %pi %phi %gamma",built_in:" abasep abs absint absolute_real_time acos acosh acot acoth acsc acsch activate addcol add_edge add_edges addmatrices addrow add_vertex add_vertices adjacency_matrix adjoin adjoint af agd airy airy_ai airy_bi airy_dai airy_dbi algsys alg_type alias allroots alphacharp alphanumericp amortization %and annuity_fv annuity_pv antid antidiff AntiDifference append appendfile apply apply1 apply2 applyb1 apropos args arit_amortization arithmetic arithsum array arrayapply arrayinfo arraymake arraysetapply ascii asec asech asin asinh askinteger asksign assoc assoc_legendre_p assoc_legendre_q assume assume_external_byte_order asympa at atan atan2 atanh atensimp atom atvalue augcoefmatrix augmented_lagrangian_method av average_degree backtrace bars barsplot barsplot_description base64 base64_decode bashindices batch batchload bc2 bdvac belln benefit_cost bern bernpoly bernstein_approx bernstein_expand bernstein_poly bessel bessel_i bessel_j bessel_k bessel_simplify bessel_y beta beta_incomplete beta_incomplete_generalized beta_incomplete_regularized bezout bfallroots bffac bf_find_root bf_fmin_cobyla bfhzeta bfloat bfloatp bfpsi bfpsi0 bfzeta biconnected_components bimetric binomial bipartition block blockmatrixp bode_gain bode_phase bothcoef box boxplot boxplot_description break bug_report build_info|10 buildq build_sample burn cabs canform canten cardinality carg cartan cartesian_product catch cauchy_matrix cbffac cdf_bernoulli cdf_beta cdf_binomial cdf_cauchy cdf_chi2 cdf_continuous_uniform cdf_discrete_uniform cdf_exp cdf_f cdf_gamma cdf_general_finite_discrete cdf_geometric cdf_gumbel cdf_hypergeometric cdf_laplace cdf_logistic cdf_lognormal cdf_negative_binomial cdf_noncentral_chi2 cdf_noncentral_student_t cdf_normal cdf_pareto cdf_poisson cdf_rank_sum cdf_rayleigh cdf_signed_rank cdf_student_t cdf_weibull cdisplay ceiling central_moment cequal cequalignore cf cfdisrep cfexpand cgeodesic cgreaterp cgreaterpignore changename changevar chaosgame charat charfun charfun2 charlist charp charpoly chdir chebyshev_t chebyshev_u checkdiv check_overlaps chinese cholesky christof chromatic_index chromatic_number cint circulant_graph clear_edge_weight clear_rules clear_vertex_label clebsch_gordan clebsch_graph clessp clesspignore close closefile cmetric coeff coefmatrix cograd col collapse collectterms columnop columnspace columnswap columnvector combination combine comp2pui compare compfile compile compile_file complement_graph complete_bipartite_graph complete_graph complex_number_p components compose_functions concan concat conjugate conmetderiv connected_components connect_vertices cons constant constantp constituent constvalue cont2part content continuous_freq contortion contour_plot contract contract_edge contragrad contrib_ode convert coord copy copy_file copy_graph copylist copymatrix cor cos cosh cot coth cov cov1 covdiff covect covers crc24sum create_graph create_list csc csch csetup cspline ctaylor ct_coordsys ctransform ctranspose cube_graph cuboctahedron_graph cunlisp cv cycle_digraph cycle_graph cylindrical days360 dblint deactivate declare declare_constvalue declare_dimensions declare_fundamental_dimensions declare_fundamental_units declare_qty declare_translated declare_unit_conversion declare_units declare_weights decsym defcon define define_alt_display define_variable defint defmatch defrule defstruct deftaylor degree_sequence del delete deleten delta demo demoivre denom depends derivdegree derivlist describe desolve determinant dfloat dgauss_a dgauss_b dgeev dgemm dgeqrf dgesv dgesvd diag diagmatrix diag_matrix diagmatrixp diameter diff digitcharp dimacs_export dimacs_import dimension dimensionless dimensions dimensions_as_list direct directory discrete_freq disjoin disjointp disolate disp dispcon dispform dispfun dispJordan display disprule dispterms distrib divide divisors divsum dkummer_m dkummer_u dlange dodecahedron_graph dotproduct dotsimp dpart draw draw2d draw3d drawdf draw_file draw_graph dscalar echelon edge_coloring edge_connectivity edges eigens_by_jacobi eigenvalues eigenvectors eighth einstein eivals eivects elapsed_real_time elapsed_run_time ele2comp ele2polynome ele2pui elem elementp elevation_grid elim elim_allbut eliminate eliminate_using ellipse elliptic_e elliptic_ec elliptic_eu elliptic_f elliptic_kc elliptic_pi ematrix empty_graph emptyp endcons entermatrix entertensor entier equal equalp equiv_classes erf erfc erf_generalized erfi errcatch error errormsg errors euler ev eval_string evenp every evolution evolution2d evundiff example exp expand expandwrt expandwrt_factored expint expintegral_chi expintegral_ci expintegral_e expintegral_e1 expintegral_ei expintegral_e_simplify expintegral_li expintegral_shi expintegral_si explicit explose exponentialize express expt exsec extdiff extract_linear_equations extremal_subset ezgcd %f f90 facsum factcomb factor factorfacsum factorial factorout factorsum facts fast_central_elements fast_linsolve fasttimes featurep fernfale fft fib fibtophi fifth filename_merge file_search file_type fillarray findde find_root find_root_abs find_root_error find_root_rel first fix flatten flength float floatnump floor flower_snark flush flush1deriv flushd flushnd flush_output fmin_cobyla forget fortran fourcos fourexpand fourier fourier_elim fourint fourintcos fourintsin foursimp foursin fourth fposition frame_bracket freeof freshline fresnel_c fresnel_s from_adjacency_matrix frucht_graph full_listify fullmap fullmapl fullratsimp fullratsubst fullsetify funcsolve fundamental_dimensions fundamental_units fundef funmake funp fv g0 g1 gamma gamma_greek gamma_incomplete gamma_incomplete_generalized gamma_incomplete_regularized gauss gauss_a gauss_b gaussprob gcd gcdex gcdivide gcfac gcfactor gd generalized_lambert_w genfact gen_laguerre genmatrix gensym geo_amortization geo_annuity_fv geo_annuity_pv geomap geometric geometric_mean geosum get getcurrentdirectory get_edge_weight getenv get_lu_factors get_output_stream_string get_pixel get_plot_option get_tex_environment get_tex_environment_default get_vertex_label gfactor gfactorsum ggf girth global_variances gn gnuplot_close gnuplot_replot gnuplot_reset gnuplot_restart gnuplot_start go Gosper GosperSum gr2d gr3d gradef gramschmidt graph6_decode graph6_encode graph6_export graph6_import graph_center graph_charpoly graph_eigenvalues graph_flow graph_order graph_periphery graph_product graph_size graph_union great_rhombicosidodecahedron_graph great_rhombicuboctahedron_graph grid_graph grind grobner_basis grotzch_graph hamilton_cycle hamilton_path hankel hankel_1 hankel_2 harmonic harmonic_mean hav heawood_graph hermite hessian hgfred hilbertmap hilbert_matrix hipow histogram histogram_description hodge horner hypergeometric i0 i1 %ibes ic1 ic2 ic_convert ichr1 ichr2 icosahedron_graph icosidodecahedron_graph icurvature ident identfor identity idiff idim idummy ieqn %if ifactors iframes ifs igcdex igeodesic_coords ilt image imagpart imetric implicit implicit_derivative implicit_plot indexed_tensor indices induced_subgraph inferencep inference_result infix info_display init_atensor init_ctensor in_neighbors innerproduct inpart inprod inrt integerp integer_partitions integrate intersect intersection intervalp intopois intosum invariant1 invariant2 inverse_fft inverse_jacobi_cd inverse_jacobi_cn inverse_jacobi_cs inverse_jacobi_dc inverse_jacobi_dn inverse_jacobi_ds inverse_jacobi_nc inverse_jacobi_nd inverse_jacobi_ns inverse_jacobi_sc inverse_jacobi_sd inverse_jacobi_sn invert invert_by_adjoint invert_by_lu inv_mod irr is is_biconnected is_bipartite is_connected is_digraph is_edge_in_graph is_graph is_graph_or_digraph ishow is_isomorphic isolate isomorphism is_planar isqrt isreal_p is_sconnected is_tree is_vertex_in_graph items_inference %j j0 j1 jacobi jacobian jacobi_cd jacobi_cn jacobi_cs jacobi_dc jacobi_dn jacobi_ds jacobi_nc jacobi_nd jacobi_ns jacobi_p jacobi_sc jacobi_sd jacobi_sn JF jn join jordan julia julia_set julia_sin %k kdels kdelta kill killcontext kostka kron_delta kronecker_product kummer_m kummer_u kurtosis kurtosis_bernoulli kurtosis_beta kurtosis_binomial kurtosis_chi2 kurtosis_continuous_uniform kurtosis_discrete_uniform kurtosis_exp kurtosis_f kurtosis_gamma kurtosis_general_finite_discrete kurtosis_geometric kurtosis_gumbel kurtosis_hypergeometric kurtosis_laplace kurtosis_logistic kurtosis_lognormal kurtosis_negative_binomial kurtosis_noncentral_chi2 kurtosis_noncentral_student_t kurtosis_normal kurtosis_pareto kurtosis_poisson kurtosis_rayleigh kurtosis_student_t kurtosis_weibull label labels lagrange laguerre lambda lambert_w laplace laplacian_matrix last lbfgs lc2kdt lcharp lc_l lcm lc_u ldefint ldisp ldisplay legendre_p legendre_q leinstein length let letrules letsimp levi_civita lfreeof lgtreillis lhs li liediff limit Lindstedt linear linearinterpol linear_program linear_regression line_graph linsolve listarray list_correlations listify list_matrix_entries list_nc_monomials listoftens listofvars listp lmax lmin load loadfile local locate_matrix_entry log logcontract log_gamma lopow lorentz_gauge lowercasep lpart lratsubst lreduce lriemann lsquares_estimates lsquares_estimates_approximate lsquares_estimates_exact lsquares_mse lsquares_residual_mse lsquares_residuals lsum ltreillis lu_backsub lucas lu_factor %m macroexpand macroexpand1 make_array makebox makefact makegamma make_graph make_level_picture makelist makeOrders make_poly_continent make_poly_country make_polygon make_random_state make_rgb_picture makeset make_string_input_stream make_string_output_stream make_transform mandelbrot mandelbrot_set map mapatom maplist matchdeclare matchfix mat_cond mat_fullunblocker mat_function mathml_display mat_norm matrix matrixmap matrixp matrix_size mattrace mat_trace mat_unblocker max max_clique max_degree max_flow maximize_lp max_independent_set max_matching maybe md5sum mean mean_bernoulli mean_beta mean_binomial mean_chi2 mean_continuous_uniform mean_deviation mean_discrete_uniform mean_exp mean_f mean_gamma mean_general_finite_discrete mean_geometric mean_gumbel mean_hypergeometric mean_laplace mean_logistic mean_lognormal mean_negative_binomial mean_noncentral_chi2 mean_noncentral_student_t mean_normal mean_pareto mean_poisson mean_rayleigh mean_student_t mean_weibull median median_deviation member mesh metricexpandall mgf1_sha1 min min_degree min_edge_cut minfactorial minimalPoly minimize_lp minimum_spanning_tree minor minpack_lsquares minpack_solve min_vertex_cover min_vertex_cut mkdir mnewton mod mode_declare mode_identity ModeMatrix moebius mon2schur mono monomial_dimensions multibernstein_poly multi_display_for_texinfo multi_elem multinomial multinomial_coeff multi_orbit multiplot_mode multi_pui multsym multthru mycielski_graph nary natural_unit nc_degree ncexpt ncharpoly negative_picture neighbors new newcontext newdet new_graph newline newton new_variable next_prime nicedummies niceindices ninth nofix nonarray noncentral_moment nonmetricity nonnegintegerp nonscalarp nonzeroandfreeof notequal nounify nptetrad npv nroots nterms ntermst nthroot nullity nullspace num numbered_boundaries numberp number_to_octets num_distinct_partitions numerval numfactor num_partitions nusum nzeta nzetai nzetar octets_to_number octets_to_oid odd_girth oddp ode2 ode_check odelin oid_to_octets op opena opena_binary openr openr_binary openw openw_binary operatorp opsubst optimize %or orbit orbits ordergreat ordergreatp orderless orderlessp orthogonal_complement orthopoly_recur orthopoly_weight outermap out_neighbors outofpois pade parabolic_cylinder_d parametric parametric_surface parg parGosper parse_string parse_timedate part part2cont partfrac partition partition_set partpol path_digraph path_graph pathname_directory pathname_name pathname_type pdf_bernoulli pdf_beta pdf_binomial pdf_cauchy pdf_chi2 pdf_continuous_uniform pdf_discrete_uniform pdf_exp pdf_f pdf_gamma pdf_general_finite_discrete pdf_geometric pdf_gumbel pdf_hypergeometric pdf_laplace pdf_logistic pdf_lognormal pdf_negative_binomial pdf_noncentral_chi2 pdf_noncentral_student_t pdf_normal pdf_pareto pdf_poisson pdf_rank_sum pdf_rayleigh pdf_signed_rank pdf_student_t pdf_weibull pearson_skewness permanent permut permutation permutations petersen_graph petrov pickapart picture_equalp picturep piechart piechart_description planar_embedding playback plog plot2d plot3d plotdf ploteq plsquares pochhammer points poisdiff poisexpt poisint poismap poisplus poissimp poissubst poistimes poistrim polar polarform polartorect polar_to_xy poly_add poly_buchberger poly_buchberger_criterion poly_colon_ideal poly_content polydecomp poly_depends_p poly_elimination_ideal poly_exact_divide poly_expand poly_expt poly_gcd polygon poly_grobner poly_grobner_equal poly_grobner_member poly_grobner_subsetp poly_ideal_intersection poly_ideal_polysaturation poly_ideal_polysaturation1 poly_ideal_saturation poly_ideal_saturation1 poly_lcm poly_minimization polymod poly_multiply polynome2ele polynomialp poly_normal_form poly_normalize poly_normalize_list poly_polysaturation_extension poly_primitive_part poly_pseudo_divide poly_reduced_grobner poly_reduction poly_saturation_extension poly_s_polynomial poly_subtract polytocompanion pop postfix potential power_mod powerseries powerset prefix prev_prime primep primes principal_components print printf printfile print_graph printpois printprops prodrac product properties propvars psi psubst ptriangularize pui pui2comp pui2ele pui2polynome pui_direct puireduc push put pv qput qrange qty quad_control quad_qag quad_qagi quad_qagp quad_qags quad_qawc quad_qawf quad_qawo quad_qaws quadrilateral quantile quantile_bernoulli quantile_beta quantile_binomial quantile_cauchy quantile_chi2 quantile_continuous_uniform quantile_discrete_uniform quantile_exp quantile_f quantile_gamma quantile_general_finite_discrete quantile_geometric quantile_gumbel quantile_hypergeometric quantile_laplace quantile_logistic quantile_lognormal quantile_negative_binomial quantile_noncentral_chi2 quantile_noncentral_student_t quantile_normal quantile_pareto quantile_poisson quantile_rayleigh quantile_student_t quantile_weibull quartile_skewness quit qunit quotient racah_v racah_w radcan radius random random_bernoulli random_beta random_binomial random_bipartite_graph random_cauchy random_chi2 random_continuous_uniform random_digraph random_discrete_uniform random_exp random_f random_gamma random_general_finite_discrete random_geometric random_graph random_graph1 random_gumbel random_hypergeometric random_laplace random_logistic random_lognormal random_negative_binomial random_network random_noncentral_chi2 random_noncentral_student_t random_normal random_pareto random_permutation random_poisson random_rayleigh random_regular_graph random_student_t random_tournament random_tree random_weibull range rank rat ratcoef ratdenom ratdiff ratdisrep ratexpand ratinterpol rational rationalize ratnumer ratnump ratp ratsimp ratsubst ratvars ratweight read read_array read_binary_array read_binary_list read_binary_matrix readbyte readchar read_hashed_array readline read_list read_matrix read_nested_list readonly read_xpm real_imagpart_to_conjugate realpart realroots rearray rectangle rectform rectform_log_if_constant recttopolar rediff reduce_consts reduce_order region region_boundaries region_boundaries_plus rem remainder remarray rembox remcomps remcon remcoord remfun remfunction remlet remove remove_constvalue remove_dimensions remove_edge remove_fundamental_dimensions remove_fundamental_units remove_plot_option remove_vertex rempart remrule remsym remvalue rename rename_file reset reset_displays residue resolvante resolvante_alternee1 resolvante_bipartite resolvante_diedrale resolvante_klein resolvante_klein3 resolvante_produit_sym resolvante_unitaire resolvante_vierer rest resultant return reveal reverse revert revert2 rgb2level rhs ricci riemann rinvariant risch rk rmdir rncombine romberg room rootscontract round row rowop rowswap rreduce run_testsuite %s save saving scalarp scaled_bessel_i scaled_bessel_i0 scaled_bessel_i1 scalefactors scanmap scatterplot scatterplot_description scene schur2comp sconcat scopy scsimp scurvature sdowncase sec sech second sequal sequalignore set_alt_display setdifference set_draw_defaults set_edge_weight setelmx setequalp setify setp set_partitions set_plot_option set_prompt set_random_state set_tex_environment set_tex_environment_default setunits setup_autoload set_up_dot_simplifications set_vertex_label seventh sexplode sf sha1sum sha256sum shortest_path shortest_weighted_path show showcomps showratvars sierpinskiale sierpinskimap sign signum similaritytransform simp_inequality simplify_sum simplode simpmetderiv simtran sin sinh sinsert sinvertcase sixth skewness skewness_bernoulli skewness_beta skewness_binomial skewness_chi2 skewness_continuous_uniform skewness_discrete_uniform skewness_exp skewness_f skewness_gamma skewness_general_finite_discrete skewness_geometric skewness_gumbel skewness_hypergeometric skewness_laplace skewness_logistic skewness_lognormal skewness_negative_binomial skewness_noncentral_chi2 skewness_noncentral_student_t skewness_normal skewness_pareto skewness_poisson skewness_rayleigh skewness_student_t skewness_weibull slength smake small_rhombicosidodecahedron_graph small_rhombicuboctahedron_graph smax smin smismatch snowmap snub_cube_graph snub_dodecahedron_graph solve solve_rec solve_rec_rat some somrac sort sparse6_decode sparse6_encode sparse6_export sparse6_import specint spherical spherical_bessel_j spherical_bessel_y spherical_hankel1 spherical_hankel2 spherical_harmonic spherical_to_xyz splice split sposition sprint sqfr sqrt sqrtdenest sremove sremovefirst sreverse ssearch ssort sstatus ssubst ssubstfirst staircase standardize standardize_inverse_trig starplot starplot_description status std std1 std_bernoulli std_beta std_binomial std_chi2 std_continuous_uniform std_discrete_uniform std_exp std_f std_gamma std_general_finite_discrete std_geometric std_gumbel std_hypergeometric std_laplace std_logistic std_lognormal std_negative_binomial std_noncentral_chi2 std_noncentral_student_t std_normal std_pareto std_poisson std_rayleigh std_student_t std_weibull stemplot stirling stirling1 stirling2 strim striml strimr string stringout stringp strong_components struve_h struve_l sublis sublist sublist_indices submatrix subsample subset subsetp subst substinpart subst_parallel substpart substring subvar subvarp sum sumcontract summand_to_rec supcase supcontext symbolp symmdifference symmetricp system take_channel take_inference tan tanh taylor taylorinfo taylorp taylor_simplifier taytorat tcl_output tcontract tellrat tellsimp tellsimpafter tentex tenth test_mean test_means_difference test_normality test_proportion test_proportions_difference test_rank_sum test_sign test_signed_rank test_variance test_variance_ratio tex tex1 tex_display texput %th third throw time timedate timer timer_info tldefint tlimit todd_coxeter toeplitz tokens to_lisp topological_sort to_poly to_poly_solve totaldisrep totalfourier totient tpartpol trace tracematrix trace_options transform_sample translate translate_file transpose treefale tree_reduce treillis treinat triangle triangularize trigexpand trigrat trigreduce trigsimp trunc truncate truncated_cube_graph truncated_dodecahedron_graph truncated_icosahedron_graph truncated_tetrahedron_graph tr_warnings_get tube tutte_graph ueivects uforget ultraspherical underlying_graph undiff union unique uniteigenvectors unitp units unit_step unitvector unorder unsum untellrat untimer untrace uppercasep uricci uriemann uvect vandermonde_matrix var var1 var_bernoulli var_beta var_binomial var_chi2 var_continuous_uniform var_discrete_uniform var_exp var_f var_gamma var_general_finite_discrete var_geometric var_gumbel var_hypergeometric var_laplace var_logistic var_lognormal var_negative_binomial var_noncentral_chi2 var_noncentral_student_t var_normal var_pareto var_poisson var_rayleigh var_student_t var_weibull vector vectorpotential vectorsimp verbify vers vertex_coloring vertex_connectivity vertex_degree vertex_distance vertex_eccentricity vertex_in_degree vertex_out_degree vertices vertices_to_cycle vertices_to_path %w weyl wheel_graph wiener_index wigner_3j wigner_6j wigner_9j with_stdout write_binary_data writebyte write_data writefile wronskian xreduce xthru %y Zeilberger zeroequiv zerofor zeromatrix zeromatrixp zeta zgeev zheev zlange zn_add_table zn_carmichael_lambda zn_characteristic_factors zn_determinant zn_factor_generators zn_invert_by_lu zn_log zn_mult_table absboxchar activecontexts adapt_depth additive adim aform algebraic algepsilon algexact aliases allbut all_dotsimp_denoms allocation allsym alphabetic animation antisymmetric arrays askexp assume_pos assume_pos_pred assumescalar asymbol atomgrad atrig1 axes axis_3d axis_bottom axis_left axis_right axis_top azimuth background background_color backsubst berlefact bernstein_explicit besselexpand beta_args_sum_to_integer beta_expand bftorat bftrunc bindtest border boundaries_array box boxchar breakup %c capping cauchysum cbrange cbtics center cflength cframe_flag cnonmet_flag color color_bar color_bar_tics colorbox columns commutative complex cone context contexts contour contour_levels cosnpiflag ctaypov ctaypt ctayswitch ctayvar ct_coords ctorsion_flag ctrgsimp cube current_let_rule_package cylinder data_file_name debugmode decreasing default_let_rule_package delay dependencies derivabbrev derivsubst detout diagmetric diff dim dimensions dispflag display2d|10 display_format_internal distribute_over doallmxops domain domxexpt domxmxops domxnctimes dontfactor doscmxops doscmxplus dot0nscsimp dot0simp dot1simp dotassoc dotconstrules dotdistrib dotexptsimp dotident dotscrules draw_graph_program draw_realpart edge_color edge_coloring edge_partition edge_type edge_width %edispflag elevation %emode endphi endtheta engineering_format_floats enhanced3d %enumer epsilon_lp erfflag erf_representation errormsg error_size error_syms error_type %e_to_numlog eval even evenfun evflag evfun ev_point expandwrt_denom expintexpand expintrep expon expop exptdispflag exptisolate exptsubst facexpand facsum_combine factlim factorflag factorial_expand factors_only fb feature features file_name file_output_append file_search_demo file_search_lisp file_search_maxima|10 file_search_tests file_search_usage file_type_lisp file_type_maxima|10 fill_color fill_density filled_func fixed_vertices flipflag float2bf font font_size fortindent fortspaces fpprec fpprintprec functions gamma_expand gammalim gdet genindex gensumnum GGFCFMAX GGFINFINITY globalsolve gnuplot_command gnuplot_curve_styles gnuplot_curve_titles gnuplot_default_term_command gnuplot_dumb_term_command gnuplot_file_args gnuplot_file_name gnuplot_out_file gnuplot_pdf_term_command gnuplot_pm3d gnuplot_png_term_command gnuplot_postamble gnuplot_preamble gnuplot_ps_term_command gnuplot_svg_term_command gnuplot_term gnuplot_view_args Gosper_in_Zeilberger gradefs grid grid2d grind halfangles head_angle head_both head_length head_type height hypergeometric_representation %iargs ibase icc1 icc2 icounter idummyx ieqnprint ifb ifc1 ifc2 ifg ifgi ifr iframe_bracket_form ifri igeowedge_flag ikt1 ikt2 imaginary inchar increasing infeval infinity inflag infolists inm inmc1 inmc2 intanalysis integer integervalued integrate_use_rootsof integration_constant integration_constant_counter interpolate_color intfaclim ip_grid ip_grid_in irrational isolate_wrt_times iterations itr julia_parameter %k1 %k2 keepfloat key key_pos kinvariant kt label label_alignment label_orientation labels lassociative lbfgs_ncorrections lbfgs_nfeval_max leftjust legend letrat let_rule_packages lfg lg lhospitallim limsubst linear linear_solver linechar linel|10 linenum line_type linewidth line_width linsolve_params linsolvewarn lispdisp listarith listconstvars listdummyvars lmxchar load_pathname loadprint logabs logarc logcb logconcoeffp logexpand lognegint logsimp logx logx_secondary logy logy_secondary logz lriem m1pbranch macroexpansion macros mainvar manual_demo maperror mapprint matrix_element_add matrix_element_mult matrix_element_transpose maxapplydepth maxapplyheight maxima_tempdir|10 maxima_userdir|10 maxnegex MAX_ORD maxposex maxpsifracdenom maxpsifracnum maxpsinegint maxpsiposint maxtayorder mesh_lines_color method mod_big_prime mode_check_errorp mode_checkp mode_check_warnp mod_test mod_threshold modular_linear_solver modulus multiplicative multiplicities myoptions nary negdistrib negsumdispflag newline newtonepsilon newtonmaxiter nextlayerfactor niceindicespref nm nmc noeval nolabels nonegative_lp noninteger nonscalar noun noundisp nouns np npi nticks ntrig numer numer_pbranch obase odd oddfun opacity opproperties opsubst optimprefix optionset orientation origin orthopoly_returns_intervals outative outchar packagefile palette partswitch pdf_file pfeformat phiresolution %piargs piece pivot_count_sx pivot_max_sx plot_format plot_options plot_realpart png_file pochhammer_max_index points pointsize point_size points_joined point_type poislim poisson poly_coefficient_ring poly_elimination_order polyfactor poly_grobner_algorithm poly_grobner_debug poly_monomial_order poly_primary_elimination_order poly_return_term_list poly_secondary_elimination_order poly_top_reduction_only posfun position powerdisp pred prederror primep_number_of_tests product_use_gamma program programmode promote_float_to_bigfloat prompt proportional_axes props psexpand ps_file radexpand radius radsubstflag rassociative ratalgdenom ratchristof ratdenomdivide rateinstein ratepsilon ratfac rational ratmx ratprint ratriemann ratsimpexpons ratvarswitch ratweights ratweyl ratwtlvl real realonly redraw refcheck resolution restart resultant ric riem rmxchar %rnum_list rombergabs rombergit rombergmin rombergtol rootsconmode rootsepsilon run_viewer same_xy same_xyz savedef savefactors scalar scalarmatrixp scale scale_lp setcheck setcheckbreak setval show_edge_color show_edges show_edge_type show_edge_width show_id show_label showtime show_vertex_color show_vertex_size show_vertex_type show_vertices show_weight simp simplified_output simplify_products simpproduct simpsum sinnpiflag solvedecomposes solveexplicit solvefactors solvenullwarn solveradcan solvetrigwarn space sparse sphere spring_embedding_depth sqrtdispflag stardisp startphi starttheta stats_numer stringdisp structures style sublis_apply_lambda subnumsimp sumexpand sumsplitfact surface surface_hide svg_file symmetric tab taylordepth taylor_logexpand taylor_order_coefficients taylor_truncate_polynomials tensorkill terminal testsuite_files thetaresolution timer_devalue title tlimswitch tr track transcompile transform transform_xy translate_fast_arrays transparent transrun tr_array_as_ref tr_bound_function_applyp tr_file_tty_messagesp tr_float_can_branch_complex tr_function_call_default trigexpandplus trigexpandtimes triginverses trigsign trivial_solutions tr_numer tr_optimize_max_loop tr_semicompile tr_state_vars tr_warn_bad_function_calls tr_warn_fexpr tr_warn_meval tr_warn_mode tr_warn_undeclared tr_warn_undefined_variable tstep ttyoff tube_extremes ufg ug %unitexpand unit_vectors uric uriem use_fast_arrays user_preamble usersetunits values vect_cross verbose vertex_color vertex_coloring vertex_partition vertex_size vertex_type view warnings weyl width windowname windowtitle wired_surface wireframe xaxis xaxis_color xaxis_secondary xaxis_type xaxis_width xlabel xlabel_secondary xlength xrange xrange_secondary xtics xtics_axis xtics_rotate xtics_rotate_secondary xtics_secondary xtics_secondary_axis xu_grid x_voxel xy_file xyplane xy_scale yaxis yaxis_color yaxis_secondary yaxis_type yaxis_width ylabel ylabel_secondary ylength yrange yrange_secondary ytics ytics_axis ytics_rotate ytics_rotate_secondary ytics_secondary ytics_secondary_axis yv_grid y_voxel yx_ratio zaxis zaxis_color zaxis_type zaxis_width zeroa zerob zerobern zeta%pi zlabel zlabel_rotate zlength zmin zn_primroot_limit zn_primroot_pretest",symbol:"_ __ %|0 %%|0"},contains:[{className:"comment",begin:"/\\*",end:"\\*/",contains:["self"]},e.QUOTE_STRING_MODE,{className:"number",relevance:0,variants:[{begin:"\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Ee][-+]?\\d+\\b"},{begin:"\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Bb][-+]?\\d+\\b",relevance:10},{begin:"\\b(\\.\\d+|\\d+\\.\\d+)\\b"},{begin:"\\b(\\d+|0[0-9A-Za-z]+)\\.?\\b"}]}],illegal:/@/}}),wm)),zf.registerLanguage("mel",(km||(km=1,Mm=function(e){return{name:"MEL",keywords:"int float string vector matrix if else switch case default while do for in break continue global proc return about abs addAttr addAttributeEditorNodeHelp addDynamic addNewShelfTab addPP addPanelCategory addPrefixToName advanceToNextDrivenKey affectedNet affects aimConstraint air alias aliasAttr align alignCtx alignCurve alignSurface allViewFit ambientLight angle angleBetween animCone animCurveEditor animDisplay animView annotate appendStringArray applicationName applyAttrPreset applyTake arcLenDimContext arcLengthDimension arclen arrayMapper art3dPaintCtx artAttrCtx artAttrPaintVertexCtx artAttrSkinPaintCtx artAttrTool artBuildPaintMenu artFluidAttrCtx artPuttyCtx artSelectCtx artSetPaintCtx artUserPaintCtx assignCommand assignInputDevice assignViewportFactories attachCurve attachDeviceAttr attachSurface attrColorSliderGrp attrCompatibility attrControlGrp attrEnumOptionMenu attrEnumOptionMenuGrp attrFieldGrp attrFieldSliderGrp attrNavigationControlGrp attrPresetEditWin attributeExists attributeInfo attributeMenu attributeQuery autoKeyframe autoPlace bakeClip bakeFluidShading bakePartialHistory bakeResults bakeSimulation basename basenameEx batchRender bessel bevel bevelPlus binMembership bindSkin blend2 blendShape blendShapeEditor blendShapePanel blendTwoAttr blindDataType boneLattice boundary boxDollyCtx boxZoomCtx bufferCurve buildBookmarkMenu buildKeyframeMenu button buttonManip CBG cacheFile cacheFileCombine cacheFileMerge cacheFileTrack camera cameraView canCreateManip canvas capitalizeString catch catchQuiet ceil changeSubdivComponentDisplayLevel changeSubdivRegion channelBox character characterMap characterOutlineEditor characterize chdir checkBox checkBoxGrp checkDefaultRenderGlobals choice circle circularFillet clamp clear clearCache clip clipEditor clipEditorCurrentTimeCtx clipSchedule clipSchedulerOutliner clipTrimBefore closeCurve closeSurface cluster cmdFileOutput cmdScrollFieldExecuter cmdScrollFieldReporter cmdShell coarsenSubdivSelectionList collision color colorAtPoint colorEditor colorIndex colorIndexSliderGrp colorSliderButtonGrp colorSliderGrp columnLayout commandEcho commandLine commandPort compactHairSystem componentEditor compositingInterop computePolysetVolume condition cone confirmDialog connectAttr connectControl connectDynamic connectJoint connectionInfo constrain constrainValue constructionHistory container containsMultibyte contextInfo control convertFromOldLayers convertIffToPsd convertLightmap convertSolidTx convertTessellation convertUnit copyArray copyFlexor copyKey copySkinWeights cos cpButton cpCache cpClothSet cpCollision cpConstraint cpConvClothToMesh cpForces cpGetSolverAttr cpPanel cpProperty cpRigidCollisionFilter cpSeam cpSetEdit cpSetSolverAttr cpSolver cpSolverTypes cpTool cpUpdateClothUVs createDisplayLayer createDrawCtx createEditor createLayeredPsdFile createMotionField createNewShelf createNode createRenderLayer createSubdivRegion cross crossProduct ctxAbort ctxCompletion ctxEditMode ctxTraverse currentCtx currentTime currentTimeCtx currentUnit curve curveAddPtCtx curveCVCtx curveEPCtx curveEditorCtx curveIntersect curveMoveEPCtx curveOnSurface curveSketchCtx cutKey cycleCheck cylinder dagPose date defaultLightListCheckBox defaultNavigation defineDataServer defineVirtualDevice deformer deg_to_rad delete deleteAttr deleteShadingGroupsAndMaterials deleteShelfTab deleteUI deleteUnusedBrushes delrandstr detachCurve detachDeviceAttr detachSurface deviceEditor devicePanel dgInfo dgdirty dgeval dgtimer dimWhen directKeyCtx directionalLight dirmap dirname disable disconnectAttr disconnectJoint diskCache displacementToPoly displayAffected displayColor displayCull displayLevelOfDetail displayPref displayRGBColor displaySmoothness displayStats displayString displaySurface distanceDimContext distanceDimension doBlur dolly dollyCtx dopeSheetEditor dot dotProduct doubleProfileBirailSurface drag dragAttrContext draggerContext dropoffLocator duplicate duplicateCurve duplicateSurface dynCache dynControl dynExport dynExpression dynGlobals dynPaintEditor dynParticleCtx dynPref dynRelEdPanel dynRelEditor dynamicLoad editAttrLimits editDisplayLayerGlobals editDisplayLayerMembers editRenderLayerAdjustment editRenderLayerGlobals editRenderLayerMembers editor editorTemplate effector emit emitter enableDevice encodeString endString endsWith env equivalent equivalentTol erf error eval evalDeferred evalEcho event exactWorldBoundingBox exclusiveLightCheckBox exec executeForEachObject exists exp expression expressionEditorListen extendCurve extendSurface extrude fcheck fclose feof fflush fgetline fgetword file fileBrowserDialog fileDialog fileExtension fileInfo filetest filletCurve filter filterCurve filterExpand filterStudioImport findAllIntersections findAnimCurves findKeyframe findMenuItem findRelatedSkinCluster finder firstParentOf fitBspline flexor floatEq floatField floatFieldGrp floatScrollBar floatSlider floatSlider2 floatSliderButtonGrp floatSliderGrp floor flow fluidCacheInfo fluidEmitter fluidVoxelInfo flushUndo fmod fontDialog fopen formLayout format fprint frameLayout fread freeFormFillet frewind fromNativePath fwrite gamma gauss geometryConstraint getApplicationVersionAsFloat getAttr getClassification getDefaultBrush getFileList getFluidAttr getInputDeviceRange getMayaPanelTypes getModifiers getPanel getParticleAttr getPluginResource getenv getpid glRender glRenderEditor globalStitch gmatch goal gotoBindPose grabColor gradientControl gradientControlNoAttr graphDollyCtx graphSelectContext graphTrackCtx gravity grid gridLayout group groupObjectsByName HfAddAttractorToAS HfAssignAS HfBuildEqualMap HfBuildFurFiles HfBuildFurImages HfCancelAFR HfConnectASToHF HfCreateAttractor HfDeleteAS HfEditAS HfPerformCreateAS HfRemoveAttractorFromAS HfSelectAttached HfSelectAttractors HfUnAssignAS hardenPointCurve hardware hardwareRenderPanel headsUpDisplay headsUpMessage help helpLine hermite hide hilite hitTest hotBox hotkey hotkeyCheck hsv_to_rgb hudButton hudSlider hudSliderButton hwReflectionMap hwRender hwRenderLoad hyperGraph hyperPanel hyperShade hypot iconTextButton iconTextCheckBox iconTextRadioButton iconTextRadioCollection iconTextScrollList iconTextStaticLabel ikHandle ikHandleCtx ikHandleDisplayScale ikSolver ikSplineHandleCtx ikSystem ikSystemInfo ikfkDisplayMethod illustratorCurves image imfPlugins inheritTransform insertJoint insertJointCtx insertKeyCtx insertKnotCurve insertKnotSurface instance instanceable instancer intField intFieldGrp intScrollBar intSlider intSliderGrp interToUI internalVar intersect iprEngine isAnimCurve isConnected isDirty isParentOf isSameObject isTrue isValidObjectName isValidString isValidUiName isolateSelect itemFilter itemFilterAttr itemFilterRender itemFilterType joint jointCluster jointCtx jointDisplayScale jointLattice keyTangent keyframe keyframeOutliner keyframeRegionCurrentTimeCtx keyframeRegionDirectKeyCtx keyframeRegionDollyCtx keyframeRegionInsertKeyCtx keyframeRegionMoveKeyCtx keyframeRegionScaleKeyCtx keyframeRegionSelectKeyCtx keyframeRegionSetKeyCtx keyframeRegionTrackCtx keyframeStats lassoContext lattice latticeDeformKeyCtx launch launchImageEditor layerButton layeredShaderPort layeredTexturePort layout layoutDialog lightList lightListEditor lightListPanel lightlink lineIntersection linearPrecision linstep listAnimatable listAttr listCameras listConnections listDeviceAttachments listHistory listInputDeviceAxes listInputDeviceButtons listInputDevices listMenuAnnotation listNodeTypes listPanelCategories listRelatives listSets listTransforms listUnselected listerEditor loadFluid loadNewShelf loadPlugin loadPluginLanguageResources loadPrefObjects localizedPanelLabel lockNode loft log longNameOf lookThru ls lsThroughFilter lsType lsUI Mayatomr mag makeIdentity makeLive makePaintable makeRoll makeSingleSurface makeTubeOn makebot manipMoveContext manipMoveLimitsCtx manipOptions manipRotateContext manipRotateLimitsCtx manipScaleContext manipScaleLimitsCtx marker match max memory menu menuBarLayout menuEditor menuItem menuItemToShelf menuSet menuSetPref messageLine min minimizeApp mirrorJoint modelCurrentTimeCtx modelEditor modelPanel mouse movIn movOut move moveIKtoFK moveKeyCtx moveVertexAlongDirection multiProfileBirailSurface mute nParticle nameCommand nameField namespace namespaceInfo newPanelItems newton nodeCast nodeIconButton nodeOutliner nodePreset nodeType noise nonLinear normalConstraint normalize nurbsBoolean nurbsCopyUVSet nurbsCube nurbsEditUV nurbsPlane nurbsSelect nurbsSquare nurbsToPoly nurbsToPolygonsPref nurbsToSubdiv nurbsToSubdivPref nurbsUVSet nurbsViewDirectionVector objExists objectCenter objectLayer objectType objectTypeUI obsoleteProc oceanNurbsPreviewPlane offsetCurve offsetCurveOnSurface offsetSurface openGLExtension openMayaPref optionMenu optionMenuGrp optionVar orbit orbitCtx orientConstraint outlinerEditor outlinerPanel overrideModifier paintEffectsDisplay pairBlend palettePort paneLayout panel panelConfiguration panelHistory paramDimContext paramDimension paramLocator parent parentConstraint particle particleExists particleInstancer particleRenderInfo partition pasteKey pathAnimation pause pclose percent performanceOptions pfxstrokes pickWalk picture pixelMove planarSrf plane play playbackOptions playblast plugAttr plugNode pluginInfo pluginResourceUtil pointConstraint pointCurveConstraint pointLight pointMatrixMult pointOnCurve pointOnSurface pointPosition poleVectorConstraint polyAppend polyAppendFacetCtx polyAppendVertex polyAutoProjection polyAverageNormal polyAverageVertex polyBevel polyBlendColor polyBlindData polyBoolOp polyBridgeEdge polyCacheMonitor polyCheck polyChipOff polyClipboard polyCloseBorder polyCollapseEdge polyCollapseFacet polyColorBlindData polyColorDel polyColorPerVertex polyColorSet polyCompare polyCone polyCopyUV polyCrease polyCreaseCtx polyCreateFacet polyCreateFacetCtx polyCube polyCut polyCutCtx polyCylinder polyCylindricalProjection polyDelEdge polyDelFacet polyDelVertex polyDuplicateAndConnect polyDuplicateEdge polyEditUV polyEditUVShell polyEvaluate polyExtrudeEdge polyExtrudeFacet polyExtrudeVertex polyFlipEdge polyFlipUV polyForceUV polyGeoSampler polyHelix polyInfo polyInstallAction polyLayoutUV polyListComponentConversion polyMapCut polyMapDel polyMapSew polyMapSewMove polyMergeEdge polyMergeEdgeCtx polyMergeFacet polyMergeFacetCtx polyMergeUV polyMergeVertex polyMirrorFace polyMoveEdge polyMoveFacet polyMoveFacetUV polyMoveUV polyMoveVertex polyNormal polyNormalPerVertex polyNormalizeUV polyOptUvs polyOptions polyOutput polyPipe polyPlanarProjection polyPlane polyPlatonicSolid polyPoke polyPrimitive polyPrism polyProjection polyPyramid polyQuad polyQueryBlindData polyReduce polySelect polySelectConstraint polySelectConstraintMonitor polySelectCtx polySelectEditCtx polySeparate polySetToFaceNormal polySewEdge polyShortestPathCtx polySmooth polySoftEdge polySphere polySphericalProjection polySplit polySplitCtx polySplitEdge polySplitRing polySplitVertex polyStraightenUVBorder polySubdivideEdge polySubdivideFacet polyToSubdiv polyTorus polyTransfer polyTriangulate polyUVSet polyUnite polyWedgeFace popen popupMenu pose pow preloadRefEd print progressBar progressWindow projFileViewer projectCurve projectTangent projectionContext projectionManip promptDialog propModCtx propMove psdChannelOutliner psdEditTextureFile psdExport psdTextureFile putenv pwd python querySubdiv quit rad_to_deg radial radioButton radioButtonGrp radioCollection radioMenuItemCollection rampColorPort rand randomizeFollicles randstate rangeControl readTake rebuildCurve rebuildSurface recordAttr recordDevice redo reference referenceEdit referenceQuery refineSubdivSelectionList refresh refreshAE registerPluginResource rehash reloadImage removeJoint removeMultiInstance removePanelCategory rename renameAttr renameSelectionList renameUI render renderGlobalsNode renderInfo renderLayerButton renderLayerParent renderLayerPostProcess renderLayerUnparent renderManip renderPartition renderQualityNode renderSettings renderThumbnailUpdate renderWindowEditor renderWindowSelectContext renderer reorder reorderDeformers requires reroot resampleFluid resetAE resetPfxToPolyCamera resetTool resolutionNode retarget reverseCurve reverseSurface revolve rgb_to_hsv rigidBody rigidSolver roll rollCtx rootOf rot rotate rotationInterpolation roundConstantRadius rowColumnLayout rowLayout runTimeCommand runup sampleImage saveAllShelves saveAttrPreset saveFluid saveImage saveInitialState saveMenu savePrefObjects savePrefs saveShelf saveToolSettings scale scaleBrushBrightness scaleComponents scaleConstraint scaleKey scaleKeyCtx sceneEditor sceneUIReplacement scmh scriptCtx scriptEditorInfo scriptJob scriptNode scriptTable scriptToShelf scriptedPanel scriptedPanelType scrollField scrollLayout sculpt searchPathArray seed selLoadSettings select selectContext selectCurveCV selectKey selectKeyCtx selectKeyframeRegionCtx selectMode selectPref selectPriority selectType selectedNodes selectionConnection separator setAttr setAttrEnumResource setAttrMapping setAttrNiceNameResource setConstraintRestPosition setDefaultShadingGroup setDrivenKeyframe setDynamic setEditCtx setEditor setFluidAttr setFocus setInfinity setInputDeviceMapping setKeyCtx setKeyPath setKeyframe setKeyframeBlendshapeTargetWts setMenuMode setNodeNiceNameResource setNodeTypeFlag setParent setParticleAttr setPfxToPolyCamera setPluginResource setProject setStampDensity setStartupMessage setState setToolTo setUITemplate setXformManip sets shadingConnection shadingGeometryRelCtx shadingLightRelCtx shadingNetworkCompare shadingNode shapeCompare shelfButton shelfLayout shelfTabLayout shellField shortNameOf showHelp showHidden showManipCtx showSelectionInTitle showShadingGroupAttrEditor showWindow sign simplify sin singleProfileBirailSurface size sizeBytes skinCluster skinPercent smoothCurve smoothTangentSurface smoothstep snap2to2 snapKey snapMode snapTogetherCtx snapshot soft softMod softModCtx sort sound soundControl source spaceLocator sphere sphrand spotLight spotLightPreviewPort spreadSheetEditor spring sqrt squareSurface srtContext stackTrace startString startsWith stitchAndExplodeShell stitchSurface stitchSurfacePoints strcmp stringArrayCatenate stringArrayContains stringArrayCount stringArrayInsertAtIndex stringArrayIntersector stringArrayRemove stringArrayRemoveAtIndex stringArrayRemoveDuplicates stringArrayRemoveExact stringArrayToString stringToStringArray strip stripPrefixFromName stroke subdAutoProjection subdCleanTopology subdCollapse subdDuplicateAndConnect subdEditUV subdListComponentConversion subdMapCut subdMapSewMove subdMatchTopology subdMirror subdToBlind subdToPoly subdTransferUVsToCache subdiv subdivCrease subdivDisplaySmoothness substitute substituteAllString substituteGeometry substring surface surfaceSampler surfaceShaderList swatchDisplayPort switchTable symbolButton symbolCheckBox sysFile system tabLayout tan tangentConstraint texLatticeDeformContext texManipContext texMoveContext texMoveUVShellContext texRotateContext texScaleContext texSelectContext texSelectShortestPathCtx texSmudgeUVContext texWinToolCtx text textCurves textField textFieldButtonGrp textFieldGrp textManip textScrollList textToShelf textureDisplacePlane textureHairColor texturePlacementContext textureWindow threadCount threePointArcCtx timeControl timePort timerX toNativePath toggle toggleAxis toggleWindowVisibility tokenize tokenizeList tolerance tolower toolButton toolCollection toolDropped toolHasOptions toolPropertyWindow torus toupper trace track trackCtx transferAttributes transformCompare transformLimits translator trim trunc truncateFluidCache truncateHairCache tumble tumbleCtx turbulence twoPointArcCtx uiRes uiTemplate unassignInputDevice undo undoInfo ungroup uniform unit unloadPlugin untangleUV untitledFileName untrim upAxis updateAE userCtx uvLink uvSnapshot validateShelfName vectorize view2dToolCtx viewCamera viewClipPlane viewFit viewHeadOn viewLookAt viewManip viewPlace viewSet visor volumeAxis vortex waitCursor warning webBrowser webBrowserPrefs whatIs window windowPref wire wireContext workspace wrinkle wrinkleContext writeTake xbmLangPathList xform",illegal:"</",contains:[e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:/[$%@](\^\w\b|#\w+|[^\s\w{]|\{\w+\}|\w+)/},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]}}),Mm)),zf.registerLanguage("mercury",(Pm||(Pm=1,Lm=function(e){const t=e.COMMENT("%","$"),r=e.inherit(e.APOS_STRING_MODE,{relevance:0}),n=e.inherit(e.QUOTE_STRING_MODE,{relevance:0});return n.contains=n.contains.slice(),n.contains.push({className:"subst",begin:"\\\\[abfnrtv]\\|\\\\x[0-9a-fA-F]*\\\\\\|%[-+# *.0-9]*[dioxXucsfeEgGp]",relevance:0}),{name:"Mercury",aliases:["m","moo"],keywords:{keyword:"module use_module import_module include_module end_module initialise mutable initialize finalize finalise interface implementation pred mode func type inst solver any_pred any_func is semidet det nondet multi erroneous failure cc_nondet cc_multi typeclass instance where pragma promise external trace atomic or_else require_complete_switch require_det require_semidet require_multi require_nondet require_cc_multi require_cc_nondet require_erroneous require_failure",meta:"inline no_inline type_spec source_file fact_table obsolete memo loop_check minimal_model terminates does_not_terminate check_termination promise_equivalent_clauses foreign_proc foreign_decl foreign_code foreign_type foreign_import_module foreign_export_enum foreign_export foreign_enum may_call_mercury will_not_call_mercury thread_safe not_thread_safe maybe_thread_safe promise_pure promise_semipure tabled_for_io local untrailed trailed attach_to_io_state can_pass_as_mercury_type stable will_not_throw_exception may_modify_trail will_not_modify_trail may_duplicate may_not_duplicate affects_liveness does_not_affect_liveness doesnt_affect_liveness no_sharing unknown_sharing sharing",built_in:"some all not if then else true fail false try catch catch_any semidet_true semidet_false semidet_fail impure_true impure semipure"},contains:[{className:"built_in",variants:[{begin:"<=>"},{begin:"<=",relevance:0},{begin:"=>",relevance:0},{begin:"/\\\\"},{begin:"\\\\/"}]},{className:"built_in",variants:[{begin:":-\\|--\x3e"},{begin:"=",relevance:0}]},t,e.C_BLOCK_COMMENT_MODE,{className:"number",begin:"0'.\\|0[box][0-9a-fA-F]*"},e.NUMBER_MODE,r,n,{begin:/:-/},{begin:/\.$/}]}}),Lm)),zf.registerLanguage("mipsasm",(Bm||(Bm=1,Fm=function(e){return{name:"MIPS Assembly",case_insensitive:!0,aliases:["mips"],keywords:{$pattern:"\\.?"+e.IDENT_RE,meta:".2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .ltorg ",built_in:"$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15 $16 $17 $18 $19 $20 $21 $22 $23 $24 $25 $26 $27 $28 $29 $30 $31 zero at v0 v1 a0 a1 a2 a3 a4 a5 a6 a7 t0 t1 t2 t3 t4 t5 t6 t7 t8 t9 s0 s1 s2 s3 s4 s5 s6 s7 s8 k0 k1 gp sp fp ra $f0 $f1 $f2 $f2 $f4 $f5 $f6 $f7 $f8 $f9 $f10 $f11 $f12 $f13 $f14 $f15 $f16 $f17 $f18 $f19 $f20 $f21 $f22 $f23 $f24 $f25 $f26 $f27 $f28 $f29 $f30 $f31 Context Random EntryLo0 EntryLo1 Context PageMask Wired EntryHi HWREna BadVAddr Count Compare SR IntCtl SRSCtl SRSMap Cause EPC PRId EBase Config Config1 Config2 Config3 LLAddr Debug DEPC DESAVE CacheErr ECC ErrorEPC TagLo DataLo TagHi DataHi WatchLo WatchHi PerfCtl PerfCnt "},contains:[{className:"keyword",begin:"\\b(addi?u?|andi?|b(al)?|beql?|bgez(al)?l?|bgtzl?|blezl?|bltz(al)?l?|bnel?|cl[oz]|divu?|ext|ins|j(al)?|jalr(\\.hb)?|jr(\\.hb)?|lbu?|lhu?|ll|lui|lw[lr]?|maddu?|mfhi|mflo|movn|movz|move|msubu?|mthi|mtlo|mul|multu?|nop|nor|ori?|rotrv?|sb|sc|se[bh]|sh|sllv?|slti?u?|srav?|srlv?|subu?|sw[lr]?|xori?|wsbh|abs\\.[sd]|add\\.[sd]|alnv.ps|bc1[ft]l?|c\\.(s?f|un|u?eq|[ou]lt|[ou]le|ngle?|seq|l[et]|ng[et])\\.[sd]|(ceil|floor|round|trunc)\\.[lw]\\.[sd]|cfc1|cvt\\.d\\.[lsw]|cvt\\.l\\.[dsw]|cvt\\.ps\\.s|cvt\\.s\\.[dlw]|cvt\\.s\\.p[lu]|cvt\\.w\\.[dls]|div\\.[ds]|ldx?c1|luxc1|lwx?c1|madd\\.[sd]|mfc1|mov[fntz]?\\.[ds]|msub\\.[sd]|mth?c1|mul\\.[ds]|neg\\.[ds]|nmadd\\.[ds]|nmsub\\.[ds]|p[lu][lu]\\.ps|recip\\.fmt|r?sqrt\\.[ds]|sdx?c1|sub\\.[ds]|suxc1|swx?c1|break|cache|d?eret|[de]i|ehb|mfc0|mtc0|pause|prefx?|rdhwr|rdpgpr|sdbbp|ssnop|synci?|syscall|teqi?|tgei?u?|tlb(p|r|w[ir])|tlti?u?|tnei?|wait|wrpgpr)",end:"\\s"},e.COMMENT("[;#](?!\\s*$)","$"),e.C_BLOCK_COMMENT_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:"'",end:"[^\\\\]'",relevance:0},{className:"title",begin:"\\|",end:"\\|",illegal:"\\n",relevance:0},{className:"number",variants:[{begin:"0x[0-9a-f]+"},{begin:"\\b-?\\d+"}],relevance:0},{className:"symbol",variants:[{begin:"^\\s*[a-z_\\.\\$][a-z0-9_\\.\\$]+:"},{begin:"^\\s*[0-9]+:"},{begin:"[0-9]+[bf]"}],relevance:0}],illegal:/\//}}),Fm)),zf.registerLanguage("mizar",(Gm||(Gm=1,Um=function(e){return{name:"Mizar",keywords:"environ vocabularies notations constructors definitions registrations theorems schemes requirements begin end definition registration cluster existence pred func defpred deffunc theorem proof let take assume then thus hence ex for st holds consider reconsider such that and in provided of as from be being by means equals implies iff redefine define now not or attr is mode suppose per cases set thesis contradiction scheme reserve struct correctness compatibility coherence symmetry assymetry reflexivity irreflexivity connectedness uniqueness commutativity idempotence involutiveness projectivity",contains:[e.COMMENT("::","$")]}}),Um)),zf.registerLanguage("perl",(Ym||(Ym=1,zm=function(e){const t=e.regex,r=/[dualxmsipngr]{0,12}/,n={$pattern:/[\w.]+/,keyword:["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork","format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","local","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","setgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","until","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"].join(" ")},a={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:n},i={begin:/->\{/,end:/\}/},o={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},s={scope:"variable",variants:[{begin:/\$\d/},{begin:t.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[o]},l={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},c=[e.BACKSLASH_ESCAPE,a,s],d=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],u=(e,n,a="\\1")=>{const i="\\1"===a?a:t.concat(a,n);return t.concat(t.concat("(?:",e,")"),n,/(?:\\.|[^\\\/])*?/,i,/(?:\\.|[^\\\/])*?/,a,r)},p=(e,n,a)=>t.concat(t.concat("(?:",e,")"),n,/(?:\\.|[^\\\/])*?/,a,r),_=[s,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),i,{className:"string",contains:c,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},l,{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:u("s|tr|y",t.either(...d,{capture:!0}))},{begin:u("s|tr|y","\\(","\\)")},{begin:u("s|tr|y","\\[","\\]")},{begin:u("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:p("(?:m|qr)?",/\//,/\//)},{begin:p("m|qr",t.either(...d,{capture:!0}),/\1/)},{begin:p("m|qr",/\(/,/\)/)},{begin:p("m|qr",/\[/,/\]/)},{begin:p("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,o]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,o,l]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return a.contains=_,i.contains=_,{name:"Perl",aliases:["pl","pm"],keywords:n,contains:_}}),zm)),zf.registerLanguage("mojolicious",Hm?qm:(Hm=1,qm=function(e){return{name:"Mojolicious",subLanguage:"xml",contains:[{className:"meta",begin:"^__(END|DATA)__$"},{begin:"^\\s*%{1,2}={0,2}",end:"$",subLanguage:"perl"},{begin:"<%{1,2}={0,2}",end:"={0,1}%>",subLanguage:"perl",excludeBegin:!0,excludeEnd:!0}]}})),zf.registerLanguage("monkey",($m||($m=1,Vm=function(e){const t={className:"number",relevance:0,variants:[{begin:"[$][a-fA-F0-9]+"},e.NUMBER_MODE]},r={variants:[{match:[/(function|method)/,/\s+/,e.UNDERSCORE_IDENT_RE]}],scope:{1:"keyword",3:"title.function"}},n={variants:[{match:[/(class|interface|extends|implements)/,/\s+/,e.UNDERSCORE_IDENT_RE]}],scope:{1:"keyword",3:"title.class"}};return{name:"Monkey",case_insensitive:!0,keywords:{keyword:["public","private","property","continue","exit","extern","new","try","catch","eachin","not","abstract","final","select","case","default","const","local","global","field","end","if","then","else","elseif","endif","while","wend","repeat","until","forever","for","to","step","next","return","module","inline","throw","import","and","or","shl","shr","mod"],built_in:["DebugLog","DebugStop","Error","Print","ACos","ACosr","ASin","ASinr","ATan","ATan2","ATan2r","ATanr","Abs","Abs","Ceil","Clamp","Clamp","Cos","Cosr","Exp","Floor","Log","Max","Max","Min","Min","Pow","Sgn","Sgn","Sin","Sinr","Sqrt","Tan","Tanr","Seed","PI","HALFPI","TWOPI"],literal:["true","false","null"]},illegal:/\/\*/,contains:[e.COMMENT("#rem","#end"),e.COMMENT("'","$",{relevance:0}),r,n,{className:"variable.language",begin:/\b(self|super)\b/},{className:"meta",begin:/\s*#/,end:"$",keywords:{keyword:"if else elseif endif end then"}},{match:[/^\s*/,/strict\b/],scope:{2:"meta"}},{beginKeywords:"alias",end:"=",contains:[e.UNDERSCORE_TITLE_MODE]},e.QUOTE_STRING_MODE,t]}}),Vm)),zf.registerLanguage("moonscript",(jm||(jm=1,Wm=function(e){const t={keyword:"if then not for in while do return else elseif break continue switch and or unless when class extends super local import export from using",literal:"true false nil",built_in:"_G _VERSION assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall coroutine debug io math os package string table"},r="[A-Za-z$_][0-9A-Za-z$_]*",n={className:"subst",begin:/#\{/,end:/\}/,keywords:t},a=[e.inherit(e.C_NUMBER_MODE,{starts:{end:"(\\s*/)?",relevance:0}}),{className:"string",variants:[{begin:/'/,end:/'/,contains:[e.BACKSLASH_ESCAPE]},{begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n]}]},{className:"built_in",begin:"@__"+e.IDENT_RE},{begin:"@"+e.IDENT_RE},{begin:e.IDENT_RE+"\\\\"+e.IDENT_RE}];n.contains=a;const i=e.inherit(e.TITLE_MODE,{begin:r}),o="(\\(.*\\)\\s*)?\\B[-=]>",s={className:"params",begin:"\\([^\\(]",returnBegin:!0,contains:[{begin:/\(/,end:/\)/,keywords:t,contains:["self"].concat(a)}]};return{name:"MoonScript",aliases:["moon"],keywords:t,illegal:/\/\*/,contains:a.concat([e.COMMENT("--","$"),{className:"function",begin:"^\\s*"+r+"\\s*=\\s*"+o,end:"[-=]>",returnBegin:!0,contains:[i,s]},{begin:/[\(,:=]\s*/,relevance:0,contains:[{className:"function",begin:o,end:"[-=]>",returnBegin:!0,contains:[s]}]},{className:"class",beginKeywords:"class",end:"$",illegal:/[:="\[\]]/,contains:[{beginKeywords:"extends",endsWithParent:!0,illegal:/[:="\[\]]/,contains:[i]},i]},{className:"name",begin:r+":",end:":",returnBegin:!0,returnEnd:!0,relevance:0}])}}),Wm)),zf.registerLanguage("n1ql",(Km||(Km=1,Qm=function(e){return{name:"N1QL",case_insensitive:!0,contains:[{beginKeywords:"build create index delete drop explain infer|10 insert merge prepare select update upsert|10",end:/;/,keywords:{keyword:["all","alter","analyze","and","any","array","as","asc","begin","between","binary","boolean","break","bucket","build","by","call","case","cast","cluster","collate","collection","commit","connect","continue","correlate","cover","create","database","dataset","datastore","declare","decrement","delete","derived","desc","describe","distinct","do","drop","each","element","else","end","every","except","exclude","execute","exists","explain","fetch","first","flatten","for","force","from","function","grant","group","gsi","having","if","ignore","ilike","in","include","increment","index","infer","inline","inner","insert","intersect","into","is","join","key","keys","keyspace","known","last","left","let","letting","like","limit","lsm","map","mapping","matched","materialized","merge","minus","namespace","nest","not","number","object","offset","on","option","or","order","outer","over","parse","partition","password","path","pool","prepare","primary","private","privilege","procedure","public","raw","realm","reduce","rename","return","returning","revoke","right","role","rollback","satisfies","schema","select","self","semi","set","show","some","start","statistics","string","system","then","to","transaction","trigger","truncate","under","union","unique","unknown","unnest","unset","update","upsert","use","user","using","validate","value","valued","values","via","view","when","where","while","with","within","work","xor"],literal:["true","false","null","missing|5"],built_in:["array_agg","array_append","array_concat","array_contains","array_count","array_distinct","array_ifnull","array_length","array_max","array_min","array_position","array_prepend","array_put","array_range","array_remove","array_repeat","array_replace","array_reverse","array_sort","array_sum","avg","count","max","min","sum","greatest","least","ifmissing","ifmissingornull","ifnull","missingif","nullif","ifinf","ifnan","ifnanorinf","naninf","neginfif","posinfif","clock_millis","clock_str","date_add_millis","date_add_str","date_diff_millis","date_diff_str","date_part_millis","date_part_str","date_trunc_millis","date_trunc_str","duration_to_str","millis","str_to_millis","millis_to_str","millis_to_utc","millis_to_zone_name","now_millis","now_str","str_to_duration","str_to_utc","str_to_zone_name","decode_json","encode_json","encoded_size","poly_length","base64","base64_encode","base64_decode","meta","uuid","abs","acos","asin","atan","atan2","ceil","cos","degrees","e","exp","ln","log","floor","pi","power","radians","random","round","sign","sin","sqrt","tan","trunc","object_length","object_names","object_pairs","object_inner_pairs","object_values","object_inner_values","object_add","object_put","object_remove","object_unwrap","regexp_contains","regexp_like","regexp_position","regexp_replace","contains","initcap","length","lower","ltrim","position","repeat","replace","rtrim","split","substr","title","trim","upper","isarray","isatom","isboolean","isnumber","isobject","isstring","type","toarray","toatom","toboolean","tonumber","toobject","tostring"]},contains:[{className:"string",begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{className:"string",begin:'"',end:'"',contains:[e.BACKSLASH_ESCAPE]},{className:"symbol",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE]},e.C_BLOCK_COMMENT_MODE]}}),Qm)),zf.registerLanguage("nestedtext",(Zm||(Zm=1,Xm=function(e){return{name:"Nested Text",aliases:["nt"],contains:[e.inherit(e.HASH_COMMENT_MODE,{begin:/^\s*(?=#)/,excludeBegin:!0}),{variants:[{match:[/^\s*/,/-/,/[ ]/,/.*$/]},{match:[/^\s*/,/-$/]}],className:{2:"bullet",4:"string"}},{match:[/^\s*/,/>/,/[ ]/,/.*$/],className:{2:"punctuation",4:"string"}},{match:[/^\s*(?=\S)/,/[^:]+/,/:\s*/,/$/],className:{2:"attribute",3:"punctuation"}},{match:[/^\s*(?=\S)/,/[^:]*[^: ]/,/[ ]*:/,/[ ]/,/.*$/],className:{2:"attribute",3:"punctuation",5:"string"}}]}}),Xm)),zf.registerLanguage("nginx",(eg||(eg=1,Jm=function(e){const t=e.regex,r={className:"variable",variants:[{begin:/\$\d+/},{begin:/\$\{\w+\}/},{begin:t.concat(/[$@]/,e.UNDERSCORE_IDENT_RE)}]},n={endsWithParent:!0,keywords:{$pattern:/[a-z_]{2,}|\/dev\/poll/,literal:["on","off","yes","no","true","false","none","blocked","debug","info","notice","warn","error","crit","select","break","last","permanent","redirect","kqueue","rtsig","epoll","poll","/dev/poll"]},relevance:0,illegal:"=>",contains:[e.HASH_COMMENT_MODE,{className:"string",contains:[e.BACKSLASH_ESCAPE,r],variants:[{begin:/"/,end:/"/},{begin:/'/,end:/'/}]},{begin:"([a-z]+):/",end:"\\s",endsWithParent:!0,excludeEnd:!0,contains:[r]},{className:"regexp",contains:[e.BACKSLASH_ESCAPE,r],variants:[{begin:"\\s\\^",end:"\\s|\\{|;",returnEnd:!0},{begin:"~\\*?\\s+",end:"\\s|\\{|;",returnEnd:!0},{begin:"\\*(\\.[a-z\\-]+)+"},{begin:"([a-z\\-]+\\.)+\\*"}]},{className:"number",begin:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{className:"number",begin:"\\b\\d+[kKmMgGdshdwy]?\\b",relevance:0},r]};return{name:"Nginx config",aliases:["nginxconf"],contains:[e.HASH_COMMENT_MODE,{beginKeywords:"upstream location",end:/;|\{/,contains:n.contains,keywords:{section:"upstream location"}},{className:"section",begin:t.concat(e.UNDERSCORE_IDENT_RE+t.lookahead(/\s+\{/)),relevance:0},{begin:t.lookahead(e.UNDERSCORE_IDENT_RE+"\\s"),end:";|\\{",contains:[{className:"attribute",begin:e.UNDERSCORE_IDENT_RE,starts:n}],relevance:0}],illegal:"[^\\s\\}\\{]"}}),Jm)),zf.registerLanguage("nim",(rg||(rg=1,tg=function(e){return{name:"Nim",keywords:{keyword:["addr","and","as","asm","bind","block","break","case","cast","concept","const","continue","converter","defer","discard","distinct","div","do","elif","else","end","enum","except","export","finally","for","from","func","generic","guarded","if","import","in","include","interface","is","isnot","iterator","let","macro","method","mixin","mod","nil","not","notin","object","of","or","out","proc","ptr","raise","ref","return","shared","shl","shr","static","template","try","tuple","type","using","var","when","while","with","without","xor","yield"],literal:["true","false"],type:["int","int8","int16","int32","int64","uint","uint8","uint16","uint32","uint64","float","float32","float64","bool","char","string","cstring","pointer","expr","stmt","void","auto","any","range","array","openarray","varargs","seq","set","clong","culong","cchar","cschar","cshort","cint","csize","clonglong","cfloat","cdouble","clongdouble","cuchar","cushort","cuint","culonglong","cstringarray","semistatic"],built_in:["stdin","stdout","stderr","result"]},contains:[{className:"meta",begin:/\{\./,end:/\.\}/,relevance:10},{className:"string",begin:/[a-zA-Z]\w*"/,end:/"/,contains:[{begin:/""/}]},{className:"string",begin:/([a-zA-Z]\w*)?"""/,end:/"""/},e.QUOTE_STRING_MODE,{className:"type",begin:/\b[A-Z]\w+\b/,relevance:0},{className:"number",relevance:0,variants:[{begin:/\b(0[xX][0-9a-fA-F][_0-9a-fA-F]*)('?[iIuU](8|16|32|64))?/},{begin:/\b(0o[0-7][_0-7]*)('?[iIuUfF](8|16|32|64))?/},{begin:/\b(0(b|B)[01][_01]*)('?[iIuUfF](8|16|32|64))?/},{begin:/\b(\d[_\d]*)('?[iIuUfF](8|16|32|64))?/}]},e.HASH_COMMENT_MODE]}}),tg)),zf.registerLanguage("nix",(ag||(ag=1,ng=function(e){const t=e.regex,r={keyword:["assert","else","if","in","inherit","let","or","rec","then","with"],literal:["true","false","null"],built_in:["abort","baseNameOf","builtins","derivation","derivationStrict","dirOf","fetchGit","fetchMercurial","fetchTarball","fetchTree","fromTOML","import","isNull","map","placeholder","removeAttrs","scopedImport","throw","toString"]},n={scope:"built_in",match:t.either(...["abort","add","addDrvOutputDependencies","addErrorContext","all","any","appendContext","attrNames","attrValues","baseNameOf","bitAnd","bitOr","bitXor","break","builtins","catAttrs","ceil","compareVersions","concatLists","concatMap","concatStringsSep","convertHash","currentSystem","currentTime","deepSeq","derivation","derivationStrict","dirOf","div","elem","elemAt","false","fetchGit","fetchMercurial","fetchTarball","fetchTree","fetchurl","filter","filterSource","findFile","flakeRefToString","floor","foldl'","fromJSON","fromTOML","functionArgs","genList","genericClosure","getAttr","getContext","getEnv","getFlake","groupBy","hasAttr","hasContext","hashFile","hashString","head","import","intersectAttrs","isAttrs","isBool","isFloat","isFunction","isInt","isList","isNull","isPath","isString","langVersion","length","lessThan","listToAttrs","map","mapAttrs","match","mul","nixPath","nixVersion","null","parseDrvName","parseFlakeRef","partition","path","pathExists","placeholder","readDir","readFile","readFileType","removeAttrs","replaceStrings","scopedImport","seq","sort","split","splitVersion","storeDir","storePath","stringLength","sub","substring","tail","throw","toFile","toJSON","toPath","toString","toXML","trace","traceVerbose","true","tryEval","typeOf","unsafeDiscardOutputDependency","unsafeDiscardStringContext","unsafeGetAttrPos","warn","zipAttrsWith"].map(e=>`builtins\\.${e}`)),relevance:10},a="[A-Za-z_][A-Za-z0-9_'-]*",i={scope:"symbol",match:new RegExp(`<${a}(/${a})*>`)},o="[A-Za-z0-9_\\+\\.-]+",s={scope:"symbol",match:new RegExp(`(\\.\\.|\\.|~)?/(${o})?(/${o})*(?=[\\s;])`)},l=t.either("==","=","\\+\\+","\\+","<=","<\\|","<",">=",">","->","//","/","!=","!","\\|\\|","\\|>","\\?","\\*","&&"),c={scope:"operator",match:t.concat(l,/(?!-)/),relevance:0},d={scope:"number",match:new RegExp(`${e.NUMBER_RE}(?!-)`),relevance:0},u={variants:[{scope:"operator",beforeMatch:/\s/,begin:/-(?!>)/},{begin:[new RegExp(`${e.NUMBER_RE}`),/-/,/(?!>)/],beginScope:{1:"number",2:"operator"}},{begin:[l,/-/,/(?!>)/],beginScope:{1:"operator",2:"operator"}}],relevance:0},p={beforeMatch:/(^|\{|;)\s*/,begin:new RegExp(`${a}(\\.${a})*\\s*=(?!=)`),returnBegin:!0,relevance:0,contains:[{scope:"attr",match:new RegExp(`${a}(\\.${a})*(?=\\s*=)`),relevance:.2}]},_={scope:"subst",begin:/\$\{/,end:/\}/,keywords:r},m={scope:"char.escape",match:/\\(?!\$)./},g={scope:"string",variants:[{begin:"''",end:"''",contains:[{scope:"char.escape",match:/''\$/},_,{scope:"char.escape",match:/'''/},m]},{begin:'"',end:'"',contains:[{scope:"char.escape",match:/\\\$/},_,m]}]},h={scope:"params",match:new RegExp(`${a}\\s*:(?=\\s)`)},f=[d,e.HASH_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.COMMENT(/\/\*\*(?!\/)/,/\*\//,{subLanguage:"markdown",relevance:0}),n,g,i,s,h,p,u,c];return _.contains=f,{name:"Nix",aliases:["nixos"],keywords:r,contains:f.concat([{scope:"meta.prompt",match:/^nix-repl>(?=\s)/,relevance:10},{scope:"meta",beforeMatch:/\s+/,begin:/:([a-z]+|\?)/}])}}),ng)),zf.registerLanguage("node-repl",og?ig:(og=1,ig=function(e){return{name:"Node REPL",contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"javascript"}},variants:[{begin:/^>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}})),zf.registerLanguage("nsis",(lg||(lg=1,sg=function(e){const t=e.regex,r={className:"variable.constant",begin:t.concat(/\$/,t.either("ADMINTOOLS","APPDATA","CDBURN_AREA","CMDLINE","COMMONFILES32","COMMONFILES64","COMMONFILES","COOKIES","DESKTOP","DOCUMENTS","EXEDIR","EXEFILE","EXEPATH","FAVORITES","FONTS","HISTORY","HWNDPARENT","INSTDIR","INTERNET_CACHE","LANGUAGE","LOCALAPPDATA","MUSIC","NETHOOD","OUTDIR","PICTURES","PLUGINSDIR","PRINTHOOD","PROFILE","PROGRAMFILES32","PROGRAMFILES64","PROGRAMFILES","QUICKLAUNCH","RECENT","RESOURCES_LOCALIZED","RESOURCES","SENDTO","SMPROGRAMS","SMSTARTUP","STARTMENU","SYSDIR","TEMP","TEMPLATES","VIDEOS","WINDIR"))},n={className:"variable",begin:/\$+\{[\!\w.:-]+\}/},a={className:"variable",begin:/\$+\w[\w\.]*/,illegal:/\(\)\{\}/},i={className:"variable",begin:/\$+\([\w^.:!-]+\)/},o={className:"params",begin:t.either("ARCHIVE","FILE_ATTRIBUTE_ARCHIVE","FILE_ATTRIBUTE_NORMAL","FILE_ATTRIBUTE_OFFLINE","FILE_ATTRIBUTE_READONLY","FILE_ATTRIBUTE_SYSTEM","FILE_ATTRIBUTE_TEMPORARY","HKCR","HKCU","HKDD","HKEY_CLASSES_ROOT","HKEY_CURRENT_CONFIG","HKEY_CURRENT_USER","HKEY_DYN_DATA","HKEY_LOCAL_MACHINE","HKEY_PERFORMANCE_DATA","HKEY_USERS","HKLM","HKPD","HKU","IDABORT","IDCANCEL","IDIGNORE","IDNO","IDOK","IDRETRY","IDYES","MB_ABORTRETRYIGNORE","MB_DEFBUTTON1","MB_DEFBUTTON2","MB_DEFBUTTON3","MB_DEFBUTTON4","MB_ICONEXCLAMATION","MB_ICONINFORMATION","MB_ICONQUESTION","MB_ICONSTOP","MB_OK","MB_OKCANCEL","MB_RETRYCANCEL","MB_RIGHT","MB_RTLREADING","MB_SETFOREGROUND","MB_TOPMOST","MB_USERICON","MB_YESNO","NORMAL","OFFLINE","READONLY","SHCTX","SHELL_CONTEXT","SYSTEM|TEMPORARY")},s={className:"keyword",begin:t.concat(/!/,t.either("addincludedir","addplugindir","appendfile","assert","cd","define","delfile","echo","else","endif","error","execute","finalize","getdllversion","gettlbversion","if","ifdef","ifmacrodef","ifmacrondef","ifndef","include","insertmacro","macro","macroend","makensis","packhdr","searchparse","searchreplace","system","tempfile","undef","uninstfinalize","verbose","warning"))},l={className:"string",variants:[{begin:'"',end:'"'},{begin:"'",end:"'"},{begin:"`",end:"`"}],illegal:/\n/,contains:[{className:"char.escape",begin:/\$(\\[nrt]|\$)/},r,n,a,i]},c={match:[/Function/,/\s+/,t.concat(/(\.)?/,e.IDENT_RE)],scope:{1:"keyword",3:"title.function"}},d={match:[/Var/,/\s+/,/(?:\/GLOBAL\s+)?/,/[A-Za-z][\w.]*/],scope:{1:"keyword",3:"params",4:"variable"}};return{name:"NSIS",case_insensitive:!0,keywords:{keyword:["Abort","AddBrandingImage","AddSize","AllowRootDirInstall","AllowSkipFiles","AutoCloseWindow","BGFont","BGGradient","BrandingText","BringToFront","Call","CallInstDLL","Caption","ChangeUI","CheckBitmap","ClearErrors","CompletedText","ComponentText","CopyFiles","CRCCheck","CreateDirectory","CreateFont","CreateShortCut","Delete","DeleteINISec","DeleteINIStr","DeleteRegKey","DeleteRegValue","DetailPrint","DetailsButtonText","DirText","DirVar","DirVerify","EnableWindow","EnumRegKey","EnumRegValue","Exch","Exec","ExecShell","ExecShellWait","ExecWait","ExpandEnvStrings","File","FileBufSize","FileClose","FileErrorText","FileOpen","FileRead","FileReadByte","FileReadUTF16LE","FileReadWord","FileWriteUTF16LE","FileSeek","FileWrite","FileWriteByte","FileWriteWord","FindClose","FindFirst","FindNext","FindWindow","FlushINI","GetCurInstType","GetCurrentAddress","GetDlgItem","GetDLLVersion","GetDLLVersionLocal","GetErrorLevel","GetFileTime","GetFileTimeLocal","GetFullPathName","GetFunctionAddress","GetInstDirError","GetKnownFolderPath","GetLabelAddress","GetTempFileName","GetWinVer","Goto","HideWindow","Icon","IfAbort","IfErrors","IfFileExists","IfRebootFlag","IfRtlLanguage","IfShellVarContextAll","IfSilent","InitPluginsDir","InstallButtonText","InstallColors","InstallDir","InstallDirRegKey","InstProgressFlags","InstType","InstTypeGetText","InstTypeSetText","Int64Cmp","Int64CmpU","Int64Fmt","IntCmp","IntCmpU","IntFmt","IntOp","IntPtrCmp","IntPtrCmpU","IntPtrOp","IsWindow","LangString","LicenseBkColor","LicenseData","LicenseForceSelection","LicenseLangString","LicenseText","LoadAndSetImage","LoadLanguageFile","LockWindow","LogSet","LogText","ManifestDPIAware","ManifestLongPathAware","ManifestMaxVersionTested","ManifestSupportedOS","MessageBox","MiscButtonText","Name|0","Nop","OutFile","Page","PageCallbacks","PEAddResource","PEDllCharacteristics","PERemoveResource","PESubsysVer","Pop","Push","Quit","ReadEnvStr","ReadINIStr","ReadRegDWORD","ReadRegStr","Reboot","RegDLL","Rename","RequestExecutionLevel","ReserveFile","Return","RMDir","SearchPath","SectionGetFlags","SectionGetInstTypes","SectionGetSize","SectionGetText","SectionIn","SectionSetFlags","SectionSetInstTypes","SectionSetSize","SectionSetText","SendMessage","SetAutoClose","SetBrandingImage","SetCompress","SetCompressor","SetCompressorDictSize","SetCtlColors","SetCurInstType","SetDatablockOptimize","SetDateSave","SetDetailsPrint","SetDetailsView","SetErrorLevel","SetErrors","SetFileAttributes","SetFont","SetOutPath","SetOverwrite","SetRebootFlag","SetRegView","SetShellVarContext","SetSilent","ShowInstDetails","ShowUninstDetails","ShowWindow","SilentInstall","SilentUnInstall","Sleep","SpaceTexts","StrCmp","StrCmpS","StrCpy","StrLen","SubCaption","Unicode","UninstallButtonText","UninstallCaption","UninstallIcon","UninstallSubCaption","UninstallText","UninstPage","UnRegDLL","Var","VIAddVersionKey","VIFileVersion","VIProductVersion","WindowIcon","WriteINIStr","WriteRegBin","WriteRegDWORD","WriteRegExpandStr","WriteRegMultiStr","WriteRegNone","WriteRegStr","WriteUninstaller","XPStyle"],literal:["admin","all","auto","both","bottom","bzip2","colored","components","current","custom","directory","false","force","hide","highest","ifdiff","ifnewer","instfiles","lastused","leave","left","license","listonly","lzma","nevershow","none","normal","notset","off","on","open","print","right","show","silent","silentlog","smooth","textonly","top","true","try","un.components","un.custom","un.directory","un.instfiles","un.license","uninstConfirm","user","Win10","Win7","Win8","WinVista","zlib"]},contains:[e.HASH_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.COMMENT(";","$",{relevance:0}),d,c,{beginKeywords:"Function PageEx Section SectionGroup FunctionEnd SectionEnd"},l,s,n,a,i,o,{className:"title.function",begin:/\w+::\w+/},e.NUMBER_MODE]}}),sg)),zf.registerLanguage("objectivec",(dg||(dg=1,cg=function(e){const t=/[a-zA-Z@][a-zA-Z0-9_]*/,r={$pattern:t,keyword:["@interface","@class","@protocol","@implementation"]};return{name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"],keywords:{"variable.language":["this","super"],$pattern:t,keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"],literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"],built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"],type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"]},illegal:"</",contains:[{className:"built_in",begin:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.C_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{className:"string",variants:[{begin:'@"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]}]},{className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),{className:"string",begin:/<.*?>/,end:/$/,illegal:"\\n"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class",begin:"("+r.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:r,contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE,relevance:0}]}}),cg)),zf.registerLanguage("ocaml",(pg||(pg=1,ug=function(e){return{name:"OCaml",aliases:["ml"],keywords:{$pattern:"[a-z_]\\w*!?",keyword:"and as assert asr begin class constraint do done downto else end exception external for fun function functor if in include inherit! inherit initializer land lazy let lor lsl lsr lxor match method!|10 method mod module mutable new object of open! open or private rec sig struct then to try type val! val virtual when while with parser value",built_in:"array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 string unit in_channel out_channel ref",literal:"true false"},illegal:/\/\/|>>/,contains:[{className:"literal",begin:"\\[(\\|\\|)?\\]|\\(\\)",relevance:0},e.COMMENT("\\(\\*","\\*\\)",{contains:["self"]}),{className:"symbol",begin:"'[A-Za-z_](?!')[\\w']*"},{className:"type",begin:"`[A-Z][\\w']*"},{className:"type",begin:"\\b[A-Z][\\w']*",relevance:0},{begin:"[a-z_]\\w*'[\\w']*",relevance:0},e.inherit(e.APOS_STRING_MODE,{className:"string",relevance:0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),{className:"number",begin:"\\b(0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)",relevance:0},{begin:/->/}]}}),ug)),zf.registerLanguage("openscad",(mg||(mg=1,_g=function(e){const t={className:"keyword",begin:"\\$(f[asn]|t|vp[rtd]|children)"},r={className:"number",begin:"\\b\\d+(\\.\\d+)?(e-?\\d+)?",relevance:0},n=e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),a={className:"function",beginKeywords:"module function",end:/=|\{/,contains:[{className:"params",begin:"\\(",end:"\\)",contains:["self",r,n,t,{className:"literal",begin:"false|true|PI|undef"}]},e.UNDERSCORE_TITLE_MODE]};return{name:"OpenSCAD",aliases:["scad"],keywords:{keyword:"function module include use for intersection_for if else \\%",literal:"false true PI undef",built_in:"circle square polygon text sphere cube cylinder polyhedron translate rotate scale resize mirror multmatrix color offset hull minkowski union difference intersection abs sign sin cos tan acos asin atan atan2 floor round ceil ln log pow sqrt exp rands min max concat lookup str chr search version version_num norm cross parent_module echo import import_dxf dxf_linear_extrude linear_extrude rotate_extrude surface projection render children dxf_cross dxf_dim let assign"},contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,r,{className:"meta",keywords:{keyword:"include use"},begin:"include|use <",end:">"},n,t,{begin:"[*!#%]",relevance:0},a]}}),_g)),zf.registerLanguage("oxygene",(hg||(hg=1,gg=function(e){const t={$pattern:/\.?\w+/,keyword:"abstract add and array as asc aspect assembly async begin break block by case class concat const copy constructor continue create default delegate desc distinct div do downto dynamic each else empty end ensure enum equals event except exit extension external false final finalize finalizer finally flags for forward from function future global group has if implementation implements implies in index inherited inline interface into invariants is iterator join locked locking loop matching method mod module namespace nested new nil not notify nullable of old on operator or order out override parallel params partial pinned private procedure property protected public queryable raise read readonly record reintroduce remove repeat require result reverse sealed select self sequence set shl shr skip static step soft take then to true try tuple type union unit unsafe until uses using var virtual raises volatile where while with write xor yield await mapped deprecated stdcall cdecl pascal register safecall overload library platform reference packed strict published autoreleasepool selector strong weak unretained"},r=e.COMMENT(/\{/,/\}/,{relevance:0}),n=e.COMMENT("\\(\\*","\\*\\)",{relevance:10}),a={className:"string",begin:"'",end:"'",contains:[{begin:"''"}]},i={className:"string",begin:"(#\\d+)+"},o={beginKeywords:"function constructor destructor procedure method",end:"[:;]",keywords:"function constructor|10 destructor|10 procedure|10 method|10",contains:[e.inherit(e.TITLE_MODE,{scope:"title.function"}),{className:"params",begin:"\\(",end:"\\)",keywords:t,contains:[a,i]},r,n]};return{name:"Oxygene",case_insensitive:!0,keywords:t,illegal:'("|\\$[G-Zg-z]|\\/\\*|</|=>|->)',contains:[r,n,e.C_LINE_COMMENT_MODE,a,i,e.NUMBER_MODE,o,{scope:"punctuation",match:/;/,relevance:0}]}}),gg)),zf.registerLanguage("parser3",(Eg||(Eg=1,fg=function(e){const t=e.COMMENT(/\{/,/\}/,{contains:["self"]});return{name:"Parser3",subLanguage:"xml",relevance:0,contains:[e.COMMENT("^#","$"),e.COMMENT(/\^rem\{/,/\}/,{relevance:10,contains:[t]}),{className:"meta",begin:"^@(?:BASE|USE|CLASS|OPTIONS)$",relevance:10},{className:"title",begin:"@[\\w\\-]+\\[[\\w^;\\-]*\\](?:\\[[\\w^;\\-]*\\])?(?:.*)$"},{className:"variable",begin:/\$\{?[\w\-.:]+\}?/},{className:"keyword",begin:/\^[\w\-.:]+/},{className:"number",begin:"\\^#[0-9a-fA-F]+"},e.C_NUMBER_MODE]}}),fg)),zf.registerLanguage("pf",(Sg||(Sg=1,bg=function(e){return{name:"Packet Filter config",aliases:["pf.conf"],keywords:{$pattern:/[a-z0-9_<>-]+/,built_in:"block match pass load anchor|5 antispoof|10 set table",keyword:"in out log quick on rdomain inet inet6 proto from port os to route allow-opts divert-packet divert-reply divert-to flags group icmp-type icmp6-type label once probability recieved-on rtable prio queue tos tag tagged user keep fragment for os drop af-to|10 binat-to|10 nat-to|10 rdr-to|10 bitmask least-stats random round-robin source-hash static-port dup-to reply-to route-to parent bandwidth default min max qlimit block-policy debug fingerprints hostid limit loginterface optimization reassemble ruleset-optimization basic none profile skip state-defaults state-policy timeout const counters persist no modulate synproxy state|5 floating if-bound no-sync pflow|10 sloppy source-track global rule max-src-nodes max-src-states max-src-conn max-src-conn-rate overload flush scrub|5 max-mss min-ttl no-df|10 random-id",literal:"all any no-route self urpf-failed egress|5 unknown"},contains:[e.HASH_COMMENT_MODE,e.NUMBER_MODE,e.QUOTE_STRING_MODE,{className:"variable",begin:/\$[\w\d#@][\w\d_]*/,relevance:0},{className:"variable",begin:/<(?!\/)/,end:/>/}]}}),bg)),zf.registerLanguage("pgsql",(Tg||(Tg=1,vg=function(e){const t=e.COMMENT("--","$"),r="\\$([a-zA-Z_]?|[a-zA-Z_][a-zA-Z_0-9]*)\\$",n="BIGINT INT8 BIGSERIAL SERIAL8 BIT VARYING VARBIT BOOLEAN BOOL BOX BYTEA CHARACTER CHAR VARCHAR CIDR CIRCLE DATE DOUBLE PRECISION FLOAT8 FLOAT INET INTEGER INT INT4 INTERVAL JSON JSONB LINE LSEG|10 MACADDR MACADDR8 MONEY NUMERIC DEC DECIMAL PATH POINT POLYGON REAL FLOAT4 SMALLINT INT2 SMALLSERIAL|10 SERIAL2|10 SERIAL|10 SERIAL4|10 TEXT TIME ZONE TIMETZ|10 TIMESTAMP TIMESTAMPTZ|10 TSQUERY|10 TSVECTOR|10 TXID_SNAPSHOT|10 UUID XML NATIONAL NCHAR INT4RANGE|10 INT8RANGE|10 NUMRANGE|10 TSRANGE|10 TSTZRANGE|10 DATERANGE|10 ANYELEMENT ANYARRAY ANYNONARRAY ANYENUM ANYRANGE CSTRING INTERNAL RECORD PG_DDL_COMMAND VOID UNKNOWN OPAQUE REFCURSOR NAME OID REGPROC|10 REGPROCEDURE|10 REGOPER|10 REGOPERATOR|10 REGCLASS|10 REGTYPE|10 REGROLE|10 REGNAMESPACE|10 REGCONFIG|10 REGDICTIONARY|10 ",a=n.trim().split(" ").map(function(e){return e.split("|")[0]}).join("|"),i="ARRAY_AGG AVG BIT_AND BIT_OR BOOL_AND BOOL_OR COUNT EVERY JSON_AGG JSONB_AGG JSON_OBJECT_AGG JSONB_OBJECT_AGG MAX MIN MODE STRING_AGG SUM XMLAGG CORR COVAR_POP COVAR_SAMP REGR_AVGX REGR_AVGY REGR_COUNT REGR_INTERCEPT REGR_R2 REGR_SLOPE REGR_SXX REGR_SXY REGR_SYY STDDEV STDDEV_POP STDDEV_SAMP VARIANCE VAR_POP VAR_SAMP PERCENTILE_CONT PERCENTILE_DISC ROW_NUMBER RANK DENSE_RANK PERCENT_RANK CUME_DIST NTILE LAG LEAD FIRST_VALUE LAST_VALUE NTH_VALUE NUM_NONNULLS NUM_NULLS ABS CBRT CEIL CEILING DEGREES DIV EXP FLOOR LN LOG MOD PI POWER RADIANS ROUND SCALE SIGN SQRT TRUNC WIDTH_BUCKET RANDOM SETSEED ACOS ACOSD ASIN ASIND ATAN ATAND ATAN2 ATAN2D COS COSD COT COTD SIN SIND TAN TAND BIT_LENGTH CHAR_LENGTH CHARACTER_LENGTH LOWER OCTET_LENGTH OVERLAY POSITION SUBSTRING TREAT TRIM UPPER ASCII BTRIM CHR CONCAT CONCAT_WS CONVERT CONVERT_FROM CONVERT_TO DECODE ENCODE INITCAP LEFT LENGTH LPAD LTRIM MD5 PARSE_IDENT PG_CLIENT_ENCODING QUOTE_IDENT|10 QUOTE_LITERAL|10 QUOTE_NULLABLE|10 REGEXP_MATCH REGEXP_MATCHES REGEXP_REPLACE REGEXP_SPLIT_TO_ARRAY REGEXP_SPLIT_TO_TABLE REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPLIT_PART STRPOS SUBSTR TO_ASCII TO_HEX TRANSLATE OCTET_LENGTH GET_BIT GET_BYTE SET_BIT SET_BYTE TO_CHAR TO_DATE TO_NUMBER TO_TIMESTAMP AGE CLOCK_TIMESTAMP|10 DATE_PART DATE_TRUNC ISFINITE JUSTIFY_DAYS JUSTIFY_HOURS JUSTIFY_INTERVAL MAKE_DATE MAKE_INTERVAL|10 MAKE_TIME MAKE_TIMESTAMP|10 MAKE_TIMESTAMPTZ|10 NOW STATEMENT_TIMESTAMP|10 TIMEOFDAY TRANSACTION_TIMESTAMP|10 ENUM_FIRST ENUM_LAST ENUM_RANGE AREA CENTER DIAMETER HEIGHT ISCLOSED ISOPEN NPOINTS PCLOSE POPEN RADIUS WIDTH BOX BOUND_BOX CIRCLE LINE LSEG PATH POLYGON ABBREV BROADCAST HOST HOSTMASK MASKLEN NETMASK NETWORK SET_MASKLEN TEXT INET_SAME_FAMILY INET_MERGE MACADDR8_SET7BIT ARRAY_TO_TSVECTOR GET_CURRENT_TS_CONFIG NUMNODE PLAINTO_TSQUERY PHRASETO_TSQUERY WEBSEARCH_TO_TSQUERY QUERYTREE SETWEIGHT STRIP TO_TSQUERY TO_TSVECTOR JSON_TO_TSVECTOR JSONB_TO_TSVECTOR TS_DELETE TS_FILTER TS_HEADLINE TS_RANK TS_RANK_CD TS_REWRITE TSQUERY_PHRASE TSVECTOR_TO_ARRAY TSVECTOR_UPDATE_TRIGGER TSVECTOR_UPDATE_TRIGGER_COLUMN XMLCOMMENT XMLCONCAT XMLELEMENT XMLFOREST XMLPI XMLROOT XMLEXISTS XML_IS_WELL_FORMED XML_IS_WELL_FORMED_DOCUMENT XML_IS_WELL_FORMED_CONTENT XPATH XPATH_EXISTS XMLTABLE XMLNAMESPACES TABLE_TO_XML TABLE_TO_XMLSCHEMA TABLE_TO_XML_AND_XMLSCHEMA QUERY_TO_XML QUERY_TO_XMLSCHEMA QUERY_TO_XML_AND_XMLSCHEMA CURSOR_TO_XML CURSOR_TO_XMLSCHEMA SCHEMA_TO_XML SCHEMA_TO_XMLSCHEMA SCHEMA_TO_XML_AND_XMLSCHEMA DATABASE_TO_XML DATABASE_TO_XMLSCHEMA DATABASE_TO_XML_AND_XMLSCHEMA XMLATTRIBUTES TO_JSON TO_JSONB ARRAY_TO_JSON ROW_TO_JSON JSON_BUILD_ARRAY JSONB_BUILD_ARRAY JSON_BUILD_OBJECT JSONB_BUILD_OBJECT JSON_OBJECT JSONB_OBJECT JSON_ARRAY_LENGTH JSONB_ARRAY_LENGTH JSON_EACH JSONB_EACH JSON_EACH_TEXT JSONB_EACH_TEXT JSON_EXTRACT_PATH JSONB_EXTRACT_PATH JSON_OBJECT_KEYS JSONB_OBJECT_KEYS JSON_POPULATE_RECORD JSONB_POPULATE_RECORD JSON_POPULATE_RECORDSET JSONB_POPULATE_RECORDSET JSON_ARRAY_ELEMENTS JSONB_ARRAY_ELEMENTS JSON_ARRAY_ELEMENTS_TEXT JSONB_ARRAY_ELEMENTS_TEXT JSON_TYPEOF JSONB_TYPEOF JSON_TO_RECORD JSONB_TO_RECORD JSON_TO_RECORDSET JSONB_TO_RECORDSET JSON_STRIP_NULLS JSONB_STRIP_NULLS JSONB_SET JSONB_INSERT JSONB_PRETTY CURRVAL LASTVAL NEXTVAL SETVAL COALESCE NULLIF GREATEST LEAST ARRAY_APPEND ARRAY_CAT ARRAY_NDIMS ARRAY_DIMS ARRAY_FILL ARRAY_LENGTH ARRAY_LOWER ARRAY_POSITION ARRAY_POSITIONS ARRAY_PREPEND ARRAY_REMOVE ARRAY_REPLACE ARRAY_TO_STRING ARRAY_UPPER CARDINALITY STRING_TO_ARRAY UNNEST ISEMPTY LOWER_INC UPPER_INC LOWER_INF UPPER_INF RANGE_MERGE GENERATE_SERIES GENERATE_SUBSCRIPTS CURRENT_DATABASE CURRENT_QUERY CURRENT_SCHEMA|10 CURRENT_SCHEMAS|10 INET_CLIENT_ADDR INET_CLIENT_PORT INET_SERVER_ADDR INET_SERVER_PORT ROW_SECURITY_ACTIVE FORMAT_TYPE TO_REGCLASS TO_REGPROC TO_REGPROCEDURE TO_REGOPER TO_REGOPERATOR TO_REGTYPE TO_REGNAMESPACE TO_REGROLE COL_DESCRIPTION OBJ_DESCRIPTION SHOBJ_DESCRIPTION TXID_CURRENT TXID_CURRENT_IF_ASSIGNED TXID_CURRENT_SNAPSHOT TXID_SNAPSHOT_XIP TXID_SNAPSHOT_XMAX TXID_SNAPSHOT_XMIN TXID_VISIBLE_IN_SNAPSHOT TXID_STATUS CURRENT_SETTING SET_CONFIG BRIN_SUMMARIZE_NEW_VALUES BRIN_SUMMARIZE_RANGE BRIN_DESUMMARIZE_RANGE GIN_CLEAN_PENDING_LIST SUPPRESS_REDUNDANT_UPDATES_TRIGGER LO_FROM_BYTEA LO_PUT LO_GET LO_CREAT LO_CREATE LO_UNLINK LO_IMPORT LO_EXPORT LOREAD LOWRITE GROUPING CAST ".trim().split(" ").map(function(e){return e.split("|")[0]}).join("|");return{name:"PostgreSQL",aliases:["postgres","postgresql"],supersetOf:"sql",case_insensitive:!0,keywords:{keyword:"ABORT ALTER ANALYZE BEGIN CALL CHECKPOINT|10 CLOSE CLUSTER COMMENT COMMIT COPY CREATE DEALLOCATE DECLARE DELETE DISCARD DO DROP END EXECUTE EXPLAIN FETCH GRANT IMPORT INSERT LISTEN LOAD LOCK MOVE NOTIFY PREPARE REASSIGN|10 REFRESH REINDEX RELEASE RESET REVOKE ROLLBACK SAVEPOINT SECURITY SELECT SET SHOW START TRUNCATE UNLISTEN|10 UPDATE VACUUM|10 VALUES AGGREGATE COLLATION CONVERSION|10 DATABASE DEFAULT PRIVILEGES DOMAIN TRIGGER EXTENSION FOREIGN WRAPPER|10 TABLE FUNCTION GROUP LANGUAGE LARGE OBJECT MATERIALIZED VIEW OPERATOR CLASS FAMILY POLICY PUBLICATION|10 ROLE RULE SCHEMA SEQUENCE SERVER STATISTICS SUBSCRIPTION SYSTEM TABLESPACE CONFIGURATION DICTIONARY PARSER TEMPLATE TYPE USER MAPPING PREPARED ACCESS METHOD CAST AS TRANSFORM TRANSACTION OWNED TO INTO SESSION AUTHORIZATION INDEX PROCEDURE ASSERTION ALL ANALYSE AND ANY ARRAY ASC ASYMMETRIC|10 BOTH CASE CHECK COLLATE COLUMN CONCURRENTLY|10 CONSTRAINT CROSS DEFERRABLE RANGE DESC DISTINCT ELSE EXCEPT FOR FREEZE|10 FROM FULL HAVING ILIKE IN INITIALLY INNER INTERSECT IS ISNULL JOIN LATERAL LEADING LIKE LIMIT NATURAL NOT NOTNULL NULL OFFSET ON ONLY OR ORDER OUTER OVERLAPS PLACING PRIMARY REFERENCES RETURNING SIMILAR SOME SYMMETRIC TABLESAMPLE THEN TRAILING UNION UNIQUE USING VARIADIC|10 VERBOSE WHEN WHERE WINDOW WITH BY RETURNS INOUT OUT SETOF|10 IF STRICT CURRENT CONTINUE OWNER LOCATION OVER PARTITION WITHIN BETWEEN ESCAPE EXTERNAL INVOKER DEFINER WORK RENAME VERSION CONNECTION CONNECT TABLES TEMP TEMPORARY FUNCTIONS SEQUENCES TYPES SCHEMAS OPTION CASCADE RESTRICT ADD ADMIN EXISTS VALID VALIDATE ENABLE DISABLE REPLICA|10 ALWAYS PASSING COLUMNS PATH REF VALUE OVERRIDING IMMUTABLE STABLE VOLATILE BEFORE AFTER EACH ROW PROCEDURAL ROUTINE NO HANDLER VALIDATOR OPTIONS STORAGE OIDS|10 WITHOUT INHERIT DEPENDS CALLED INPUT LEAKPROOF|10 COST ROWS NOWAIT SEARCH UNTIL ENCRYPTED|10 PASSWORD CONFLICT|10 INSTEAD INHERITS CHARACTERISTICS WRITE CURSOR ALSO STATEMENT SHARE EXCLUSIVE INLINE ISOLATION REPEATABLE READ COMMITTED SERIALIZABLE UNCOMMITTED LOCAL GLOBAL SQL PROCEDURES RECURSIVE SNAPSHOT ROLLUP CUBE TRUSTED|10 INCLUDE FOLLOWING PRECEDING UNBOUNDED RANGE GROUPS UNENCRYPTED|10 SYSID FORMAT DELIMITER HEADER QUOTE ENCODING FILTER OFF FORCE_QUOTE FORCE_NOT_NULL FORCE_NULL COSTS BUFFERS TIMING SUMMARY DISABLE_PAGE_SKIPPING RESTART CYCLE GENERATED IDENTITY DEFERRED IMMEDIATE LEVEL LOGGED UNLOGGED OF NOTHING NONE EXCLUDE ATTRIBUTE USAGE ROUTINES TRUE FALSE NAN INFINITY ALIAS BEGIN CONSTANT DECLARE END EXCEPTION RETURN PERFORM|10 RAISE GET DIAGNOSTICS STACKED|10 FOREACH LOOP ELSIF EXIT WHILE REVERSE SLICE DEBUG LOG INFO NOTICE WARNING ASSERT OPEN SUPERUSER NOSUPERUSER CREATEDB NOCREATEDB CREATEROLE NOCREATEROLE INHERIT NOINHERIT LOGIN NOLOGIN REPLICATION NOREPLICATION BYPASSRLS NOBYPASSRLS ",built_in:"CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURRENT_CATALOG|10 CURRENT_DATE LOCALTIME LOCALTIMESTAMP CURRENT_ROLE|10 CURRENT_SCHEMA|10 SESSION_USER PUBLIC FOUND NEW OLD TG_NAME|10 TG_WHEN|10 TG_LEVEL|10 TG_OP|10 TG_RELID|10 TG_RELNAME|10 TG_TABLE_NAME|10 TG_TABLE_SCHEMA|10 TG_NARGS|10 TG_ARGV|10 TG_EVENT|10 TG_TAG|10 ROW_COUNT RESULT_OID|10 PG_CONTEXT|10 RETURNED_SQLSTATE COLUMN_NAME CONSTRAINT_NAME PG_DATATYPE_NAME|10 MESSAGE_TEXT TABLE_NAME SCHEMA_NAME PG_EXCEPTION_DETAIL|10 PG_EXCEPTION_HINT|10 PG_EXCEPTION_CONTEXT|10 SQLSTATE SQLERRM|10 SUCCESSFUL_COMPLETION WARNING DYNAMIC_RESULT_SETS_RETURNED IMPLICIT_ZERO_BIT_PADDING NULL_VALUE_ELIMINATED_IN_SET_FUNCTION PRIVILEGE_NOT_GRANTED PRIVILEGE_NOT_REVOKED STRING_DATA_RIGHT_TRUNCATION DEPRECATED_FEATURE NO_DATA NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED SQL_STATEMENT_NOT_YET_COMPLETE CONNECTION_EXCEPTION CONNECTION_DOES_NOT_EXIST CONNECTION_FAILURE SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION TRANSACTION_RESOLUTION_UNKNOWN PROTOCOL_VIOLATION TRIGGERED_ACTION_EXCEPTION FEATURE_NOT_SUPPORTED INVALID_TRANSACTION_INITIATION LOCATOR_EXCEPTION INVALID_LOCATOR_SPECIFICATION INVALID_GRANTOR INVALID_GRANT_OPERATION INVALID_ROLE_SPECIFICATION DIAGNOSTICS_EXCEPTION STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER CASE_NOT_FOUND CARDINALITY_VIOLATION DATA_EXCEPTION ARRAY_SUBSCRIPT_ERROR CHARACTER_NOT_IN_REPERTOIRE DATETIME_FIELD_OVERFLOW DIVISION_BY_ZERO ERROR_IN_ASSIGNMENT ESCAPE_CHARACTER_CONFLICT INDICATOR_OVERFLOW INTERVAL_FIELD_OVERFLOW INVALID_ARGUMENT_FOR_LOGARITHM INVALID_ARGUMENT_FOR_NTILE_FUNCTION INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION INVALID_ARGUMENT_FOR_POWER_FUNCTION INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION INVALID_CHARACTER_VALUE_FOR_CAST INVALID_DATETIME_FORMAT INVALID_ESCAPE_CHARACTER INVALID_ESCAPE_OCTET INVALID_ESCAPE_SEQUENCE NONSTANDARD_USE_OF_ESCAPE_CHARACTER INVALID_INDICATOR_PARAMETER_VALUE INVALID_PARAMETER_VALUE INVALID_REGULAR_EXPRESSION INVALID_ROW_COUNT_IN_LIMIT_CLAUSE INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE INVALID_TABLESAMPLE_ARGUMENT INVALID_TABLESAMPLE_REPEAT INVALID_TIME_ZONE_DISPLACEMENT_VALUE INVALID_USE_OF_ESCAPE_CHARACTER MOST_SPECIFIC_TYPE_MISMATCH NULL_VALUE_NOT_ALLOWED NULL_VALUE_NO_INDICATOR_PARAMETER NUMERIC_VALUE_OUT_OF_RANGE SEQUENCE_GENERATOR_LIMIT_EXCEEDED STRING_DATA_LENGTH_MISMATCH STRING_DATA_RIGHT_TRUNCATION SUBSTRING_ERROR TRIM_ERROR UNTERMINATED_C_STRING ZERO_LENGTH_CHARACTER_STRING FLOATING_POINT_EXCEPTION INVALID_TEXT_REPRESENTATION INVALID_BINARY_REPRESENTATION BAD_COPY_FILE_FORMAT UNTRANSLATABLE_CHARACTER NOT_AN_XML_DOCUMENT INVALID_XML_DOCUMENT INVALID_XML_CONTENT INVALID_XML_COMMENT INVALID_XML_PROCESSING_INSTRUCTION INTEGRITY_CONSTRAINT_VIOLATION RESTRICT_VIOLATION NOT_NULL_VIOLATION FOREIGN_KEY_VIOLATION UNIQUE_VIOLATION CHECK_VIOLATION EXCLUSION_VIOLATION INVALID_CURSOR_STATE INVALID_TRANSACTION_STATE ACTIVE_SQL_TRANSACTION BRANCH_TRANSACTION_ALREADY_ACTIVE HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION READ_ONLY_SQL_TRANSACTION SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED NO_ACTIVE_SQL_TRANSACTION IN_FAILED_SQL_TRANSACTION IDLE_IN_TRANSACTION_SESSION_TIMEOUT INVALID_SQL_STATEMENT_NAME TRIGGERED_DATA_CHANGE_VIOLATION INVALID_AUTHORIZATION_SPECIFICATION INVALID_PASSWORD DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST DEPENDENT_OBJECTS_STILL_EXIST INVALID_TRANSACTION_TERMINATION SQL_ROUTINE_EXCEPTION FUNCTION_EXECUTED_NO_RETURN_STATEMENT MODIFYING_SQL_DATA_NOT_PERMITTED PROHIBITED_SQL_STATEMENT_ATTEMPTED READING_SQL_DATA_NOT_PERMITTED INVALID_CURSOR_NAME EXTERNAL_ROUTINE_EXCEPTION CONTAINING_SQL_NOT_PERMITTED MODIFYING_SQL_DATA_NOT_PERMITTED PROHIBITED_SQL_STATEMENT_ATTEMPTED READING_SQL_DATA_NOT_PERMITTED EXTERNAL_ROUTINE_INVOCATION_EXCEPTION INVALID_SQLSTATE_RETURNED NULL_VALUE_NOT_ALLOWED TRIGGER_PROTOCOL_VIOLATED SRF_PROTOCOL_VIOLATED EVENT_TRIGGER_PROTOCOL_VIOLATED SAVEPOINT_EXCEPTION INVALID_SAVEPOINT_SPECIFICATION INVALID_CATALOG_NAME INVALID_SCHEMA_NAME TRANSACTION_ROLLBACK TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION SERIALIZATION_FAILURE STATEMENT_COMPLETION_UNKNOWN DEADLOCK_DETECTED SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION SYNTAX_ERROR INSUFFICIENT_PRIVILEGE CANNOT_COERCE GROUPING_ERROR WINDOWING_ERROR INVALID_RECURSION INVALID_FOREIGN_KEY INVALID_NAME NAME_TOO_LONG RESERVED_NAME DATATYPE_MISMATCH INDETERMINATE_DATATYPE COLLATION_MISMATCH INDETERMINATE_COLLATION WRONG_OBJECT_TYPE GENERATED_ALWAYS UNDEFINED_COLUMN UNDEFINED_FUNCTION UNDEFINED_TABLE UNDEFINED_PARAMETER UNDEFINED_OBJECT DUPLICATE_COLUMN DUPLICATE_CURSOR DUPLICATE_DATABASE DUPLICATE_FUNCTION DUPLICATE_PREPARED_STATEMENT DUPLICATE_SCHEMA DUPLICATE_TABLE DUPLICATE_ALIAS DUPLICATE_OBJECT AMBIGUOUS_COLUMN AMBIGUOUS_FUNCTION AMBIGUOUS_PARAMETER AMBIGUOUS_ALIAS INVALID_COLUMN_REFERENCE INVALID_COLUMN_DEFINITION INVALID_CURSOR_DEFINITION INVALID_DATABASE_DEFINITION INVALID_FUNCTION_DEFINITION INVALID_PREPARED_STATEMENT_DEFINITION INVALID_SCHEMA_DEFINITION INVALID_TABLE_DEFINITION INVALID_OBJECT_DEFINITION WITH_CHECK_OPTION_VIOLATION INSUFFICIENT_RESOURCES DISK_FULL OUT_OF_MEMORY TOO_MANY_CONNECTIONS CONFIGURATION_LIMIT_EXCEEDED PROGRAM_LIMIT_EXCEEDED STATEMENT_TOO_COMPLEX TOO_MANY_COLUMNS TOO_MANY_ARGUMENTS OBJECT_NOT_IN_PREREQUISITE_STATE OBJECT_IN_USE CANT_CHANGE_RUNTIME_PARAM LOCK_NOT_AVAILABLE OPERATOR_INTERVENTION QUERY_CANCELED ADMIN_SHUTDOWN CRASH_SHUTDOWN CANNOT_CONNECT_NOW DATABASE_DROPPED SYSTEM_ERROR IO_ERROR UNDEFINED_FILE DUPLICATE_FILE SNAPSHOT_TOO_OLD CONFIG_FILE_ERROR LOCK_FILE_EXISTS FDW_ERROR FDW_COLUMN_NAME_NOT_FOUND FDW_DYNAMIC_PARAMETER_VALUE_NEEDED FDW_FUNCTION_SEQUENCE_ERROR FDW_INCONSISTENT_DESCRIPTOR_INFORMATION FDW_INVALID_ATTRIBUTE_VALUE FDW_INVALID_COLUMN_NAME FDW_INVALID_COLUMN_NUMBER FDW_INVALID_DATA_TYPE FDW_INVALID_DATA_TYPE_DESCRIPTORS FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER FDW_INVALID_HANDLE FDW_INVALID_OPTION_INDEX FDW_INVALID_OPTION_NAME FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH FDW_INVALID_STRING_FORMAT FDW_INVALID_USE_OF_NULL_POINTER FDW_TOO_MANY_HANDLES FDW_OUT_OF_MEMORY FDW_NO_SCHEMAS FDW_OPTION_NAME_NOT_FOUND FDW_REPLY_HANDLE FDW_SCHEMA_NOT_FOUND FDW_TABLE_NOT_FOUND FDW_UNABLE_TO_CREATE_EXECUTION FDW_UNABLE_TO_CREATE_REPLY FDW_UNABLE_TO_ESTABLISH_CONNECTION PLPGSQL_ERROR RAISE_EXCEPTION NO_DATA_FOUND TOO_MANY_ROWS ASSERT_FAILURE INTERNAL_ERROR DATA_CORRUPTED INDEX_CORRUPTED "},illegal:/:==|\W\s*\(\*|(^|\s)\$[a-z]|\{\{|[a-z]:\s*$|\.\.\.|TO:|DO:/,contains:[{className:"keyword",variants:[{begin:/\bTEXT\s*SEARCH\b/},{begin:/\b(PRIMARY|FOREIGN|FOR(\s+NO)?)\s+KEY\b/},{begin:/\bPARALLEL\s+(UNSAFE|RESTRICTED|SAFE)\b/},{begin:/\bSTORAGE\s+(PLAIN|EXTERNAL|EXTENDED|MAIN)\b/},{begin:/\bMATCH\s+(FULL|PARTIAL|SIMPLE)\b/},{begin:/\bNULLS\s+(FIRST|LAST)\b/},{begin:/\bEVENT\s+TRIGGER\b/},{begin:/\b(MAPPING|OR)\s+REPLACE\b/},{begin:/\b(FROM|TO)\s+(PROGRAM|STDIN|STDOUT)\b/},{begin:/\b(SHARE|EXCLUSIVE)\s+MODE\b/},{begin:/\b(LEFT|RIGHT)\s+(OUTER\s+)?JOIN\b/},{begin:/\b(FETCH|MOVE)\s+(NEXT|PRIOR|FIRST|LAST|ABSOLUTE|RELATIVE|FORWARD|BACKWARD)\b/},{begin:/\bPRESERVE\s+ROWS\b/},{begin:/\bDISCARD\s+PLANS\b/},{begin:/\bREFERENCING\s+(OLD|NEW)\b/},{begin:/\bSKIP\s+LOCKED\b/},{begin:/\bGROUPING\s+SETS\b/},{begin:/\b(BINARY|INSENSITIVE|SCROLL|NO\s+SCROLL)\s+(CURSOR|FOR)\b/},{begin:/\b(WITH|WITHOUT)\s+HOLD\b/},{begin:/\bWITH\s+(CASCADED|LOCAL)\s+CHECK\s+OPTION\b/},{begin:/\bEXCLUDE\s+(TIES|NO\s+OTHERS)\b/},{begin:/\bFORMAT\s+(TEXT|XML|JSON|YAML)\b/},{begin:/\bSET\s+((SESSION|LOCAL)\s+)?NAMES\b/},{begin:/\bIS\s+(NOT\s+)?UNKNOWN\b/},{begin:/\bSECURITY\s+LABEL\b/},{begin:/\bSTANDALONE\s+(YES|NO|NO\s+VALUE)\b/},{begin:/\bWITH\s+(NO\s+)?DATA\b/},{begin:/\b(FOREIGN|SET)\s+DATA\b/},{begin:/\bSET\s+(CATALOG|CONSTRAINTS)\b/},{begin:/\b(WITH|FOR)\s+ORDINALITY\b/},{begin:/\bIS\s+(NOT\s+)?DOCUMENT\b/},{begin:/\bXML\s+OPTION\s+(DOCUMENT|CONTENT)\b/},{begin:/\b(STRIP|PRESERVE)\s+WHITESPACE\b/},{begin:/\bNO\s+(ACTION|MAXVALUE|MINVALUE)\b/},{begin:/\bPARTITION\s+BY\s+(RANGE|LIST|HASH)\b/},{begin:/\bAT\s+TIME\s+ZONE\b/},{begin:/\bGRANTED\s+BY\b/},{begin:/\bRETURN\s+(QUERY|NEXT)\b/},{begin:/\b(ATTACH|DETACH)\s+PARTITION\b/},{begin:/\bFORCE\s+ROW\s+LEVEL\s+SECURITY\b/},{begin:/\b(INCLUDING|EXCLUDING)\s+(COMMENTS|CONSTRAINTS|DEFAULTS|IDENTITY|INDEXES|STATISTICS|STORAGE|ALL)\b/},{begin:/\bAS\s+(ASSIGNMENT|IMPLICIT|PERMISSIVE|RESTRICTIVE|ENUM|RANGE)\b/}]},{begin:/\b(FORMAT|FAMILY|VERSION)\s*\(/},{begin:/\bINCLUDE\s*\(/,keywords:"INCLUDE"},{begin:/\bRANGE(?!\s*(BETWEEN|UNBOUNDED|CURRENT|[-0-9]+))/},{begin:/\b(VERSION|OWNER|TEMPLATE|TABLESPACE|CONNECTION\s+LIMIT|PROCEDURE|RESTRICT|JOIN|PARSER|COPY|START|END|COLLATION|INPUT|ANALYZE|STORAGE|LIKE|DEFAULT|DELIMITER|ENCODING|COLUMN|CONSTRAINT|TABLE|SCHEMA)\s*=/},{begin:/\b(PG_\w+?|HAS_[A-Z_]+_PRIVILEGE)\b/,relevance:10},{begin:/\bEXTRACT\s*\(/,end:/\bFROM\b/,returnEnd:!0,keywords:{type:"CENTURY DAY DECADE DOW DOY EPOCH HOUR ISODOW ISOYEAR MICROSECONDS MILLENNIUM MILLISECONDS MINUTE MONTH QUARTER SECOND TIMEZONE TIMEZONE_HOUR TIMEZONE_MINUTE WEEK YEAR"}},{begin:/\b(XMLELEMENT|XMLPI)\s*\(\s*NAME/,keywords:{keyword:"NAME"}},{begin:/\b(XMLPARSE|XMLSERIALIZE)\s*\(\s*(DOCUMENT|CONTENT)/,keywords:{keyword:"DOCUMENT CONTENT"}},{beginKeywords:"CACHE INCREMENT MAXVALUE MINVALUE",end:e.C_NUMBER_RE,returnEnd:!0,keywords:"BY CACHE INCREMENT MAXVALUE MINVALUE"},{className:"type",begin:/\b(WITH|WITHOUT)\s+TIME\s+ZONE\b/},{className:"type",begin:/\bINTERVAL\s+(YEAR|MONTH|DAY|HOUR|MINUTE|SECOND)(\s+TO\s+(MONTH|HOUR|MINUTE|SECOND))?\b/},{begin:/\bRETURNS\s+(LANGUAGE_HANDLER|TRIGGER|EVENT_TRIGGER|FDW_HANDLER|INDEX_AM_HANDLER|TSM_HANDLER)\b/,keywords:{keyword:"RETURNS",type:"LANGUAGE_HANDLER TRIGGER EVENT_TRIGGER FDW_HANDLER INDEX_AM_HANDLER TSM_HANDLER"}},{begin:"\\b("+i+")\\s*\\("},{begin:"\\.("+a+")\\b"},{begin:"\\b("+a+")\\s+PATH\\b",keywords:{keyword:"PATH",type:n.replace("PATH ","")}},{className:"type",begin:"\\b("+a+")\\b"},{className:"string",begin:"'",end:"'",contains:[{begin:"''"}]},{className:"string",begin:"(e|E|u&|U&)'",end:"'",contains:[{begin:"\\\\."}],relevance:10},e.END_SAME_AS_BEGIN({begin:r,end:r,contains:[{subLanguage:["pgsql","perl","python","tcl","r","lua","java","php","ruby","bash","scheme","xml","json"],endsWithParent:!0}]}),{begin:'"',end:'"',contains:[{begin:'""'}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,t,{className:"meta",variants:[{begin:"%(ROW)?TYPE",relevance:10},{begin:"\\$\\d+"},{begin:"^#\\w",end:"$"}]},{className:"symbol",begin:"<<\\s*[a-zA-Z_][a-zA-Z_0-9$]*\\s*>>",relevance:10}]}}),vg)),zf.registerLanguage("php",(Cg||(Cg=1,yg=function(e){const t=e.regex,r=/(?![A-Za-z0-9])(?![$])/,n=t.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,r),a=t.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,r),i=t.concat(/[A-Z]+/,r),o={scope:"variable",match:"\\$+"+n},s={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},l=e.inherit(e.APOS_STRING_MODE,{illegal:null}),c="[ \t\n]",d={scope:"string",variants:[e.inherit(e.QUOTE_STRING_MODE,{illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(s)}),l,{begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:e.QUOTE_STRING_MODE.contains.concat(s),"on:begin":(e,t)=>{t.data._beginMatch=e[1]||e[2]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}},e.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/})]},u={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},p=["false","null","true"],_=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],m=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],g={keyword:_,literal:(e=>{const t=[];return e.forEach(e=>{t.push(e),e.toLowerCase()===e?t.push(e.toUpperCase()):t.push(e.toLowerCase())}),t})(p),built_in:m},h=e=>e.map(e=>e.replace(/\|\d+$/,"")),f={variants:[{match:[/new/,t.concat(c,"+"),t.concat("(?!",h(m).join("\\b|"),"\\b)"),a],scope:{1:"keyword",4:"title.class"}}]},E=t.concat(n,"\\b(?!\\()"),b={variants:[{match:[t.concat(/::/,t.lookahead(/(?!class\b)/)),E],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[a,t.concat(/::/,t.lookahead(/(?!class\b)/)),E],scope:{1:"title.class",3:"variable.constant"}},{match:[a,t.concat("::",t.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[a,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},S={scope:"attr",match:t.concat(n,t.lookahead(":"),t.lookahead(/(?!::)/))},v={relevance:0,begin:/\(/,end:/\)/,keywords:g,contains:[S,o,b,e.C_BLOCK_COMMENT_MODE,d,u,f]},T={relevance:0,match:[/\b/,t.concat("(?!fn\\b|function\\b|",h(_).join("\\b|"),"|",h(m).join("\\b|"),"\\b)"),n,t.concat(c,"*"),t.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[v]};v.contains.push(T);const y=[S,b,e.C_BLOCK_COMMENT_MODE,d,u,f],C={begin:t.concat(/#\[\s*\\?/,t.either(a,i)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:p,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:p,keyword:["new","array"]},contains:["self",...y]},...y,{scope:"meta",variants:[{match:a},{match:i}]}]};return{case_insensitive:!1,keywords:g,contains:[C,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},{scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},{scope:"variable.language",match:/\$this\b/},o,T,b,{match:[/const/,/\s/,n],scope:{1:"keyword",3:"variable.constant"}},f,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:g,contains:["self",C,o,b,e.C_BLOCK_COMMENT_MODE,d,u]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},d,u]}}),yg)),zf.registerLanguage("php-template",(Rg||(Rg=1,Ng=function(e){return{name:"PHP template",subLanguage:"xml",contains:[{begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*",end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0})]}]}}),Ng)),zf.registerLanguage("plaintext",Og?Ag:(Og=1,Ag=function(e){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}})),zf.registerLanguage("pony",(xg||(xg=1,Ig=function(e){return{name:"Pony",keywords:{keyword:"actor addressof and as be break class compile_error compile_intrinsic consume continue delegate digestof do else elseif embed end error for fun if ifdef in interface is isnt lambda let match new not object or primitive recover repeat return struct then trait try type until use var where while with xor",meta:"iso val tag trn box ref",literal:"this false true"},contains:[{className:"type",begin:"\\b_?[A-Z][\\w]*",relevance:0},{className:"string",begin:'"""',end:'"""',relevance:10},{className:"string",begin:'"',end:'"',contains:[e.BACKSLASH_ESCAPE]},{className:"string",begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE],relevance:0},{begin:e.IDENT_RE+"'",relevance:0},{className:"number",begin:"(-?)(\\b0[xX][a-fA-F0-9]+|\\b0[bB][01]+|(\\b\\d+(_\\d+)?(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",relevance:0},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]}}),Ig)),zf.registerLanguage("powershell",(Dg||(Dg=1,wg=function(e){const t={$pattern:/-?[A-z\.\-]+\b/,keyword:"if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter",built_in:"ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write"},r={begin:"`[\\s\\S]",relevance:0},n={className:"variable",variants:[{begin:/\$\B/},{className:"keyword",begin:/\$this/},{begin:/\$[\w\d][\w\d_:]*/}]},a={className:"string",variants:[{begin:/"/,end:/"/},{begin:/@"/,end:/^"@/}],contains:[r,n,{className:"variable",begin:/\$[A-z]/,end:/[^A-z]/}]},i={className:"string",variants:[{begin:/'/,end:/'/},{begin:/@'/,end:/^'@/}]},o=e.inherit(e.COMMENT(null,null),{variants:[{begin:/#/,end:/$/},{begin:/<#/,end:/#>/}],contains:[{className:"doctag",variants:[{begin:/\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/},{begin:/\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/}]}]}),s={className:"built_in",variants:[{begin:"(".concat("Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where",")+(-)[\\w\\d]+")}]},l={className:"class",beginKeywords:"class enum",end:/\s*[{]/,excludeEnd:!0,relevance:0,contains:[e.TITLE_MODE]},c={className:"function",begin:/function\s+/,end:/\s*\{|$/,excludeEnd:!0,returnBegin:!0,relevance:0,contains:[{begin:"function",relevance:0,className:"keyword"},{className:"title",begin:/\w[\w\d]*((-)[\w\d]+)*/,relevance:0},{begin:/\(/,end:/\)/,className:"params",relevance:0,contains:[n]}]},d={begin:/using\s/,end:/$/,returnBegin:!0,contains:[a,i,{className:"keyword",begin:/(using|assembly|command|module|namespace|type)/}]},u={variants:[{className:"operator",begin:"(".concat("-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor",")\\b")},{className:"literal",begin:/(-){1,2}[\w\d-]+/,relevance:0}]},p={className:"function",begin:/\[.*\]\s*[\w]+[ ]??\(/,end:/$/,returnBegin:!0,relevance:0,contains:[{className:"keyword",begin:"(".concat(t.keyword.toString().replace(/\s/g,"|"),")\\b"),endsParent:!0,relevance:0},e.inherit(e.TITLE_MODE,{endsParent:!0})]},_=[p,o,r,e.NUMBER_MODE,a,i,s,n,{className:"literal",begin:/\$(null|true|false)\b/},{className:"selector-tag",begin:/@\B/,relevance:0}],m={begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[].concat("self",_,{begin:"("+["string","char","byte","int","long","bool","decimal","single","double","DateTime","xml","array","hashtable","void"].join("|")+")",className:"built_in",relevance:0},{className:"type",begin:/[\.\w\d]+/,relevance:0})};return p.contains.unshift(m),{name:"PowerShell",aliases:["pwsh","ps","ps1"],case_insensitive:!0,keywords:t,contains:_.concat(l,c,d,u,m)}}),wg)),zf.registerLanguage("processing",(kg||(kg=1,Mg=function(e){const t=e.regex,r=["displayHeight","displayWidth","mouseY","mouseX","mousePressed","pmouseX","pmouseY","key","keyCode","pixels","focused","frameCount","frameRate","height","width","size","createGraphics","beginDraw","createShape","loadShape","PShape","arc","ellipse","line","point","quad","rect","triangle","bezier","bezierDetail","bezierPoint","bezierTangent","curve","curveDetail","curvePoint","curveTangent","curveTightness","shape","shapeMode","beginContour","beginShape","bezierVertex","curveVertex","endContour","endShape","quadraticVertex","vertex","ellipseMode","noSmooth","rectMode","smooth","strokeCap","strokeJoin","strokeWeight","mouseClicked","mouseDragged","mouseMoved","mousePressed","mouseReleased","mouseWheel","keyPressed","keyPressedkeyReleased","keyTyped","print","println","save","saveFrame","day","hour","millis","minute","month","second","year","background","clear","colorMode","fill","noFill","noStroke","stroke","alpha","blue","brightness","color","green","hue","lerpColor","red","saturation","modelX","modelY","modelZ","screenX","screenY","screenZ","ambient","emissive","shininess","specular","add","createImage","beginCamera","camera","endCamera","frustum","ortho","perspective","printCamera","printProjection","cursor","frameRate","noCursor","exit","loop","noLoop","popStyle","pushStyle","redraw","binary","boolean","byte","char","float","hex","int","str","unbinary","unhex","join","match","matchAll","nf","nfc","nfp","nfs","split","splitTokens","trim","append","arrayCopy","concat","expand","reverse","shorten","sort","splice","subset","box","sphere","sphereDetail","createInput","createReader","loadBytes","loadJSONArray","loadJSONObject","loadStrings","loadTable","loadXML","open","parseXML","saveTable","selectFolder","selectInput","beginRaw","beginRecord","createOutput","createWriter","endRaw","endRecord","PrintWritersaveBytes","saveJSONArray","saveJSONObject","saveStream","saveStrings","saveXML","selectOutput","popMatrix","printMatrix","pushMatrix","resetMatrix","rotate","rotateX","rotateY","rotateZ","scale","shearX","shearY","translate","ambientLight","directionalLight","lightFalloff","lights","lightSpecular","noLights","normal","pointLight","spotLight","image","imageMode","loadImage","noTint","requestImage","tint","texture","textureMode","textureWrap","blend","copy","filter","get","loadPixels","set","updatePixels","blendMode","loadShader","PShaderresetShader","shader","createFont","loadFont","text","textFont","textAlign","textLeading","textMode","textSize","textWidth","textAscent","textDescent","abs","ceil","constrain","dist","exp","floor","lerp","log","mag","map","max","min","norm","pow","round","sq","sqrt","acos","asin","atan","atan2","cos","degrees","radians","sin","tan","noise","noiseDetail","noiseSeed","random","randomGaussian","randomSeed"],n=e.IDENT_RE,a={variants:[{match:t.concat(t.either(...r),t.lookahead(/\s*\(/)),className:"built_in"},{relevance:0,match:t.concat(/\b(?!for|if|while)/,n,t.lookahead(/\s*\(/)),className:"title.function"}]},i={match:[/new\s+/,n],className:{1:"keyword",2:"class.title"}},o={relevance:0,match:[/\./,n],className:{2:"property"}},s={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,n]},{match:[/class/,/\s+/,n]}],className:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}};return{name:"Processing",aliases:["pde"],keywords:{keyword:["abstract","assert","break","case","catch","const","continue","default","else","enum","final","finally","for","if","import","instanceof","long","native","new","package","private","private","protected","protected","public","public","return","static","strictfp","switch","synchronized","throw","throws","transient","try","void","volatile","while"],literal:"P2D P3D HALF_PI PI QUARTER_PI TAU TWO_PI null true false",title:"setup draw",variable:"super this",built_in:[...r,"BufferedReader","PVector","PFont","PImage","PGraphics","HashMap","String","Array","FloatDict","ArrayList","FloatList","IntDict","IntList","JSONArray","JSONObject","Object","StringDict","StringList","Table","TableRow","XML"],type:["boolean","byte","char","color","double","float","int","long","short"]},contains:[s,i,a,o,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE]}}),Mg)),zf.registerLanguage("profile",(Pg||(Pg=1,Lg=function(e){return{name:"Python profiler",contains:[e.C_NUMBER_MODE,{begin:"[a-zA-Z_][\\da-zA-Z_]+\\.[\\da-zA-Z_]{1,3}",end:":",excludeEnd:!0},{begin:"(ncalls|tottime|cumtime)",end:"$",keywords:"ncalls tottime|10 cumtime|10 filename",relevance:10},{begin:"function calls",end:"$",contains:[e.C_NUMBER_MODE],relevance:10},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:"\\(",end:"\\)$",excludeBegin:!0,excludeEnd:!0,relevance:0}]}}),Lg)),zf.registerLanguage("prolog",(Bg||(Bg=1,Fg=function(e){const t={begin:/\(/,end:/\)/,relevance:0},r={begin:/\[/,end:/\]/},n={className:"comment",begin:/%/,end:/$/,contains:[e.PHRASAL_WORDS_MODE]},a={className:"string",begin:/`/,end:/`/,contains:[e.BACKSLASH_ESCAPE]},i=[{begin:/[a-z][A-Za-z0-9_]*/,relevance:0},{className:"symbol",variants:[{begin:/[A-Z][a-zA-Z0-9_]*/},{begin:/_[A-Za-z0-9_]*/}],relevance:0},t,{begin:/:-/},r,n,e.C_BLOCK_COMMENT_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,a,{className:"string",begin:/0'(\\'|.)/},{className:"string",begin:/0'\\s/},e.C_NUMBER_MODE];return t.contains=i,r.contains=i,{name:"Prolog",contains:i.concat([{begin:/\.$/}])}}),Fg)),zf.registerLanguage("properties",(Gg||(Gg=1,Ug=function(e){const t="[ \\t\\f]*",r=t+"[:=]"+t,n="[ \\t\\f]+",a="([^\\\\:= \\t\\f\\n]|\\\\.)+",i={end:"("+r+"|"+n+")",relevance:0,starts:{className:"string",end:/$/,relevance:0,contains:[{begin:"\\\\\\\\"},{begin:"\\\\\\n"}]}};return{name:".properties",disableAutodetect:!0,case_insensitive:!0,illegal:/\S/,contains:[e.COMMENT("^\\s*[!#]","$"),{returnBegin:!0,variants:[{begin:a+r},{begin:a+n}],contains:[{className:"attr",begin:a,endsParent:!0}],starts:i},{className:"attr",begin:a+t+"$"}]}}),Ug)),zf.registerLanguage("protobuf",(Yg||(Yg=1,zg=function(e){const t={match:[/(message|enum|service)\s+/,e.IDENT_RE],scope:{1:"keyword",2:"title.class"}};return{name:"Protocol Buffers",aliases:["proto"],keywords:{keyword:["package","import","option","optional","required","repeated","group","oneof"],type:["double","float","int32","int64","uint32","uint64","sint32","sint64","fixed32","fixed64","sfixed32","sfixed64","bool","string","bytes"],literal:["true","false"]},contains:[e.QUOTE_STRING_MODE,e.NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t,{className:"function",beginKeywords:"rpc",end:/[{;]/,excludeEnd:!0,keywords:"rpc returns"},{begin:/^\s*[A-Z_]+(?=\s*=[^\n]+;$)/}]}}),zg)),zf.registerLanguage("puppet",(Hg||(Hg=1,qg=function(e){const t=e.COMMENT("#","$"),r="([A-Za-z_]|::)(\\w|::)*",n=e.inherit(e.TITLE_MODE,{begin:r}),a={className:"variable",begin:"\\$"+r},i={className:"string",contains:[e.BACKSLASH_ESCAPE,a],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/}]};return{name:"Puppet",aliases:["pp"],contains:[t,a,i,{beginKeywords:"class",end:"\\{|;",illegal:/=/,contains:[n,t]},{beginKeywords:"define",end:/\{/,contains:[{className:"section",begin:e.IDENT_RE,endsParent:!0}]},{begin:e.IDENT_RE+"\\s+\\{",returnBegin:!0,end:/\S/,contains:[{className:"keyword",begin:e.IDENT_RE,relevance:.2},{begin:/\{/,end:/\}/,keywords:{keyword:"and case default else elsif false if in import enherits node or true undef unless main settings $string ",literal:"alias audit before loglevel noop require subscribe tag owner ensure group mode name|0 changes context force incl lens load_path onlyif provider returns root show_diff type_check en_address ip_address realname command environment hour monute month monthday special target weekday creates cwd ogoutput refresh refreshonly tries try_sleep umask backup checksum content ctime force ignore links mtime purge recurse recurselimit replace selinux_ignore_defaults selrange selrole seltype seluser source souirce_permissions sourceselect validate_cmd validate_replacement allowdupe attribute_membership auth_membership forcelocal gid ia_load_module members system host_aliases ip allowed_trunk_vlans description device_url duplex encapsulation etherchannel native_vlan speed principals allow_root auth_class auth_type authenticate_user k_of_n mechanisms rule session_owner shared options device fstype enable hasrestart directory present absent link atboot blockdevice device dump pass remounts poller_tag use message withpath adminfile allow_virtual allowcdrom category configfiles flavor install_options instance package_settings platform responsefile status uninstall_options vendor unless_system_user unless_uid binary control flags hasstatus manifest pattern restart running start stop allowdupe auths expiry gid groups home iterations key_membership keys managehome membership password password_max_age password_min_age profile_membership profiles project purge_ssh_keys role_membership roles salt shell uid baseurl cost descr enabled enablegroups exclude failovermethod gpgcheck gpgkey http_caching include includepkgs keepalive metadata_expire metalink mirrorlist priority protect proxy proxy_password proxy_username repo_gpgcheck s3_enabled skip_if_unavailable sslcacert sslclientcert sslclientkey sslverify mounted",built_in:"architecture augeasversion blockdevices boardmanufacturer boardproductname boardserialnumber cfkey dhcp_servers domain ec2_ ec2_userdata facterversion filesystems ldom fqdn gid hardwareisa hardwaremodel hostname id|0 interfaces ipaddress ipaddress_ ipaddress6 ipaddress6_ iphostnumber is_virtual kernel kernelmajversion kernelrelease kernelversion kernelrelease kernelversion lsbdistcodename lsbdistdescription lsbdistid lsbdistrelease lsbmajdistrelease lsbminordistrelease lsbrelease macaddress macaddress_ macosx_buildversion macosx_productname macosx_productversion macosx_productverson_major macosx_productversion_minor manufacturer memoryfree memorysize netmask metmask_ network_ operatingsystem operatingsystemmajrelease operatingsystemrelease osfamily partitions path physicalprocessorcount processor processorcount productname ps puppetversion rubysitedir rubyversion selinux selinux_config_mode selinux_config_policy selinux_current_mode selinux_current_mode selinux_enforced selinux_policyversion serialnumber sp_ sshdsakey sshecdsakey sshrsakey swapencrypted swapfree swapsize timezone type uniqueid uptime uptime_days uptime_hours uptime_seconds uuid virtual vlans xendomains zfs_version zonenae zones zpool_version"},relevance:0,contains:[i,t,{begin:"[a-zA-Z_]+\\s*=>",returnBegin:!0,end:"=>",contains:[{className:"attr",begin:e.IDENT_RE}]},{className:"number",begin:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",relevance:0},a]}],relevance:0}]}}),qg)),zf.registerLanguage("purebasic",($g||($g=1,Vg=function(e){return{name:"PureBASIC",aliases:["pb","pbi"],keywords:"Align And Array As Break CallDebugger Case CompilerCase CompilerDefault CompilerElse CompilerElseIf CompilerEndIf CompilerEndSelect CompilerError CompilerIf CompilerSelect CompilerWarning Continue Data DataSection Debug DebugLevel Declare DeclareC DeclareCDLL DeclareDLL DeclareModule Default Define Dim DisableASM DisableDebugger DisableExplicit Else ElseIf EnableASM EnableDebugger EnableExplicit End EndDataSection EndDeclareModule EndEnumeration EndIf EndImport EndInterface EndMacro EndModule EndProcedure EndSelect EndStructure EndStructureUnion EndWith Enumeration EnumerationBinary Extends FakeReturn For ForEach ForEver Global Gosub Goto If Import ImportC IncludeBinary IncludeFile IncludePath Interface List Macro MacroExpandedCount Map Module NewList NewMap Next Not Or Procedure ProcedureC ProcedureCDLL ProcedureDLL ProcedureReturn Protected Prototype PrototypeC ReDim Read Repeat Restore Return Runtime Select Shared Static Step Structure StructureUnion Swap Threaded To UndefineMacro Until Until UnuseModule UseModule Wend While With XIncludeFile XOr",contains:[e.COMMENT(";","$",{relevance:0}),{className:"function",begin:"\\b(Procedure|Declare)(C|CDLL|DLL)?\\b",end:"\\(",excludeEnd:!0,returnBegin:!0,contains:[{className:"keyword",begin:"(Procedure|Declare)(C|CDLL|DLL)?",excludeEnd:!0},{className:"type",begin:"\\.\\w*"},e.UNDERSCORE_TITLE_MODE]},{className:"string",begin:'(~)?"',end:'"',illegal:"\\n"},{className:"symbol",begin:"#[a-zA-Z_]\\w*\\$?"}]}}),Vg)),zf.registerLanguage("python",(jg||(jg=1,Wg=function(e){const t=e.regex,r=/[\p{XID_Start}_]\p{XID_Continue}*/u,n=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],a={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:n,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},i={className:"meta",begin:/^(>>>|\.\.\.) /},o={className:"subst",begin:/\{/,end:/\}/,keywords:a,illegal:/#/},s={begin:/\{\{/,relevance:0},l={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,i],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,i],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,i,s,o]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,i,s,o]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,s,o]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,o]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},c="[0-9](_?[0-9])*",d=`(\\b(${c}))?\\.(${c})|\\b(${c})\\.`,u=`\\b|${n.join("|")}`,p={className:"number",relevance:0,variants:[{begin:`(\\b(${c})|(${d}))[eE][+-]?(${c})[jJ]?(?=${u})`},{begin:`(${d})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${u})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${u})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${u})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${u})`},{begin:`\\b(${c})[jJ](?=${u})`}]},_={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:a,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},m={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:a,contains:["self",i,p,l,e.HASH_COMMENT_MODE]}]};return o.contains=[l,p,i],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:a,illegal:/(<\/|\?)|=>/,contains:[i,p,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},l,_,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,r],scope:{1:"keyword",3:"title.function"},contains:[m]},{variants:[{match:[/\bclass/,/\s+/,r,/\s*/,/\(\s*/,r,/\s*\)/]},{match:[/\bclass/,/\s+/,r]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[p,m,l]}]}}),Wg)),zf.registerLanguage("python-repl",Kg?Qg:(Kg=1,Qg=function(e){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}})),zf.registerLanguage("q",(Zg||(Zg=1,Xg=function(e){return{name:"Q",aliases:["k","kdb"],keywords:{$pattern:/(`?)[A-Za-z0-9_]+\b/,keyword:"do while select delete by update from",literal:"0b 1b",built_in:"neg not null string reciprocal floor ceiling signum mod xbar xlog and or each scan over prior mmu lsq inv md5 ltime gtime count first var dev med cov cor all any rand sums prds mins maxs fills deltas ratios avgs differ prev next rank reverse iasc idesc asc desc msum mcount mavg mdev xrank mmin mmax xprev rotate distinct group where flip type key til get value attr cut set upsert raze union inter except cross sv vs sublist enlist read0 read1 hopen hclose hdel hsym hcount peach system ltrim rtrim trim lower upper ssr view tables views cols xcols keys xkey xcol xasc xdesc fkeys meta lj aj aj0 ij pj asof uj ww wj wj1 fby xgroup ungroup ej save load rsave rload show csv parse eval min max avg wavg wsum sin cos tan sum",type:"`float `double int `timestamp `timespan `datetime `time `boolean `symbol `char `byte `short `long `real `month `date `minute `second `guid"},contains:[e.C_LINE_COMMENT_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE]}}),Xg)),zf.registerLanguage("qml",(eh||(eh=1,Jg=function(e){const t="[a-zA-Z_][a-zA-Z0-9\\._]*",r={className:"attribute",begin:"\\bid\\s*:",starts:{className:"string",end:t,returnEnd:!1}},n={begin:t+"\\s*:",returnBegin:!0,contains:[{className:"attribute",begin:t,end:"\\s*:",excludeEnd:!0,relevance:0}],relevance:0},a={begin:e.regex.concat(t,/\s*\{/),end:/\{/,returnBegin:!0,relevance:0,contains:[e.inherit(e.TITLE_MODE,{begin:t})]};return{name:"QML",aliases:["qt"],case_insensitive:!1,keywords:{keyword:"in of on if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await import",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Behavior bool color coordinate date double enumeration font geocircle georectangle geoshape int list matrix4x4 parent point quaternion real rect size string url variant vector2d vector3d vector4d Promise"},contains:[{className:"meta",begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,{className:"subst",begin:"\\$\\{",end:"\\}"}]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"number",variants:[{begin:"\\b(0[bB][01]+)"},{begin:"\\b(0[oO][0-7]+)"},{begin:e.C_NUMBER_RE}],relevance:0},{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.REGEXP_MODE,{begin:/</,end:/>\s*[);\]]/,relevance:0,subLanguage:"xml"}],relevance:0},{className:"keyword",begin:"\\bsignal\\b",starts:{className:"string",end:"(\\(|:|=|;|,|//|/\\*|$)",returnEnd:!0}},{className:"keyword",begin:"\\bproperty\\b",starts:{className:"string",end:"(:|=|;|,|//|/\\*|$)",returnEnd:!0}},{className:"function",beginKeywords:"function",end:/\{/,excludeEnd:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/[A-Za-z$_][0-9A-Za-z$_]*/}),{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]}],illegal:/\[|%/},{begin:"\\."+e.IDENT_RE,relevance:0},r,n,a],illegal:/#/}}),Jg)),zf.registerLanguage("r",(rh||(rh=1,th=function(e){const t=e.regex,r=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,n=t.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),a=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,i=t.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/);return{name:"R",keywords:{$pattern:r,keyword:"function if in break next repeat else for while",literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/,starts:{end:t.lookahead(t.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)),endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{scope:"variable",variants:[{match:r},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}]}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"',relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{1:"operator",2:"number"},match:[a,n]},{scope:{1:"operator",2:"number"},match:[/%[^%]*%/,n]},{scope:{1:"punctuation",2:"number"},match:[i,n]},{scope:{2:"number"},match:[/[^a-zA-Z0-9._]|^/,n]}]},{scope:{3:"operator"},match:[r,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:a},{match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:i},{begin:"`",end:"`",contains:[{begin:/\\./}]}]}}),th)),zf.registerLanguage("reasonml",(ah||(ah=1,nh=function(e){return{name:"ReasonML",aliases:["re"],keywords:{$pattern:/[a-z_]\w*!?/,keyword:["and","as","asr","assert","begin","class","constraint","do","done","downto","else","end","esfun","exception","external","for","fun","function","functor","if","in","include","inherit","initializer","land","lazy","let","lor","lsl","lsr","lxor","mod","module","mutable","new","nonrec","object","of","open","or","pri","pub","rec","sig","struct","switch","then","to","try","type","val","virtual","when","while","with"],built_in:["array","bool","bytes","char","exn|5","float","int","int32","int64","list","lazy_t|5","nativeint|5","ref","string","unit"],literal:["true","false"]},illegal:/(:-|:=|\$\{|\+=)/,contains:[{scope:"literal",match:/\[(\|\|)?\]|\(\)/,relevance:0},e.C_LINE_COMMENT_MODE,e.COMMENT(/\/\*/,/\*\//,{illegal:/^(#,\/\/)/}),{scope:"symbol",match:/\'[A-Za-z_](?!\')[\w\']*/},{scope:"type",match:/`[A-Z][\w\']*/},{scope:"type",match:/\b[A-Z][\w\']*/,relevance:0},{match:/[a-z_]\w*\'[\w\']*/,relevance:0},{scope:"operator",match:/\s+(\|\||\+[\+\.]?|\*[\*\/\.]?|\/[\.]?|\.\.\.|\|>|&&|===?)\s+/,relevance:0},e.inherit(e.APOS_STRING_MODE,{scope:"string",relevance:0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),{scope:"number",variants:[{match:/\b0[xX][a-fA-F0-9_]+[Lln]?/},{match:/\b0[oO][0-7_]+[Lln]?/},{match:/\b0[bB][01_]+[Lln]?/},{match:/\b[0-9][0-9_]*([Lln]|(\.[0-9_]*)?([eE][-+]?[0-9_]+)?)/}],relevance:0}]}}),nh)),zf.registerLanguage("rib",(oh||(oh=1,ih=function(e){return{name:"RenderMan RIB",keywords:"ArchiveRecord AreaLightSource Atmosphere Attribute AttributeBegin AttributeEnd Basis Begin Blobby Bound Clipping ClippingPlane Color ColorSamples ConcatTransform Cone CoordinateSystem CoordSysTransform CropWindow Curves Cylinder DepthOfField Detail DetailRange Disk Displacement Display End ErrorHandler Exposure Exterior Format FrameAspectRatio FrameBegin FrameEnd GeneralPolygon GeometricApproximation Geometry Hider Hyperboloid Identity Illuminate Imager Interior LightSource MakeCubeFaceEnvironment MakeLatLongEnvironment MakeShadow MakeTexture Matte MotionBegin MotionEnd NuPatch ObjectBegin ObjectEnd ObjectInstance Opacity Option Orientation Paraboloid Patch PatchMesh Perspective PixelFilter PixelSamples PixelVariance Points PointsGeneralPolygons PointsPolygons Polygon Procedural Projection Quantize ReadArchive RelativeDetail ReverseOrientation Rotate Scale ScreenWindow ShadingInterpolation ShadingRate Shutter Sides Skew SolidBegin SolidEnd Sphere SubdivisionMesh Surface TextureCoordinates Torus Transform TransformBegin TransformEnd TransformPoints Translate TrimCurve WorldBegin WorldEnd",illegal:"</",contains:[e.HASH_COMMENT_MODE,e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]}}),ih)),zf.registerLanguage("roboconf",(lh||(lh=1,sh=function(e){const t="[a-zA-Z-_][^\\n{]+\\{",r={className:"attribute",begin:/[a-zA-Z-_]+/,end:/\s*:/,excludeEnd:!0,starts:{end:";",relevance:0,contains:[{className:"variable",begin:/\.[a-zA-Z-_]+/},{className:"keyword",begin:/\(optional\)/}]}};return{name:"Roboconf",aliases:["graph","instances"],case_insensitive:!0,keywords:"import",contains:[{begin:"^facet "+t,end:/\}/,keywords:"facet",contains:[r,e.HASH_COMMENT_MODE]},{begin:"^\\s*instance of "+t,end:/\}/,keywords:"name count channels instance-data instance-state instance of",illegal:/\S/,contains:["self",r,e.HASH_COMMENT_MODE]},{begin:"^"+t,end:/\}/,contains:[r,e.HASH_COMMENT_MODE]},e.HASH_COMMENT_MODE]}}),sh)),zf.registerLanguage("routeros",(dh||(dh=1,ch=function(e){const t="foreach do while for if from to step else on-error and or not in",r="true false yes no nothing nil null",n={className:"variable",variants:[{begin:/\$[\w\d#@][\w\d_]*/},{begin:/\$\{(.*?)\}/}]},a={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,{className:"variable",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]}]},i={className:"string",begin:/'/,end:/'/};return{name:"MikroTik RouterOS script",aliases:["mikrotik"],case_insensitive:!0,keywords:{$pattern:/:?[\w-]+/,literal:r,keyword:t+" :"+t.split(" ").join(" :")+" :"+"global local beep delay put len typeof pick log time set find environment terminal error execute parse resolve toarray tobool toid toip toip6 tonum tostr totime".split(" ").join(" :")},contains:[{variants:[{begin:/\/\*/,end:/\*\//},{begin:/\/\//,end:/$/},{begin:/<\//,end:/>/}],illegal:/./},e.COMMENT("^#","$"),a,i,n,{begin:/[\w-]+=([^\s{}[\]()>]+)/,relevance:0,returnBegin:!0,contains:[{className:"attribute",begin:/[^=]+/},{begin:/=/,endsWithParent:!0,relevance:0,contains:[a,i,n,{className:"literal",begin:"\\b("+r.split(" ").join("|")+")\\b"},{begin:/("[^"]*"|[^\s{}[\]]+)/}]}]},{className:"number",begin:/\*[0-9a-fA-F]+/},{begin:"\\b("+"add remove enable disable set get print export edit find run debug error info warning".split(" ").join("|")+")([\\s[(\\]|])",returnBegin:!0,contains:[{className:"built_in",begin:/\w+/}]},{className:"built_in",variants:[{begin:"(\\.\\./|/|\\s)(("+"traffic-flow traffic-generator firewall scheduler aaa accounting address-list address align area bandwidth-server bfd bgp bridge client clock community config connection console customer default dhcp-client dhcp-server discovery dns e-mail ethernet filter firmware gps graphing group hardware health hotspot identity igmp-proxy incoming instance interface ip ipsec ipv6 irq l2tp-server lcd ldp logging mac-server mac-winbox mangle manual mirror mme mpls nat nd neighbor network note ntp ospf ospf-v3 ovpn-server page peer pim ping policy pool port ppp pppoe-client pptp-server prefix profile proposal proxy queue radius resource rip ripng route routing screen script security-profiles server service service-port settings shares smb sms sniffer snmp snooper socks sstp-server system tool tracking type upgrade upnp user-manager users user vlan secret vrrp watchdog web-access wireless pptp pppoe lan wan layer7-protocol lease simple raw".split(" ").join("|")+");?\\s)+"},{begin:/\.\./,relevance:0}]}]}}),ch)),zf.registerLanguage("rsl",(ph||(ph=1,uh=function(e){const t={match:[/(surface|displacement|light|volume|imager)/,/\s+/,e.IDENT_RE],scope:{1:"keyword",3:"title.class"}};return{name:"RenderMan RSL",keywords:{keyword:["while","for","if","do","return","else","break","extern","continue"],built_in:["abs","acos","ambient","area","asin","atan","atmosphere","attribute","calculatenormal","ceil","cellnoise","clamp","comp","concat","cos","degrees","depth","Deriv","diffuse","distance","Du","Dv","environment","exp","faceforward","filterstep","floor","format","fresnel","incident","length","lightsource","log","match","max","min","mod","noise","normalize","ntransform","opposite","option","phong","pnoise","pow","printf","ptlined","radians","random","reflect","refract","renderinfo","round","setcomp","setxcomp","setycomp","setzcomp","shadow","sign","sin","smoothstep","specular","specularbrdf","spline","sqrt","step","tan","texture","textureinfo","trace","transform","vtransform","xcomp","ycomp","zcomp"],type:["matrix","float","color","point","normal","vector"]},illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,e.C_NUMBER_MODE,{className:"meta",begin:"#",end:"$"},t,{beginKeywords:"illuminate illuminance gather",end:"\\("}]}}),uh)),zf.registerLanguage("ruleslanguage",(mh||(mh=1,_h=function(e){return{name:"Oracle Rules Language",keywords:{keyword:"BILL_PERIOD BILL_START BILL_STOP RS_EFFECTIVE_START RS_EFFECTIVE_STOP RS_JURIS_CODE RS_OPCO_CODE INTDADDATTRIBUTE|5 INTDADDVMSG|5 INTDBLOCKOP|5 INTDBLOCKOPNA|5 INTDCLOSE|5 INTDCOUNT|5 INTDCOUNTSTATUSCODE|5 INTDCREATEMASK|5 INTDCREATEDAYMASK|5 INTDCREATEFACTORMASK|5 INTDCREATEHANDLE|5 INTDCREATEOVERRIDEDAYMASK|5 INTDCREATEOVERRIDEMASK|5 INTDCREATESTATUSCODEMASK|5 INTDCREATETOUPERIOD|5 INTDDELETE|5 INTDDIPTEST|5 INTDEXPORT|5 INTDGETERRORCODE|5 INTDGETERRORMESSAGE|5 INTDISEQUAL|5 INTDJOIN|5 INTDLOAD|5 INTDLOADACTUALCUT|5 INTDLOADDATES|5 INTDLOADHIST|5 INTDLOADLIST|5 INTDLOADLISTDATES|5 INTDLOADLISTENERGY|5 INTDLOADLISTHIST|5 INTDLOADRELATEDCHANNEL|5 INTDLOADSP|5 INTDLOADSTAGING|5 INTDLOADUOM|5 INTDLOADUOMDATES|5 INTDLOADUOMHIST|5 INTDLOADVERSION|5 INTDOPEN|5 INTDREADFIRST|5 INTDREADNEXT|5 INTDRECCOUNT|5 INTDRELEASE|5 INTDREPLACE|5 INTDROLLAVG|5 INTDROLLPEAK|5 INTDSCALAROP|5 INTDSCALE|5 INTDSETATTRIBUTE|5 INTDSETDSTPARTICIPANT|5 INTDSETSTRING|5 INTDSETVALUE|5 INTDSETVALUESTATUS|5 INTDSHIFTSTARTTIME|5 INTDSMOOTH|5 INTDSORT|5 INTDSPIKETEST|5 INTDSUBSET|5 INTDTOU|5 INTDTOURELEASE|5 INTDTOUVALUE|5 INTDUPDATESTATS|5 INTDVALUE|5 STDEV INTDDELETEEX|5 INTDLOADEXACTUAL|5 INTDLOADEXCUT|5 INTDLOADEXDATES|5 INTDLOADEX|5 INTDLOADEXRELATEDCHANNEL|5 INTDSAVEEX|5 MVLOAD|5 MVLOADACCT|5 MVLOADACCTDATES|5 MVLOADACCTHIST|5 MVLOADDATES|5 MVLOADHIST|5 MVLOADLIST|5 MVLOADLISTDATES|5 MVLOADLISTHIST|5 IF FOR NEXT DONE SELECT END CALL ABORT CLEAR CHANNEL FACTOR LIST NUMBER OVERRIDE SET WEEK DISTRIBUTIONNODE ELSE WHEN THEN OTHERWISE IENUM CSV INCLUDE LEAVE RIDER SAVE DELETE NOVALUE SECTION WARN SAVE_UPDATE DETERMINANT LABEL REPORT REVENUE EACH IN FROM TOTAL CHARGE BLOCK AND OR CSV_FILE RATE_CODE AUXILIARY_DEMAND UIDACCOUNT RS BILL_PERIOD_SELECT HOURS_PER_MONTH INTD_ERROR_STOP SEASON_SCHEDULE_NAME ACCOUNTFACTOR ARRAYUPPERBOUND CALLSTOREDPROC GETADOCONNECTION GETCONNECT GETDATASOURCE GETQUALIFIER GETUSERID HASVALUE LISTCOUNT LISTOP LISTUPDATE LISTVALUE PRORATEFACTOR RSPRORATE SETBINPATH SETDBMONITOR WQ_OPEN BILLINGHOURS DATE DATEFROMFLOAT DATETIMEFROMSTRING DATETIMETOSTRING DATETOFLOAT DAY DAYDIFF DAYNAME DBDATETIME HOUR MINUTE MONTH MONTHDIFF MONTHHOURS MONTHNAME ROUNDDATE SAMEWEEKDAYLASTYEAR SECOND WEEKDAY WEEKDIFF YEAR YEARDAY YEARSTR COMPSUM HISTCOUNT HISTMAX HISTMIN HISTMINNZ HISTVALUE MAXNRANGE MAXRANGE MINRANGE COMPIKVA COMPKVA COMPKVARFROMKQKW COMPLF IDATTR FLAG LF2KW LF2KWH MAXKW POWERFACTOR READING2USAGE AVGSEASON MAXSEASON MONTHLYMERGE SEASONVALUE SUMSEASON ACCTREADDATES ACCTTABLELOAD CONFIGADD CONFIGGET CREATEOBJECT CREATEREPORT EMAILCLIENT EXPBLKMDMUSAGE EXPMDMUSAGE EXPORT_USAGE FACTORINEFFECT GETUSERSPECIFIEDSTOP INEFFECT ISHOLIDAY RUNRATE SAVE_PROFILE SETREPORTTITLE USEREXIT WATFORRUNRATE TO TABLE ACOS ASIN ATAN ATAN2 BITAND CEIL COS COSECANT COSH COTANGENT DIVQUOT DIVREM EXP FABS FLOOR FMOD FREPM FREXPN LOG LOG10 MAX MAXN MIN MINNZ MODF POW ROUND ROUND2VALUE ROUNDINT SECANT SIN SINH SQROOT TAN TANH FLOAT2STRING FLOAT2STRINGNC INSTR LEFT LEN LTRIM MID RIGHT RTRIM STRING STRINGNC TOLOWER TOUPPER TRIM NUMDAYS READ_DATE STAGING",built_in:"IDENTIFIER OPTIONS XML_ELEMENT XML_OP XML_ELEMENT_OF DOMDOCCREATE DOMDOCLOADFILE DOMDOCLOADXML DOMDOCSAVEFILE DOMDOCGETROOT DOMDOCADDPI DOMNODEGETNAME DOMNODEGETTYPE DOMNODEGETVALUE DOMNODEGETCHILDCT DOMNODEGETFIRSTCHILD DOMNODEGETSIBLING DOMNODECREATECHILDELEMENT DOMNODESETATTRIBUTE DOMNODEGETCHILDELEMENTCT DOMNODEGETFIRSTCHILDELEMENT DOMNODEGETSIBLINGELEMENT DOMNODEGETATTRIBUTECT DOMNODEGETATTRIBUTEI DOMNODEGETATTRIBUTEBYNAME DOMNODEGETBYNAME"},contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,{className:"literal",variants:[{begin:"#\\s+",relevance:0},{begin:"#[a-zA-Z .]+"}]}]}}),_h)),zf.registerLanguage("rust",(hh||(hh=1,gh=function(e){const t=e.regex,r=/(r#)?/,n=t.concat(r,e.UNDERSCORE_IDENT_RE),a=t.concat(r,e.IDENT_RE),i={className:"title.function.invoke",relevance:0,begin:t.concat(/\b/,/(?!let|for|while|if|else|match\b)/,a,t.lookahead(/\s*\(/))},o="([ui](8|16|32|64|128|size)|f(32|64))?",s=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],l=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:l,keyword:["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],literal:["true","false","Some","None","Ok","Err"],built_in:s},illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.COMMENT("/\\*","\\*/",{contains:["self"]}),e.inherit(e.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+o},{begin:"\\b0o([0-7_]+)"+o},{begin:"\\b0x([A-Fa-f0-9_]+)"+o},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+o}],relevance:0},{begin:[/fn/,/\s+/,n],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,n],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,n,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{begin:e.IDENT_RE+"::",keywords:{keyword:"Self",built_in:s,type:l}},{className:"punctuation",begin:"->"},i]}}),gh)),zf.registerLanguage("sas",(Eh||(Eh=1,fh=function(e){const t=e.regex;return{name:"SAS",case_insensitive:!0,keywords:{literal:["null","missing","_all_","_automatic_","_character_","_infile_","_n_","_name_","_null_","_numeric_","_user_","_webout_"],keyword:["do","if","then","else","end","until","while","abort","array","attrib","by","call","cards","cards4","catname","continue","datalines","datalines4","delete","delim","delimiter","display","dm","drop","endsas","error","file","filename","footnote","format","goto","in","infile","informat","input","keep","label","leave","length","libname","link","list","lostcard","merge","missing","modify","options","output","out","page","put","redirect","remove","rename","replace","retain","return","select","set","skip","startsas","stop","title","update","waitsas","where","window","x|0","systask","add","and","alter","as","cascade","check","create","delete","describe","distinct","drop","foreign","from","group","having","index","insert","into","in","key","like","message","modify","msgtype","not","null","on","or","order","primary","references","reset","restrict","select","set","table","unique","update","validate","view","where"]},contains:[{className:"keyword",begin:/^\s*(proc [\w\d_]+|data|run|quit)[\s;]/},{className:"variable",begin:/&[a-zA-Z_&][a-zA-Z0-9_]*\.?/},{begin:[/^\s*/,/datalines;|cards;/,/(?:.*\n)+/,/^\s*;\s*$/],className:{2:"keyword",3:"string"}},{begin:[/%mend|%macro/,/\s+/,/[a-zA-Z_&][a-zA-Z0-9_]*/],className:{1:"built_in",3:"title.function"}},{className:"built_in",begin:"%"+t.either("bquote","nrbquote","cmpres","qcmpres","compstor","datatyp","display","do","else","end","eval","global","goto","if","index","input","keydef","label","left","length","let","local","lowcase","macro","mend","nrbquote","nrquote","nrstr","put","qcmpres","qleft","qlowcase","qscan","qsubstr","qsysfunc","qtrim","quote","qupcase","scan","str","substr","superq","syscall","sysevalf","sysexec","sysfunc","sysget","syslput","sysprod","sysrc","sysrput","then","to","trim","unquote","until","upcase","verify","while","window")},{className:"title.function",begin:/%[a-zA-Z_][a-zA-Z_0-9]*/},{className:"meta",begin:t.either("abs","addr","airy","arcos","arsin","atan","attrc","attrn","band","betainv","blshift","bnot","bor","brshift","bxor","byte","cdf","ceil","cexist","cinv","close","cnonct","collate","compbl","compound","compress","cos","cosh","css","curobs","cv","daccdb","daccdbsl","daccsl","daccsyd","dacctab","dairy","date","datejul","datepart","datetime","day","dclose","depdb","depdbsl","depdbsl","depsl","depsl","depsyd","depsyd","deptab","deptab","dequote","dhms","dif","digamma","dim","dinfo","dnum","dopen","doptname","doptnum","dread","dropnote","dsname","erf","erfc","exist","exp","fappend","fclose","fcol","fdelete","fetch","fetchobs","fexist","fget","fileexist","filename","fileref","finfo","finv","fipname","fipnamel","fipstate","floor","fnonct","fnote","fopen","foptname","foptnum","fpoint","fpos","fput","fread","frewind","frlen","fsep","fuzz","fwrite","gaminv","gamma","getoption","getvarc","getvarn","hbound","hms","hosthelp","hour","ibessel","index","indexc","indexw","input","inputc","inputn","int","intck","intnx","intrr","irr","jbessel","juldate","kurtosis","lag","lbound","left","length","lgamma","libname","libref","log","log10","log2","logpdf","logpmf","logsdf","lowcase","max","mdy","mean","min","minute","mod","month","mopen","mort","n","netpv","nmiss","normal","note","npv","open","ordinal","pathname","pdf","peek","peekc","pmf","point","poisson","poke","probbeta","probbnml","probchi","probf","probgam","probhypr","probit","probnegb","probnorm","probt","put","putc","putn","qtr","quote","ranbin","rancau","ranexp","rangam","range","rank","rannor","ranpoi","rantbl","rantri","ranuni","repeat","resolve","reverse","rewind","right","round","saving","scan","sdf","second","sign","sin","sinh","skewness","soundex","spedis","sqrt","std","stderr","stfips","stname","stnamel","substr","sum","symget","sysget","sysmsg","sysprod","sysrc","system","tan","tanh","time","timepart","tinv","tnonct","today","translate","tranwrd","trigamma","trim","trimn","trunc","uniform","upcase","uss","var","varfmt","varinfmt","varlabel","varlen","varname","varnum","varray","varrayx","vartype","verify","vformat","vformatd","vformatdx","vformatn","vformatnx","vformatw","vformatwx","vformatx","vinarray","vinarrayx","vinformat","vinformatd","vinformatdx","vinformatn","vinformatnx","vinformatw","vinformatwx","vinformatx","vlabel","vlabelx","vlength","vlengthx","vname","vnamex","vtype","vtypex","weekday","year","yyq","zipfips","zipname","zipnamel","zipstate")+"(?=\\()"},{className:"string",variants:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},e.COMMENT("\\*",";"),e.C_BLOCK_COMMENT_MODE]}}),fh)),zf.registerLanguage("scala",(Sh||(Sh=1,bh=function(e){const t=e.regex,r={className:"subst",variants:[{begin:"\\$[A-Za-z0-9_]+"},{begin:/\$\{/,end:/\}/}]},n={className:"string",variants:[{begin:'"""',end:'"""'},{begin:'"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:'[a-z]+"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE,r]},{className:"string",begin:'[a-z]+"""',end:'"""',contains:[r],relevance:10}]},a={className:"type",begin:"\\b[A-Z][A-Za-z0-9_]*",relevance:0},i={className:"title",begin:/[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/,relevance:0},o={className:"class",beginKeywords:"class object trait type",end:/[:={\[\n;]/,excludeEnd:!0,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{beginKeywords:"extends with",relevance:10},{begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[a,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[a,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},i]},s={className:"function",beginKeywords:"def",end:t.lookahead(/[:={\[(\n;]/),contains:[i]};return{name:"Scala",keywords:{literal:"true false null",keyword:"type yield lazy override def with val var sealed abstract private trait object if then forSome for while do throw finally protected extends import final return else break new catch super class case package default try this match continue throws implicit export enum given transparent"},contains:[{begin:["//>",/\s+/,/using/,/\s+/,/\S+/],beginScope:{1:"comment",3:"keyword",5:"type"},end:/$/,contains:[{className:"string",begin:/\S+/}]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,n,a,s,o,e.C_NUMBER_MODE,{begin:[/^\s*/,"extension",/\s+(?=[[(])/],beginScope:{2:"keyword"}},{begin:[/^\s*/,/end/,/\s+/,/(extension\b)?/],beginScope:{2:"keyword",4:"keyword"}},{match:/\.inline\b/},{begin:/\binline(?=\s)/,keywords:"inline"},{begin:[/\(\s*/,/using/,/\s+(?!\))/],beginScope:{2:"keyword"}},{className:"meta",begin:"@[A-Za-z]+"}]}}),bh)),zf.registerLanguage("scheme",(Th||(Th=1,vh=function(e){const t="[^\\(\\)\\[\\]\\{\\}\",'`;#|\\\\\\s]+",r="(-|\\+)?\\d+([./]\\d+)?",n={$pattern:t,built_in:"case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules ' * + , ,@ - ... / ; < <= = => > >= ` abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?"},a={className:"literal",begin:"(#t|#f|#\\\\"+t+"|#\\\\.)"},i={className:"number",variants:[{begin:r,relevance:0},{begin:r+"[+\\-]"+r+"i",relevance:0},{begin:"#b[0-1]+(/[0-1]+)?"},{begin:"#o[0-7]+(/[0-7]+)?"},{begin:"#x[0-9a-f]+(/[0-9a-f]+)?"}]},o=e.QUOTE_STRING_MODE,s=[e.COMMENT(";","$",{relevance:0}),e.COMMENT("#\\|","\\|#")],l={begin:t,relevance:0},c={className:"symbol",begin:"'"+t},d={endsWithParent:!0,relevance:0},u={variants:[{begin:/'/},{begin:"`"}],contains:[{begin:"\\(",end:"\\)",contains:["self",a,o,i,l,c]}]},p={className:"name",relevance:0,begin:t,keywords:n},_={variants:[{begin:"\\(",end:"\\)"},{begin:"\\[",end:"\\]"}],contains:[{begin:/lambda/,endsWithParent:!0,returnBegin:!0,contains:[p,{endsParent:!0,variants:[{begin:/\(/,end:/\)/},{begin:/\[/,end:/\]/}],contains:[l]}]},p,d]};return d.contains=[a,i,o,l,c,u,_].concat(s),{name:"Scheme",aliases:["scm"],illegal:/\S/,contains:[e.SHEBANG(),i,o,c,u,_].concat(s)}}),vh)),zf.registerLanguage("scilab",(Ch||(Ch=1,yh=function(e){const t=[e.C_NUMBER_MODE,{className:"string",begin:"'|\"",end:"'|\"",contains:[e.BACKSLASH_ESCAPE,{begin:"''"}]}];return{name:"Scilab",aliases:["sci"],keywords:{$pattern:/%?\w+/,keyword:"abort break case clear catch continue do elseif else endfunction end for function global if pause return resume select try then while",literal:"%f %F %t %T %pi %eps %inf %nan %e %i %z %s",built_in:"abs and acos asin atan ceil cd chdir clearglobal cosh cos cumprod deff disp error exec execstr exists exp eye gettext floor fprintf fread fsolve imag isdef isempty isinfisnan isvector lasterror length load linspace list listfiles log10 log2 log max min msprintf mclose mopen ones or pathconvert poly printf prod pwd rand real round sinh sin size gsort sprintf sqrt strcat strcmps tring sum system tanh tan type typename warning zeros matrix"},illegal:'("|#|/\\*|\\s+/\\w+)',contains:[{className:"function",beginKeywords:"function",end:"$",contains:[e.UNDERSCORE_TITLE_MODE,{className:"params",begin:"\\(",end:"\\)"}]},{begin:"[a-zA-Z_][a-zA-Z_0-9]*[\\.']+",relevance:0},{begin:"\\[",end:"\\][\\.']*",relevance:0,contains:t},e.COMMENT("//","$")].concat(t)}}),yh)),zf.registerLanguage("scss",function(){if(Rh)return Nh;Rh=1;const e=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],t=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),r=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),n=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),a=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();return Nh=function(i){const o=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(i),s=n,l=r,c="@[a-z-]+",d={className:"variable",begin:"(\\$[a-zA-Z-][a-zA-Z0-9_-]*)\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[i.C_LINE_COMMENT_MODE,i.C_BLOCK_COMMENT_MODE,o.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},o.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+e.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+l.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+s.join("|")+")"},d,{begin:/\(/,end:/\)/,contains:[o.CSS_NUMBER_MODE]},o.CSS_VARIABLE,{className:"attribute",begin:"\\b("+a.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[o.BLOCK_COMMENT,d,o.HEXCOLOR,o.CSS_NUMBER_MODE,i.QUOTE_STRING_MODE,i.APOS_STRING_MODE,o.IMPORTANT,o.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:c,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:t.join(" ")},contains:[{begin:c,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},d,i.QUOTE_STRING_MODE,i.APOS_STRING_MODE,o.HEXCOLOR,o.CSS_NUMBER_MODE]},o.FUNCTION_DISPATCH]}},Nh}()),zf.registerLanguage("shell",Oh?Ah:(Oh=1,Ah=function(e){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}})),zf.registerLanguage("smali",(xh||(xh=1,Ih=function(e){const t=["add","and","cmp","cmpg","cmpl","const","div","double","float","goto","if","int","long","move","mul","neg","new","nop","not","or","rem","return","shl","shr","sput","sub","throw","ushr","xor"];return{name:"Smali",contains:[{className:"string",begin:'"',end:'"',relevance:0},e.COMMENT("#","$",{relevance:0}),{className:"keyword",variants:[{begin:"\\s*\\.end\\s[a-zA-Z0-9]*"},{begin:"^[ ]*\\.[a-zA-Z]*",relevance:0},{begin:"\\s:[a-zA-Z_0-9]*",relevance:0},{begin:"\\s("+["transient","constructor","abstract","final","synthetic","public","private","protected","static","bridge","system"].join("|")+")"}]},{className:"built_in",variants:[{begin:"\\s("+t.join("|")+")\\s"},{begin:"\\s("+t.join("|")+")((-|/)[a-zA-Z0-9]+)+\\s",relevance:10},{begin:"\\s("+["aget","aput","array","check","execute","fill","filled","goto/16","goto/32","iget","instance","invoke","iput","monitor","packed","sget","sparse"].join("|")+")((-|/)[a-zA-Z0-9]+)*\\s",relevance:10}]},{className:"class",begin:"L[^(;:\n]*;",relevance:0},{begin:"[vp][0-9]+"}]}}),Ih)),zf.registerLanguage("smalltalk",(Dh||(Dh=1,wh=function(e){const t="[a-z][a-zA-Z0-9_]*",r={className:"string",begin:"\\$.{1}"},n={className:"symbol",begin:"#"+e.UNDERSCORE_IDENT_RE};return{name:"Smalltalk",aliases:["st"],keywords:["self","super","nil","true","false","thisContext"],contains:[e.COMMENT('"','"'),e.APOS_STRING_MODE,{className:"type",begin:"\\b[A-Z][A-Za-z0-9_]*",relevance:0},{begin:t+":",relevance:0},e.C_NUMBER_MODE,n,r,{begin:"\\|[ ]*"+t+"([ ]+"+t+")*[ ]*\\|",returnBegin:!0,end:/\|/,illegal:/\S/,contains:[{begin:"(\\|[ ]*)?"+t}]},{begin:"#\\(",end:"\\)",contains:[e.APOS_STRING_MODE,r,e.C_NUMBER_MODE,n]}]}}),wh)),zf.registerLanguage("sml",(kh||(kh=1,Mh=function(e){return{name:"SML (Standard ML)",aliases:["ml"],keywords:{$pattern:"[a-z_]\\w*!?",keyword:"abstype and andalso as case datatype do else end eqtype exception fn fun functor handle if in include infix infixr let local nonfix of op open orelse raise rec sharing sig signature struct structure then type val with withtype where while",built_in:"array bool char exn int list option order real ref string substring vector unit word",literal:"true false NONE SOME LESS EQUAL GREATER nil"},illegal:/\/\/|>>/,contains:[{className:"literal",begin:/\[(\|\|)?\]|\(\)/,relevance:0},e.COMMENT("\\(\\*","\\*\\)",{contains:["self"]}),{className:"symbol",begin:"'[A-Za-z_](?!')[\\w']*"},{className:"type",begin:"`[A-Z][\\w']*"},{className:"type",begin:"\\b[A-Z][\\w']*",relevance:0},{begin:"[a-z_]\\w*'[\\w']*"},e.inherit(e.APOS_STRING_MODE,{className:"string",relevance:0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),{className:"number",begin:"\\b(0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)",relevance:0},{begin:/[-=]>/}]}}),Mh)),zf.registerLanguage("sqf",(Ph||(Ph=1,Lh=function(e){const t={className:"string",variants:[{begin:'"',end:'"',contains:[{begin:'""',relevance:0}]},{begin:"'",end:"'",contains:[{begin:"''",relevance:0}]}]},r={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:"define undef ifdef ifndef else endif include if",contains:[{begin:/\\\n/,relevance:0},e.inherit(t,{className:"string"}),{begin:/<[^\n>]*>/,end:/$/,illegal:"\\n"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]};return{name:"SQF",case_insensitive:!0,keywords:{keyword:["break","breakWith","breakOut","breakTo","case","catch","continue","continueWith","default","do","else","exit","exitWith","for","forEach","from","if","local","private","switch","step","then","throw","to","try","waitUntil","while","with"],built_in:["abs","accTime","acos","action","actionIDs","actionKeys","actionKeysEx","actionKeysImages","actionKeysNames","actionKeysNamesArray","actionName","actionParams","activateAddons","activatedAddons","activateKey","activeTitleEffectParams","add3DENConnection","add3DENEventHandler","add3DENLayer","addAction","addBackpack","addBackpackCargo","addBackpackCargoGlobal","addBackpackGlobal","addBinocularItem","addCamShake","addCuratorAddons","addCuratorCameraArea","addCuratorEditableObjects","addCuratorEditingArea","addCuratorPoints","addEditorObject","addEventHandler","addForce","addForceGeneratorRTD","addGoggles","addGroupIcon","addHandgunItem","addHeadgear","addItem","addItemCargo","addItemCargoGlobal","addItemPool","addItemToBackpack","addItemToUniform","addItemToVest","addLiveStats","addMagazine","addMagazineAmmoCargo","addMagazineCargo","addMagazineCargoGlobal","addMagazineGlobal","addMagazinePool","addMagazines","addMagazineTurret","addMenu","addMenuItem","addMissionEventHandler","addMPEventHandler","addMusicEventHandler","addonFiles","addOwnedMine","addPlayerScores","addPrimaryWeaponItem","addPublicVariableEventHandler","addRating","addResources","addScore","addScoreSide","addSecondaryWeaponItem","addSwitchableUnit","addTeamMember","addToRemainsCollector","addTorque","addUniform","addUserActionEventHandler","addVehicle","addVest","addWaypoint","addWeapon","addWeaponCargo","addWeaponCargoGlobal","addWeaponGlobal","addWeaponItem","addWeaponPool","addWeaponTurret","addWeaponWithAttachmentsCargo","addWeaponWithAttachmentsCargoGlobal","admin","agent","agents","AGLToASL","aimedAtTarget","aimPos","airDensityCurveRTD","airDensityRTD","airplaneThrottle","airportSide","AISFinishHeal","alive","all3DENEntities","allActiveTitleEffects","allAddonsInfo","allAirports","allControls","allCurators","allCutLayers","allDead","allDeadMen","allDiaryRecords","allDiarySubjects","allDisplays","allEnv3DSoundSources","allGroups","allLODs","allMapMarkers","allMines","allMissionObjects","allObjects","allow3DMode","allowCrewInImmobile","allowCuratorLogicIgnoreAreas","allowDamage","allowDammage","allowedService","allowFileOperations","allowFleeing","allowGetIn","allowService","allowSprint","allPlayers","allSimpleObjects","allSites","allTurrets","allUnits","allUnitsUAV","allUsers","allVariables","ambientTemperature","ammo","ammoOnPylon","and","animate","animateBay","animateDoor","animatePylon","animateSource","animationNames","animationPhase","animationSourcePhase","animationState","apertureParams","append","apply","armoryPoints","arrayIntersect","asin","ASLToAGL","ASLToATL","assert","assignAsCargo","assignAsCargoIndex","assignAsCommander","assignAsDriver","assignAsGunner","assignAsTurret","assignCurator","assignedCargo","assignedCommander","assignedDriver","assignedGroup","assignedGunner","assignedItems","assignedTarget","assignedTeam","assignedVehicle","assignedVehicleRole","assignedVehicles","assignItem","assignTeam","assignToAirport","atan","atan2","atg","ATLToASL","attachedObject","attachedObjects","attachedTo","attachObject","attachTo","attackEnabled","awake","backpack","backpackCargo","backpackContainer","backpackItems","backpackMagazines","backpackSpaceFor","behaviour","benchmark","bezierInterpolation","binocular","binocularItems","binocularMagazine","boundingBox","boundingBoxReal","boundingCenter","brakesDisabled","briefingName","buildingExit","buildingPos","buldozer_EnableRoadDiag","buldozer_IsEnabledRoadDiag","buldozer_LoadNewRoads","buldozer_reloadOperMap","buttonAction","buttonSetAction","cadetMode","calculatePath","calculatePlayerVisibilityByFriendly","call","callExtension","camCommand","camCommit","camCommitPrepared","camCommitted","camConstuctionSetParams","camCreate","camDestroy","cameraEffect","cameraEffectEnableHUD","cameraInterest","cameraOn","cameraView","campaignConfigFile","camPreload","camPreloaded","camPrepareBank","camPrepareDir","camPrepareDive","camPrepareFocus","camPrepareFov","camPrepareFovRange","camPreparePos","camPrepareRelPos","camPrepareTarget","camSetBank","camSetDir","camSetDive","camSetFocus","camSetFov","camSetFovRange","camSetPos","camSetRelPos","camSetTarget","camTarget","camUseNVG","canAdd","canAddItemToBackpack","canAddItemToUniform","canAddItemToVest","cancelSimpleTaskDestination","canDeployWeapon","canFire","canMove","canSlingLoad","canStand","canSuspend","canTriggerDynamicSimulation","canUnloadInCombat","canVehicleCargo","captive","captiveNum","cbChecked","cbSetChecked","ceil","channelEnabled","cheatsEnabled","checkAIFeature","checkVisibility","className","clear3DENAttribute","clear3DENInventory","clearAllItemsFromBackpack","clearBackpackCargo","clearBackpackCargoGlobal","clearForcesRTD","clearGroupIcons","clearItemCargo","clearItemCargoGlobal","clearItemPool","clearMagazineCargo","clearMagazineCargoGlobal","clearMagazinePool","clearOverlay","clearRadio","clearWeaponCargo","clearWeaponCargoGlobal","clearWeaponPool","clientOwner","closeDialog","closeDisplay","closeOverlay","collapseObjectTree","collect3DENHistory","collectiveRTD","collisionDisabledWith","combatBehaviour","combatMode","commandArtilleryFire","commandChat","commander","commandFire","commandFollow","commandFSM","commandGetOut","commandingMenu","commandMove","commandRadio","commandStop","commandSuppressiveFire","commandTarget","commandWatch","comment","commitOverlay","compatibleItems","compatibleMagazines","compile","compileFinal","compileScript","completedFSM","composeText","configClasses","configFile","configHierarchy","configName","configOf","configProperties","configSourceAddonList","configSourceMod","configSourceModList","confirmSensorTarget","connectTerminalToUAV","connectToServer","controlsGroupCtrl","conversationDisabled","copyFromClipboard","copyToClipboard","copyWaypoints","cos","count","countEnemy","countFriendly","countSide","countType","countUnknown","create3DENComposition","create3DENEntity","createAgent","createCenter","createDialog","createDiaryLink","createDiaryRecord","createDiarySubject","createDisplay","createGearDialog","createGroup","createGuardedPoint","createHashMap","createHashMapFromArray","createLocation","createMarker","createMarkerLocal","createMenu","createMine","createMissionDisplay","createMPCampaignDisplay","createSimpleObject","createSimpleTask","createSite","createSoundSource","createTask","createTeam","createTrigger","createUnit","createVehicle","createVehicleCrew","createVehicleLocal","crew","ctAddHeader","ctAddRow","ctClear","ctCurSel","ctData","ctFindHeaderRows","ctFindRowHeader","ctHeaderControls","ctHeaderCount","ctRemoveHeaders","ctRemoveRows","ctrlActivate","ctrlAddEventHandler","ctrlAngle","ctrlAnimateModel","ctrlAnimationPhaseModel","ctrlAt","ctrlAutoScrollDelay","ctrlAutoScrollRewind","ctrlAutoScrollSpeed","ctrlBackgroundColor","ctrlChecked","ctrlClassName","ctrlCommit","ctrlCommitted","ctrlCreate","ctrlDelete","ctrlEnable","ctrlEnabled","ctrlFade","ctrlFontHeight","ctrlForegroundColor","ctrlHTMLLoaded","ctrlIDC","ctrlIDD","ctrlMapAnimAdd","ctrlMapAnimClear","ctrlMapAnimCommit","ctrlMapAnimDone","ctrlMapCursor","ctrlMapMouseOver","ctrlMapPosition","ctrlMapScale","ctrlMapScreenToWorld","ctrlMapSetPosition","ctrlMapWorldToScreen","ctrlModel","ctrlModelDirAndUp","ctrlModelScale","ctrlMousePosition","ctrlParent","ctrlParentControlsGroup","ctrlPosition","ctrlRemoveAllEventHandlers","ctrlRemoveEventHandler","ctrlScale","ctrlScrollValues","ctrlSetActiveColor","ctrlSetAngle","ctrlSetAutoScrollDelay","ctrlSetAutoScrollRewind","ctrlSetAutoScrollSpeed","ctrlSetBackgroundColor","ctrlSetChecked","ctrlSetDisabledColor","ctrlSetEventHandler","ctrlSetFade","ctrlSetFocus","ctrlSetFont","ctrlSetFontH1","ctrlSetFontH1B","ctrlSetFontH2","ctrlSetFontH2B","ctrlSetFontH3","ctrlSetFontH3B","ctrlSetFontH4","ctrlSetFontH4B","ctrlSetFontH5","ctrlSetFontH5B","ctrlSetFontH6","ctrlSetFontH6B","ctrlSetFontHeight","ctrlSetFontHeightH1","ctrlSetFontHeightH2","ctrlSetFontHeightH3","ctrlSetFontHeightH4","ctrlSetFontHeightH5","ctrlSetFontHeightH6","ctrlSetFontHeightSecondary","ctrlSetFontP","ctrlSetFontPB","ctrlSetFontSecondary","ctrlSetForegroundColor","ctrlSetModel","ctrlSetModelDirAndUp","ctrlSetModelScale","ctrlSetMousePosition","ctrlSetPixelPrecision","ctrlSetPosition","ctrlSetPositionH","ctrlSetPositionW","ctrlSetPositionX","ctrlSetPositionY","ctrlSetScale","ctrlSetScrollValues","ctrlSetShadow","ctrlSetStructuredText","ctrlSetText","ctrlSetTextColor","ctrlSetTextColorSecondary","ctrlSetTextSecondary","ctrlSetTextSelection","ctrlSetTooltip","ctrlSetTooltipColorBox","ctrlSetTooltipColorShade","ctrlSetTooltipColorText","ctrlSetTooltipMaxWidth","ctrlSetURL","ctrlSetURLOverlayMode","ctrlShadow","ctrlShow","ctrlShown","ctrlStyle","ctrlText","ctrlTextColor","ctrlTextHeight","ctrlTextSecondary","ctrlTextSelection","ctrlTextWidth","ctrlTooltip","ctrlType","ctrlURL","ctrlURLOverlayMode","ctrlVisible","ctRowControls","ctRowCount","ctSetCurSel","ctSetData","ctSetHeaderTemplate","ctSetRowTemplate","ctSetValue","ctValue","curatorAddons","curatorCamera","curatorCameraArea","curatorCameraAreaCeiling","curatorCoef","curatorEditableObjects","curatorEditingArea","curatorEditingAreaType","curatorMouseOver","curatorPoints","curatorRegisteredObjects","curatorSelected","curatorWaypointCost","current3DENOperation","currentChannel","currentCommand","currentMagazine","currentMagazineDetail","currentMagazineDetailTurret","currentMagazineTurret","currentMuzzle","currentNamespace","currentPilot","currentTask","currentTasks","currentThrowable","currentVisionMode","currentWaypoint","currentWeapon","currentWeaponMode","currentWeaponTurret","currentZeroing","cursorObject","cursorTarget","customChat","customRadio","customWaypointPosition","cutFadeOut","cutObj","cutRsc","cutText","damage","date","dateToNumber","dayTime","deActivateKey","debriefingText","debugFSM","debugLog","decayGraphValues","deg","delete3DENEntities","deleteAt","deleteCenter","deleteCollection","deleteEditorObject","deleteGroup","deleteGroupWhenEmpty","deleteIdentity","deleteLocation","deleteMarker","deleteMarkerLocal","deleteRange","deleteResources","deleteSite","deleteStatus","deleteTeam","deleteVehicle","deleteVehicleCrew","deleteWaypoint","detach","detectedMines","diag_activeMissionFSMs","diag_activeScripts","diag_activeSQFScripts","diag_activeSQSScripts","diag_allMissionEventHandlers","diag_captureFrame","diag_captureFrameToFile","diag_captureSlowFrame","diag_codePerformance","diag_deltaTime","diag_drawmode","diag_dumpCalltraceToLog","diag_dumpScriptAssembly","diag_dumpTerrainSynth","diag_dynamicSimulationEnd","diag_enable","diag_enabled","diag_exportConfig","diag_exportTerrainSVG","diag_fps","diag_fpsmin","diag_frameno","diag_getTerrainSegmentOffset","diag_lightNewLoad","diag_list","diag_localized","diag_log","diag_logSlowFrame","diag_mergeConfigFile","diag_recordTurretLimits","diag_resetFSM","diag_resetshapes","diag_scope","diag_setLightNew","diag_stacktrace","diag_tickTime","diag_toggle","dialog","diarySubjectExists","didJIP","didJIPOwner","difficulty","difficultyEnabled","difficultyEnabledRTD","difficultyOption","direction","directionStabilizationEnabled","directSay","disableAI","disableBrakes","disableCollisionWith","disableConversation","disableDebriefingStats","disableMapIndicators","disableNVGEquipment","disableRemoteSensors","disableSerialization","disableTIEquipment","disableUAVConnectability","disableUserInput","displayAddEventHandler","displayChild","displayCtrl","displayParent","displayRemoveAllEventHandlers","displayRemoveEventHandler","displaySetEventHandler","displayUniqueName","displayUpdate","dissolveTeam","distance","distance2D","distanceSqr","distributionRegion","do3DENAction","doArtilleryFire","doFire","doFollow","doFSM","doGetOut","doMove","doorPhase","doStop","doSuppressiveFire","doTarget","doWatch","drawArrow","drawEllipse","drawIcon","drawIcon3D","drawLaser","drawLine","drawLine3D","drawLink","drawLocation","drawPolygon","drawRectangle","drawTriangle","driver","drop","dynamicSimulationDistance","dynamicSimulationDistanceCoef","dynamicSimulationEnabled","dynamicSimulationSystemEnabled","echo","edit3DENMissionAttributes","editObject","editorSetEventHandler","effectiveCommander","elevatePeriscope","emptyPositions","enableAI","enableAIFeature","enableAimPrecision","enableAttack","enableAudioFeature","enableAutoStartUpRTD","enableAutoTrimRTD","enableCamShake","enableCaustics","enableChannel","enableCollisionWith","enableCopilot","enableDebriefingStats","enableDiagLegend","enableDirectionStabilization","enableDynamicSimulation","enableDynamicSimulationSystem","enableEndDialog","enableEngineArtillery","enableEnvironment","enableFatigue","enableGunLights","enableInfoPanelComponent","enableIRLasers","enableMimics","enablePersonTurret","enableRadio","enableReload","enableRopeAttach","enableSatNormalOnDetail","enableSaving","enableSentences","enableSimulation","enableSimulationGlobal","enableStamina","enableStressDamage","enableTeamSwitch","enableTraffic","enableUAVConnectability","enableUAVWaypoints","enableVehicleCargo","enableVehicleSensor","enableWeaponDisassembly","endLoadingScreen","endMission","engineOn","enginesIsOnRTD","enginesPowerRTD","enginesRpmRTD","enginesTorqueRTD","entities","environmentEnabled","environmentVolume","equipmentDisabled","estimatedEndServerTime","estimatedTimeLeft","evalObjectArgument","everyBackpack","everyContainer","exec","execEditorScript","execFSM","execVM","exp","expectedDestination","exportJIPMessages","eyeDirection","eyePos","face","faction","fadeEnvironment","fadeMusic","fadeRadio","fadeSound","fadeSpeech","failMission","fileExists","fillWeaponsFromPool","find","findAny","findCover","findDisplay","findEditorObject","findEmptyPosition","findEmptyPositionReady","findIf","findNearestEnemy","finishMissionInit","finite","fire","fireAtTarget","firstBackpack","flag","flagAnimationPhase","flagOwner","flagSide","flagTexture","flatten","fleeing","floor","flyInHeight","flyInHeightASL","focusedCtrl","fog","fogForecast","fogParams","forceAddUniform","forceAtPositionRTD","forceCadetDifficulty","forcedMap","forceEnd","forceFlagTexture","forceFollowRoad","forceGeneratorRTD","forceMap","forceRespawn","forceSpeed","forceUnicode","forceWalk","forceWeaponFire","forceWeatherChange","forEachMember","forEachMemberAgent","forEachMemberTeam","forgetTarget","format","formation","formationDirection","formationLeader","formationMembers","formationPosition","formationTask","formatText","formLeader","freeExtension","freeLook","fromEditor","fuel","fullCrew","gearIDCAmmoCount","gearSlotAmmoCount","gearSlotData","gestureState","get","get3DENActionState","get3DENAttribute","get3DENCamera","get3DENConnections","get3DENEntity","get3DENEntityID","get3DENGrid","get3DENIconsVisible","get3DENLayerEntities","get3DENLinesVisible","get3DENMissionAttribute","get3DENMouseOver","get3DENSelected","getAimingCoef","getAllEnv3DSoundControllers","getAllEnvSoundControllers","getAllHitPointsDamage","getAllOwnedMines","getAllPylonsInfo","getAllSoundControllers","getAllUnitTraits","getAmmoCargo","getAnimAimPrecision","getAnimSpeedCoef","getArray","getArtilleryAmmo","getArtilleryComputerSettings","getArtilleryETA","getAssetDLCInfo","getAssignedCuratorLogic","getAssignedCuratorUnit","getAttackTarget","getAudioOptionVolumes","getBackpackCargo","getBleedingRemaining","getBurningValue","getCalculatePlayerVisibilityByFriendly","getCameraViewDirection","getCargoIndex","getCenterOfMass","getClientState","getClientStateNumber","getCompatiblePylonMagazines","getConnectedUAV","getConnectedUAVUnit","getContainerMaxLoad","getCorpse","getCruiseControl","getCursorObjectParams","getCustomAimCoef","getCustomSoundController","getCustomSoundControllerCount","getDammage","getDebriefingText","getDescription","getDir","getDirVisual","getDiverState","getDLCAssetsUsage","getDLCAssetsUsageByName","getDLCs","getDLCUsageTime","getEditorCamera","getEditorMode","getEditorObjectScope","getElevationOffset","getEngineTargetRPMRTD","getEnv3DSoundController","getEnvSoundController","getEventHandlerInfo","getFatigue","getFieldManualStartPage","getForcedFlagTexture","getForcedSpeed","getFriend","getFSMVariable","getFuelCargo","getGraphValues","getGroupIcon","getGroupIconParams","getGroupIcons","getHideFrom","getHit","getHitIndex","getHitPointDamage","getItemCargo","getLighting","getLightingAt","getLoadedModsInfo","getMagazineCargo","getMarkerColor","getMarkerPos","getMarkerSize","getMarkerType","getMass","getMissionConfig","getMissionConfigValue","getMissionDLCs","getMissionLayerEntities","getMissionLayers","getMissionPath","getModelInfo","getMousePosition","getMusicPlayedTime","getNumber","getObjectArgument","getObjectChildren","getObjectDLC","getObjectFOV","getObjectID","getObjectMaterials","getObjectProxy","getObjectScale","getObjectTextures","getObjectType","getObjectViewDistance","getOpticsMode","getOrDefault","getOrDefaultCall","getOxygenRemaining","getPersonUsedDLCs","getPilotCameraDirection","getPilotCameraPosition","getPilotCameraRotation","getPilotCameraTarget","getPiPViewDistance","getPlateNumber","getPlayerChannel","getPlayerID","getPlayerScores","getPlayerUID","getPlayerVoNVolume","getPos","getPosASL","getPosASLVisual","getPosASLW","getPosATL","getPosATLVisual","getPosVisual","getPosWorld","getPosWorldVisual","getPylonMagazines","getRelDir","getRelPos","getRemoteSensorsDisabled","getRepairCargo","getResolution","getRoadInfo","getRotorBrakeRTD","getSensorTargets","getSensorThreats","getShadowDistance","getShotParents","getSlingLoad","getSoundController","getSoundControllerResult","getSpeed","getStamina","getStatValue","getSteamFriendsServers","getSubtitleOptions","getSuppression","getTerrainGrid","getTerrainHeight","getTerrainHeightASL","getTerrainInfo","getText","getTextRaw","getTextureInfo","getTextWidth","getTiParameters","getTotalDLCUsageTime","getTrimOffsetRTD","getTurretLimits","getTurretOpticsMode","getUnitFreefallInfo","getUnitLoadout","getUnitTrait","getUnloadInCombat","getUserInfo","getUserMFDText","getUserMFDValue","getVariable","getVehicleCargo","getVehicleTiPars","getWeaponCargo","getWeaponSway","getWingsOrientationRTD","getWingsPositionRTD","getWPPos","glanceAt","globalChat","globalRadio","goggles","goto","group","groupChat","groupFromNetId","groupIconSelectable","groupIconsVisible","groupID","groupOwner","groupRadio","groups","groupSelectedUnits","groupSelectUnit","gunner","gusts","halt","handgunItems","handgunMagazine","handgunWeapon","handsHit","hashValue","hasInterface","hasPilotCamera","hasWeapon","hcAllGroups","hcGroupParams","hcLeader","hcRemoveAllGroups","hcRemoveGroup","hcSelected","hcSelectGroup","hcSetGroup","hcShowBar","hcShownBar","headgear","hideBody","hideObject","hideObjectGlobal","hideSelection","hint","hintC","hintCadet","hintSilent","hmd","hostMission","htmlLoad","HUDMovementLevels","humidity","image","importAllGroups","importance","in","inArea","inAreaArray","incapacitatedState","inflame","inflamed","infoPanel","infoPanelComponentEnabled","infoPanelComponents","infoPanels","inGameUISetEventHandler","inheritsFrom","initAmbientLife","inPolygon","inputAction","inputController","inputMouse","inRangeOfArtillery","insert","insertEditorObject","intersect","is3DEN","is3DENMultiplayer","is3DENPreview","isAbleToBreathe","isActionMenuVisible","isAgent","isAimPrecisionEnabled","isAllowedCrewInImmobile","isArray","isAutoHoverOn","isAutonomous","isAutoStartUpEnabledRTD","isAutotest","isAutoTrimOnRTD","isAwake","isBleeding","isBurning","isClass","isCollisionLightOn","isCopilotEnabled","isDamageAllowed","isDedicated","isDLCAvailable","isEngineOn","isEqualRef","isEqualTo","isEqualType","isEqualTypeAll","isEqualTypeAny","isEqualTypeArray","isEqualTypeParams","isFilePatchingEnabled","isFinal","isFlashlightOn","isFlatEmpty","isForcedWalk","isFormationLeader","isGameFocused","isGamePaused","isGroupDeletedWhenEmpty","isHidden","isInRemainsCollector","isInstructorFigureEnabled","isIRLaserOn","isKeyActive","isKindOf","isLaserOn","isLightOn","isLocalized","isManualFire","isMarkedForCollection","isMissionProfileNamespaceLoaded","isMultiplayer","isMultiplayerSolo","isNil","isNotEqualRef","isNotEqualTo","isNull","isNumber","isObjectHidden","isObjectRTD","isOnRoad","isPiPEnabled","isPlayer","isRealTime","isRemoteExecuted","isRemoteExecutedJIP","isSaving","isSensorTargetConfirmed","isServer","isShowing3DIcons","isSimpleObject","isSprintAllowed","isStaminaEnabled","isSteamMission","isSteamOverlayEnabled","isStreamFriendlyUIEnabled","isStressDamageEnabled","isText","isTouchingGround","isTurnedOut","isTutHintsEnabled","isUAVConnectable","isUAVConnected","isUIContext","isUniformAllowed","isVehicleCargo","isVehicleRadarOn","isVehicleSensorEnabled","isWalking","isWeaponDeployed","isWeaponRested","itemCargo","items","itemsWithMagazines","join","joinAs","joinAsSilent","joinSilent","joinString","kbAddDatabase","kbAddDatabaseTargets","kbAddTopic","kbHasTopic","kbReact","kbRemoveTopic","kbTell","kbWasSaid","keyImage","keyName","keys","knowsAbout","land","landAt","landResult","language","laserTarget","lbAdd","lbClear","lbColor","lbColorRight","lbCurSel","lbData","lbDelete","lbIsSelected","lbPicture","lbPictureRight","lbSelection","lbSetColor","lbSetColorRight","lbSetCurSel","lbSetData","lbSetPicture","lbSetPictureColor","lbSetPictureColorDisabled","lbSetPictureColorSelected","lbSetPictureRight","lbSetPictureRightColor","lbSetPictureRightColorDisabled","lbSetPictureRightColorSelected","lbSetSelectColor","lbSetSelectColorRight","lbSetSelected","lbSetText","lbSetTextRight","lbSetTooltip","lbSetValue","lbSize","lbSort","lbSortBy","lbSortByValue","lbText","lbTextRight","lbTooltip","lbValue","leader","leaderboardDeInit","leaderboardGetRows","leaderboardInit","leaderboardRequestRowsFriends","leaderboardRequestRowsGlobal","leaderboardRequestRowsGlobalAroundUser","leaderboardsRequestUploadScore","leaderboardsRequestUploadScoreKeepBest","leaderboardState","leaveVehicle","libraryCredits","libraryDisclaimers","lifeState","lightAttachObject","lightDetachObject","lightIsOn","lightnings","limitSpeed","linearConversion","lineIntersects","lineIntersectsObjs","lineIntersectsSurfaces","lineIntersectsWith","linkItem","list","listObjects","listRemoteTargets","listVehicleSensors","ln","lnbAddArray","lnbAddColumn","lnbAddRow","lnbClear","lnbColor","lnbColorRight","lnbCurSelRow","lnbData","lnbDeleteColumn","lnbDeleteRow","lnbGetColumnsPosition","lnbPicture","lnbPictureRight","lnbSetColor","lnbSetColorRight","lnbSetColumnsPos","lnbSetCurSelRow","lnbSetData","lnbSetPicture","lnbSetPictureColor","lnbSetPictureColorRight","lnbSetPictureColorSelected","lnbSetPictureColorSelectedRight","lnbSetPictureRight","lnbSetText","lnbSetTextRight","lnbSetTooltip","lnbSetValue","lnbSize","lnbSort","lnbSortBy","lnbSortByValue","lnbText","lnbTextRight","lnbValue","load","loadAbs","loadBackpack","loadConfig","loadFile","loadGame","loadIdentity","loadMagazine","loadOverlay","loadStatus","loadUniform","loadVest","localize","localNamespace","locationPosition","lock","lockCameraTo","lockCargo","lockDriver","locked","lockedCameraTo","lockedCargo","lockedDriver","lockedInventory","lockedTurret","lockIdentity","lockInventory","lockTurret","lockWp","log","logEntities","logNetwork","logNetworkTerminate","lookAt","lookAtPos","magazineCargo","magazines","magazinesAllTurrets","magazinesAmmo","magazinesAmmoCargo","magazinesAmmoFull","magazinesDetail","magazinesDetailBackpack","magazinesDetailUniform","magazinesDetailVest","magazinesTurret","magazineTurretAmmo","mapAnimAdd","mapAnimClear","mapAnimCommit","mapAnimDone","mapCenterOnCamera","mapGridPosition","markAsFinishedOnSteam","markerAlpha","markerBrush","markerChannel","markerColor","markerDir","markerPolyline","markerPos","markerShadow","markerShape","markerSize","markerText","markerType","matrixMultiply","matrixTranspose","max","maxLoad","members","menuAction","menuAdd","menuChecked","menuClear","menuCollapse","menuData","menuDelete","menuEnable","menuEnabled","menuExpand","menuHover","menuPicture","menuSetAction","menuSetCheck","menuSetData","menuSetPicture","menuSetShortcut","menuSetText","menuSetURL","menuSetValue","menuShortcut","menuShortcutText","menuSize","menuSort","menuText","menuURL","menuValue","merge","min","mineActive","mineDetectedBy","missileTarget","missileTargetPos","missionConfigFile","missionDifficulty","missionEnd","missionName","missionNameSource","missionNamespace","missionProfileNamespace","missionStart","missionVersion","mod","modelToWorld","modelToWorldVisual","modelToWorldVisualWorld","modelToWorldWorld","modParams","moonIntensity","moonPhase","morale","move","move3DENCamera","moveInAny","moveInCargo","moveInCommander","moveInDriver","moveInGunner","moveInTurret","moveObjectToEnd","moveOut","moveTime","moveTo","moveToCompleted","moveToFailed","musicVolume","name","namedProperties","nameSound","nearEntities","nearestBuilding","nearestLocation","nearestLocations","nearestLocationWithDubbing","nearestMines","nearestObject","nearestObjects","nearestTerrainObjects","nearObjects","nearObjectsReady","nearRoads","nearSupplies","nearTargets","needReload","needService","netId","netObjNull","newOverlay","nextMenuItemIndex","nextWeatherChange","nMenuItems","not","numberOfEnginesRTD","numberToDate","objectCurators","objectFromNetId","objectParent","objStatus","onBriefingGroup","onBriefingNotes","onBriefingPlan","onBriefingTeamSwitch","onCommandModeChanged","onDoubleClick","onEachFrame","onGroupIconClick","onGroupIconOverEnter","onGroupIconOverLeave","onHCGroupSelectionChanged","onMapSingleClick","onPlayerConnected","onPlayerDisconnected","onPreloadFinished","onPreloadStarted","onShowNewObject","onTeamSwitch","openCuratorInterface","openDLCPage","openGPS","openMap","openSteamApp","openYoutubeVideo","or","orderGetIn","overcast","overcastForecast","owner","param","params","parseNumber","parseSimpleArray","parseText","parsingNamespace","particlesQuality","periscopeElevation","pickWeaponPool","pitch","pixelGrid","pixelGridBase","pixelGridNoUIScale","pixelH","pixelW","playableSlotsNumber","playableUnits","playAction","playActionNow","player","playerRespawnTime","playerSide","playersNumber","playGesture","playMission","playMove","playMoveNow","playMusic","playScriptedMission","playSound","playSound3D","playSoundUI","pose","position","positionCameraToWorld","posScreenToWorld","posWorldToScreen","ppEffectAdjust","ppEffectCommit","ppEffectCommitted","ppEffectCreate","ppEffectDestroy","ppEffectEnable","ppEffectEnabled","ppEffectForceInNVG","precision","preloadCamera","preloadObject","preloadSound","preloadTitleObj","preloadTitleRsc","preprocessFile","preprocessFileLineNumbers","primaryWeapon","primaryWeaponItems","primaryWeaponMagazine","priority","processDiaryLink","productVersion","profileName","profileNamespace","profileNameSteam","progressLoadingScreen","progressPosition","progressSetPosition","publicVariable","publicVariableClient","publicVariableServer","pushBack","pushBackUnique","putWeaponPool","queryItemsPool","queryMagazinePool","queryWeaponPool","rad","radioChannelAdd","radioChannelCreate","radioChannelInfo","radioChannelRemove","radioChannelSetCallSign","radioChannelSetLabel","radioEnabled","radioVolume","rain","rainbow","rainParams","random","rank","rankId","rating","rectangular","regexFind","regexMatch","regexReplace","registeredTasks","registerTask","reload","reloadEnabled","remoteControl","remoteExec","remoteExecCall","remoteExecutedOwner","remove3DENConnection","remove3DENEventHandler","remove3DENLayer","removeAction","removeAll3DENEventHandlers","removeAllActions","removeAllAssignedItems","removeAllBinocularItems","removeAllContainers","removeAllCuratorAddons","removeAllCuratorCameraAreas","removeAllCuratorEditingAreas","removeAllEventHandlers","removeAllHandgunItems","removeAllItems","removeAllItemsWithMagazines","removeAllMissionEventHandlers","removeAllMPEventHandlers","removeAllMusicEventHandlers","removeAllOwnedMines","removeAllPrimaryWeaponItems","removeAllSecondaryWeaponItems","removeAllUserActionEventHandlers","removeAllWeapons","removeBackpack","removeBackpackGlobal","removeBinocularItem","removeCuratorAddons","removeCuratorCameraArea","removeCuratorEditableObjects","removeCuratorEditingArea","removeDiaryRecord","removeDiarySubject","removeDrawIcon","removeDrawLinks","removeEventHandler","removeFromRemainsCollector","removeGoggles","removeGroupIcon","removeHandgunItem","removeHeadgear","removeItem","removeItemFromBackpack","removeItemFromUniform","removeItemFromVest","removeItems","removeMagazine","removeMagazineGlobal","removeMagazines","removeMagazinesTurret","removeMagazineTurret","removeMenuItem","removeMissionEventHandler","removeMPEventHandler","removeMusicEventHandler","removeOwnedMine","removePrimaryWeaponItem","removeSecondaryWeaponItem","removeSimpleTask","removeSwitchableUnit","removeTeamMember","removeUniform","removeUserActionEventHandler","removeVest","removeWeapon","removeWeaponAttachmentCargo","removeWeaponCargo","removeWeaponGlobal","removeWeaponTurret","reportRemoteTarget","requiredVersion","resetCamShake","resetSubgroupDirection","resize","resources","respawnVehicle","restartEditorCamera","reveal","revealMine","reverse","reversedMouseY","roadAt","roadsConnectedTo","roleDescription","ropeAttachedObjects","ropeAttachedTo","ropeAttachEnabled","ropeAttachTo","ropeCreate","ropeCut","ropeDestroy","ropeDetach","ropeEndPosition","ropeLength","ropes","ropesAttachedTo","ropeSegments","ropeUnwind","ropeUnwound","rotorsForcesRTD","rotorsRpmRTD","round","runInitScript","safeZoneH","safeZoneW","safeZoneWAbs","safeZoneX","safeZoneXAbs","safeZoneY","save3DENInventory","saveGame","saveIdentity","saveJoysticks","saveMissionProfileNamespace","saveOverlay","saveProfileNamespace","saveStatus","saveVar","savingEnabled","say","say2D","say3D","scopeName","score","scoreSide","screenshot","screenToWorld","scriptDone","scriptName","scudState","secondaryWeapon","secondaryWeaponItems","secondaryWeaponMagazine","select","selectBestPlaces","selectDiarySubject","selectedEditorObjects","selectEditorObject","selectionNames","selectionPosition","selectionVectorDirAndUp","selectLeader","selectMax","selectMin","selectNoPlayer","selectPlayer","selectRandom","selectRandomWeighted","selectWeapon","selectWeaponTurret","sendAUMessage","sendSimpleCommand","sendTask","sendTaskResult","sendUDPMessage","sentencesEnabled","serverCommand","serverCommandAvailable","serverCommandExecutable","serverName","serverNamespace","serverTime","set","set3DENAttribute","set3DENAttributes","set3DENGrid","set3DENIconsVisible","set3DENLayer","set3DENLinesVisible","set3DENLogicType","set3DENMissionAttribute","set3DENMissionAttributes","set3DENModelsVisible","set3DENObjectType","set3DENSelected","setAccTime","setActualCollectiveRTD","setAirplaneThrottle","setAirportSide","setAmmo","setAmmoCargo","setAmmoOnPylon","setAnimSpeedCoef","setAperture","setApertureNew","setArmoryPoints","setAttributes","setAutonomous","setBehaviour","setBehaviourStrong","setBleedingRemaining","setBrakesRTD","setCameraInterest","setCamShakeDefParams","setCamShakeParams","setCamUseTi","setCaptive","setCenterOfMass","setCollisionLight","setCombatBehaviour","setCombatMode","setCompassOscillation","setConvoySeparation","setCruiseControl","setCuratorCameraAreaCeiling","setCuratorCoef","setCuratorEditingAreaType","setCuratorWaypointCost","setCurrentChannel","setCurrentTask","setCurrentWaypoint","setCustomAimCoef","SetCustomMissionData","setCustomSoundController","setCustomWeightRTD","setDamage","setDammage","setDate","setDebriefingText","setDefaultCamera","setDestination","setDetailMapBlendPars","setDiaryRecordText","setDiarySubjectPicture","setDir","setDirection","setDrawIcon","setDriveOnPath","setDropInterval","setDynamicSimulationDistance","setDynamicSimulationDistanceCoef","setEditorMode","setEditorObjectScope","setEffectCondition","setEffectiveCommander","setEngineRpmRTD","setFace","setFaceanimation","setFatigue","setFeatureType","setFlagAnimationPhase","setFlagOwner","setFlagSide","setFlagTexture","setFog","setForceGeneratorRTD","setFormation","setFormationTask","setFormDir","setFriend","setFromEditor","setFSMVariable","setFuel","setFuelCargo","setGroupIcon","setGroupIconParams","setGroupIconsSelectable","setGroupIconsVisible","setGroupid","setGroupIdGlobal","setGroupOwner","setGusts","setHideBehind","setHit","setHitIndex","setHitPointDamage","setHorizonParallaxCoef","setHUDMovementLevels","setHumidity","setIdentity","setImportance","setInfoPanel","setLeader","setLightAmbient","setLightAttenuation","setLightBrightness","setLightColor","setLightConePars","setLightDayLight","setLightFlareMaxDistance","setLightFlareSize","setLightIntensity","setLightIR","setLightnings","setLightUseFlare","setLightVolumeShape","setLocalWindParams","setMagazineTurretAmmo","setMarkerAlpha","setMarkerAlphaLocal","setMarkerBrush","setMarkerBrushLocal","setMarkerColor","setMarkerColorLocal","setMarkerDir","setMarkerDirLocal","setMarkerPolyline","setMarkerPolylineLocal","setMarkerPos","setMarkerPosLocal","setMarkerShadow","setMarkerShadowLocal","setMarkerShape","setMarkerShapeLocal","setMarkerSize","setMarkerSizeLocal","setMarkerText","setMarkerTextLocal","setMarkerType","setMarkerTypeLocal","setMass","setMaxLoad","setMimic","setMissileTarget","setMissileTargetPos","setMousePosition","setMusicEffect","setMusicEventHandler","setName","setNameSound","setObjectArguments","setObjectMaterial","setObjectMaterialGlobal","setObjectProxy","setObjectScale","setObjectTexture","setObjectTextureGlobal","setObjectViewDistance","setOpticsMode","setOvercast","setOwner","setOxygenRemaining","setParticleCircle","setParticleClass","setParticleFire","setParticleParams","setParticleRandom","setPilotCameraDirection","setPilotCameraRotation","setPilotCameraTarget","setPilotLight","setPiPEffect","setPiPViewDistance","setPitch","setPlateNumber","setPlayable","setPlayerRespawnTime","setPlayerVoNVolume","setPos","setPosASL","setPosASL2","setPosASLW","setPosATL","setPosition","setPosWorld","setPylonLoadout","setPylonsPriority","setRadioMsg","setRain","setRainbow","setRandomLip","setRank","setRectangular","setRepairCargo","setRotorBrakeRTD","setShadowDistance","setShotParents","setSide","setSimpleTaskAlwaysVisible","setSimpleTaskCustomData","setSimpleTaskDescription","setSimpleTaskDestination","setSimpleTaskTarget","setSimpleTaskType","setSimulWeatherLayers","setSize","setSkill","setSlingLoad","setSoundEffect","setSpeaker","setSpeech","setSpeedMode","setStamina","setStaminaScheme","setStatValue","setSuppression","setSystemOfUnits","setTargetAge","setTaskMarkerOffset","setTaskResult","setTaskState","setTerrainGrid","setTerrainHeight","setText","setTimeMultiplier","setTiParameter","setTitleEffect","setTowParent","setTrafficDensity","setTrafficDistance","setTrafficGap","setTrafficSpeed","setTriggerActivation","setTriggerArea","setTriggerInterval","setTriggerStatements","setTriggerText","setTriggerTimeout","setTriggerType","setTurretLimits","setTurretOpticsMode","setType","setUnconscious","setUnitAbility","setUnitCombatMode","setUnitFreefallHeight","setUnitLoadout","setUnitPos","setUnitPosWeak","setUnitRank","setUnitRecoilCoefficient","setUnitTrait","setUnloadInCombat","setUserActionText","setUserMFDText","setUserMFDValue","setVariable","setVectorDir","setVectorDirAndUp","setVectorUp","setVehicleAmmo","setVehicleAmmoDef","setVehicleArmor","setVehicleCargo","setVehicleId","setVehicleLock","setVehiclePosition","setVehicleRadar","setVehicleReceiveRemoteTargets","setVehicleReportOwnPosition","setVehicleReportRemoteTargets","setVehicleTiPars","setVehicleVarName","setVelocity","setVelocityModelSpace","setVelocityTransformation","setViewDistance","setVisibleIfTreeCollapsed","setWantedRPMRTD","setWaves","setWaypointBehaviour","setWaypointCombatMode","setWaypointCompletionRadius","setWaypointDescription","setWaypointForceBehaviour","setWaypointFormation","setWaypointHousePosition","setWaypointLoiterAltitude","setWaypointLoiterRadius","setWaypointLoiterType","setWaypointName","setWaypointPosition","setWaypointScript","setWaypointSpeed","setWaypointStatements","setWaypointTimeout","setWaypointType","setWaypointVisible","setWeaponReloadingTime","setWeaponZeroing","setWind","setWindDir","setWindForce","setWindStr","setWingForceScaleRTD","setWPPos","show3DIcons","showChat","showCinemaBorder","showCommandingMenu","showCompass","showCuratorCompass","showGps","showHUD","showLegend","showMap","shownArtilleryComputer","shownChat","shownCompass","shownCuratorCompass","showNewEditorObject","shownGps","shownHUD","shownMap","shownPad","shownRadio","shownScoretable","shownSubtitles","shownUAVFeed","shownWarrant","shownWatch","showPad","showRadio","showScoretable","showSubtitles","showUAVFeed","showWarrant","showWatch","showWaypoint","showWaypoints","side","sideChat","sideRadio","simpleTasks","simulationEnabled","simulCloudDensity","simulCloudOcclusion","simulInClouds","simulWeatherSync","sin","size","sizeOf","skill","skillFinal","skipTime","sleep","sliderPosition","sliderRange","sliderSetPosition","sliderSetRange","sliderSetSpeed","sliderSpeed","slingLoadAssistantShown","soldierMagazines","someAmmo","sort","soundVolume","spawn","speaker","speechVolume","speed","speedMode","splitString","sqrt","squadParams","stance","startLoadingScreen","stop","stopEngineRTD","stopped","str","sunOrMoon","supportInfo","suppressFor","surfaceIsWater","surfaceNormal","surfaceTexture","surfaceType","swimInDepth","switchableUnits","switchAction","switchCamera","switchGesture","switchLight","switchMove","synchronizedObjects","synchronizedTriggers","synchronizedWaypoints","synchronizeObjectsAdd","synchronizeObjectsRemove","synchronizeTrigger","synchronizeWaypoint","systemChat","systemOfUnits","systemTime","systemTimeUTC","tan","targetKnowledge","targets","targetsAggregate","targetsQuery","taskAlwaysVisible","taskChildren","taskCompleted","taskCustomData","taskDescription","taskDestination","taskHint","taskMarkerOffset","taskName","taskParent","taskResult","taskState","taskType","teamMember","teamName","teams","teamSwitch","teamSwitchEnabled","teamType","terminate","terrainIntersect","terrainIntersectASL","terrainIntersectAtASL","text","textLog","textLogFormat","tg","time","timeMultiplier","titleCut","titleFadeOut","titleObj","titleRsc","titleText","toArray","toFixed","toLower","toLowerANSI","toString","toUpper","toUpperANSI","triggerActivated","triggerActivation","triggerAmmo","triggerArea","triggerAttachedVehicle","triggerAttachObject","triggerAttachVehicle","triggerDynamicSimulation","triggerInterval","triggerStatements","triggerText","triggerTimeout","triggerTimeoutCurrent","triggerType","trim","turretLocal","turretOwner","turretUnit","tvAdd","tvClear","tvCollapse","tvCollapseAll","tvCount","tvCurSel","tvData","tvDelete","tvExpand","tvExpandAll","tvIsSelected","tvPicture","tvPictureRight","tvSelection","tvSetColor","tvSetCurSel","tvSetData","tvSetPicture","tvSetPictureColor","tvSetPictureColorDisabled","tvSetPictureColorSelected","tvSetPictureRight","tvSetPictureRightColor","tvSetPictureRightColorDisabled","tvSetPictureRightColorSelected","tvSetSelectColor","tvSetSelected","tvSetText","tvSetTooltip","tvSetValue","tvSort","tvSortAll","tvSortByValue","tvSortByValueAll","tvText","tvTooltip","tvValue","type","typeName","typeOf","UAVControl","uiNamespace","uiSleep","unassignCurator","unassignItem","unassignTeam","unassignVehicle","underwater","uniform","uniformContainer","uniformItems","uniformMagazines","uniqueUnitItems","unitAddons","unitAimPosition","unitAimPositionVisual","unitBackpack","unitCombatMode","unitIsUAV","unitPos","unitReady","unitRecoilCoefficient","units","unitsBelowHeight","unitTurret","unlinkItem","unlockAchievement","unregisterTask","updateDrawIcon","updateMenuItem","updateObjectTree","useAIOperMapObstructionTest","useAISteeringComponent","useAudioTimeForMoves","userInputDisabled","values","vectorAdd","vectorCos","vectorCrossProduct","vectorDiff","vectorDir","vectorDirVisual","vectorDistance","vectorDistanceSqr","vectorDotProduct","vectorFromTo","vectorLinearConversion","vectorMagnitude","vectorMagnitudeSqr","vectorModelToWorld","vectorModelToWorldVisual","vectorMultiply","vectorNormalized","vectorUp","vectorUpVisual","vectorWorldToModel","vectorWorldToModelVisual","vehicle","vehicleCargoEnabled","vehicleChat","vehicleMoveInfo","vehicleRadio","vehicleReceiveRemoteTargets","vehicleReportOwnPosition","vehicleReportRemoteTargets","vehicles","vehicleVarName","velocity","velocityModelSpace","verifySignature","vest","vestContainer","vestItems","vestMagazines","viewDistance","visibleCompass","visibleGps","visibleMap","visiblePosition","visiblePositionASL","visibleScoretable","visibleWatch","waves","waypointAttachedObject","waypointAttachedVehicle","waypointAttachObject","waypointAttachVehicle","waypointBehaviour","waypointCombatMode","waypointCompletionRadius","waypointDescription","waypointForceBehaviour","waypointFormation","waypointHousePosition","waypointLoiterAltitude","waypointLoiterRadius","waypointLoiterType","waypointName","waypointPosition","waypoints","waypointScript","waypointsEnabledUAV","waypointShow","waypointSpeed","waypointStatements","waypointTimeout","waypointTimeoutCurrent","waypointType","waypointVisible","weaponAccessories","weaponAccessoriesCargo","weaponCargo","weaponDirection","weaponInertia","weaponLowered","weaponReloadingTime","weapons","weaponsInfo","weaponsItems","weaponsItemsCargo","weaponState","weaponsTurret","weightRTD","WFSideText","wind","windDir","windRTD","windStr","wingsForcesRTD","worldName","worldSize","worldToModel","worldToModelVisual","worldToScreen"],literal:["blufor","civilian","configNull","controlNull","displayNull","diaryRecordNull","east","endl","false","grpNull","independent","lineBreak","locationNull","nil","objNull","opfor","pi","resistance","scriptNull","sideAmbientLife","sideEmpty","sideEnemy","sideFriendly","sideLogic","sideUnknown","taskNull","teamMemberNull","true","west"]},contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.NUMBER_MODE,{className:"variable",begin:/\b_+[a-zA-Z]\w*/},{className:"title",begin:/[a-zA-Z][a-zA-Z_0-9]*_fnc_[a-zA-Z_0-9]+/},t,r],illegal:[/\$[^a-fA-F0-9]/,/\w\$/,/\?/,/@/,/ \| /,/[a-zA-Z_]\./,/\:\=/,/\[\:/]}}),Lh)),zf.registerLanguage("sql",(Bh||(Bh=1,Fh=function(e){const t=e.regex,r=e.COMMENT("--","$"),n=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],a=n,i=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(e=>!n.includes(e)),o={match:t.concat(/\b/,t.either(...a),/\s*\(/),relevance:0,keywords:{built_in:a}};function s(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,"\\s+"))),/\b/)}const l={scope:"keyword",match:s(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]),relevance:0};return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:function(e,{exceptions:t,when:r}={}){const n=r;return t=t||[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:n(e)?`${e}|0`:e)}(i,{when:e=>e.length<3}),literal:["true","false","unknown"],type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"]},contains:[{scope:"type",match:s(["double precision","large object","with timezone","without timezone"])},l,o,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{match:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,r,{scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}}),Fh)),zf.registerLanguage("stan",(Gh||(Gh=1,Uh=function(e){const t=e.regex,r=["bernoulli","bernoulli_logit","bernoulli_logit_glm","beta","beta_binomial","beta_proportion","binomial","binomial_logit","categorical","categorical_logit","categorical_logit_glm","cauchy","chi_square","dirichlet","discrete_range","double_exponential","exp_mod_normal","exponential","frechet","gamma","gaussian_dlm_obs","gumbel","hmm_latent","hypergeometric","inv_chi_square","inv_gamma","inv_wishart","inv_wishart_cholesky","lkj_corr","lkj_corr_cholesky","logistic","loglogistic","lognormal","multi_gp","multi_gp_cholesky","multinomial","multinomial_logit","multi_normal","multi_normal_cholesky","multi_normal_prec","multi_student_cholesky_t","multi_student_t","multi_student_t_cholesky","neg_binomial","neg_binomial_2","neg_binomial_2_log","neg_binomial_2_log_glm","normal","normal_id_glm","ordered_logistic","ordered_logistic_glm","ordered_probit","pareto","pareto_type_2","poisson","poisson_log","poisson_log_glm","rayleigh","scaled_inv_chi_square","skew_double_exponential","skew_normal","std_normal","std_normal_log","student_t","uniform","von_mises","weibull","wiener","wishart","wishart_cholesky"],n=e.COMMENT(/\/\*/,/\*\//,{relevance:0,contains:[{scope:"doctag",match:/@(return|param)/}]}),a={scope:"meta",begin:/#include\b/,end:/$/,contains:[{match:/[a-z][a-z-._]+/,scope:"string"},e.C_LINE_COMMENT_MODE]},i=["lower","upper","offset","multiplier"];return{name:"Stan",aliases:["stanfuncs"],keywords:{$pattern:e.IDENT_RE,title:["functions","model","data","parameters","quantities","transformed","generated"],type:["array","tuple","complex","int","real","vector","complex_vector","ordered","positive_ordered","simplex","unit_vector","row_vector","complex_row_vector","matrix","complex_matrix","cholesky_factor_corr|10","cholesky_factor_cov|10","corr_matrix|10","cov_matrix|10","void"],keyword:["for","in","if","else","while","break","continue","return"],built_in:["abs","acos","acosh","add_diag","algebra_solver","algebra_solver_newton","append_array","append_col","append_row","asin","asinh","atan","atan2","atanh","bessel_first_kind","bessel_second_kind","binary_log_loss","block","cbrt","ceil","chol2inv","cholesky_decompose","choose","col","cols","columns_dot_product","columns_dot_self","complex_schur_decompose","complex_schur_decompose_t","complex_schur_decompose_u","conj","cos","cosh","cov_exp_quad","crossprod","csr_extract","csr_extract_u","csr_extract_v","csr_extract_w","csr_matrix_times_vector","csr_to_dense_matrix","cumulative_sum","dae","dae_tol","determinant","diag_matrix","diagonal","diag_post_multiply","diag_pre_multiply","digamma","dims","distance","dot_product","dot_self","eigendecompose","eigendecompose_sym","eigenvalues","eigenvalues_sym","eigenvectors","eigenvectors_sym","erf","erfc","exp","exp2","expm1","falling_factorial","fdim","fft","fft2","floor","fma","fmax","fmin","fmod","gamma_p","gamma_q","generalized_inverse","get_imag","get_real","head","hmm_hidden_state_prob","hmm_marginal","hypot","identity_matrix","inc_beta","integrate_1d","integrate_ode","integrate_ode_adams","integrate_ode_bdf","integrate_ode_rk45","int_step","inv","inv_cloglog","inv_erfc","inverse","inverse_spd","inv_fft","inv_fft2","inv_inc_beta","inv_logit","inv_Phi","inv_sqrt","inv_square","is_inf","is_nan","lambert_w0","lambert_wm1","lbeta","lchoose","ldexp","lgamma","linspaced_array","linspaced_int_array","linspaced_row_vector","linspaced_vector","lmgamma","lmultiply","log","log1m","log1m_exp","log1m_inv_logit","log1p","log1p_exp","log_determinant","log_diff_exp","log_falling_factorial","log_inv_logit","log_inv_logit_diff","logit","log_mix","log_modified_bessel_first_kind","log_rising_factorial","log_softmax","log_sum_exp","machine_precision","map_rect","matrix_exp","matrix_exp_multiply","matrix_power","max","mdivide_left_spd","mdivide_left_tri_low","mdivide_right_spd","mdivide_right_tri_low","mean","min","modified_bessel_first_kind","modified_bessel_second_kind","multiply_lower_tri_self_transpose","negative_infinity","norm","norm1","norm2","not_a_number","num_elements","ode_adams","ode_adams_tol","ode_adjoint_tol_ctl","ode_bdf","ode_bdf_tol","ode_ckrk","ode_ckrk_tol","ode_rk45","ode_rk45_tol","one_hot_array","one_hot_int_array","one_hot_row_vector","one_hot_vector","ones_array","ones_int_array","ones_row_vector","ones_vector","owens_t","Phi","Phi_approx","polar","positive_infinity","pow","print","prod","proj","qr","qr_Q","qr_R","qr_thin","qr_thin_Q","qr_thin_R","quad_form","quad_form_diag","quad_form_sym","quantile","rank","reduce_sum","reject","rep_array","rep_matrix","rep_row_vector","rep_vector","reverse","rising_factorial","round","row","rows","rows_dot_product","rows_dot_self","scale_matrix_exp_multiply","sd","segment","sin","singular_values","sinh","size","softmax","sort_asc","sort_desc","sort_indices_asc","sort_indices_desc","sqrt","square","squared_distance","step","sub_col","sub_row","sum","svd","svd_U","svd_V","symmetrize_from_lower_tri","tail","tan","tanh","target","tcrossprod","tgamma","to_array_1d","to_array_2d","to_complex","to_int","to_matrix","to_row_vector","to_vector","trace","trace_gen_quad_form","trace_quad_form","trigamma","trunc","uniform_simplex","variance","zeros_array","zeros_int_array","zeros_row_vector"]},contains:[e.C_LINE_COMMENT_MODE,a,e.HASH_COMMENT_MODE,n,{scope:"built_in",match:/\s(pi|e|sqrt2|log2|log10)(?=\()/,relevance:0},{match:t.concat(/[<,]\s*/,t.either(...i),/\s*=/),keywords:i},{scope:"keyword",match:/\btarget(?=\s*\+=)/},{match:[/~\s*/,t.either(...r),/(?:\(\))/,/\s*T(?=\s*\[)/],scope:{2:"built_in",4:"keyword"}},{scope:"built_in",keywords:r,begin:t.concat(/\w*/,t.either(...r),/(_lpdf|_lupdf|_lpmf|_cdf|_lcdf|_lccdf|_qf)(?=\s*[\(.*\)])/)},{begin:[/~/,/\s*/,t.concat(t.either(...r),/(?=\s*[\(.*\)])/)],scope:{3:"built_in"}},{begin:[/~/,/\s*\w+(?=\s*[\(.*\)])/,"(?!.*/\b("+t.either(...r)+")\b)"],scope:{2:"title.function"}},{scope:"title.function",begin:/\w*(_lpdf|_lupdf|_lpmf|_cdf|_lcdf|_lccdf|_qf)(?=\s*[\(.*\)])/},{scope:"number",match:t.concat(/(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)/,/(?:[eE][+-]?\d+(?:_\d+)*)?i?(?!\w)/),relevance:0},{scope:"string",begin:/"/,end:/"/}]}}),Uh)),zf.registerLanguage("stata",(Yh||(Yh=1,zh=function(e){return{name:"Stata",aliases:["do","ado"],case_insensitive:!0,keywords:"if else in foreach for forv forva forval forvalu forvalue forvalues by bys bysort xi quietly qui capture about ac ac_7 acprplot acprplot_7 adjust ado adopath adoupdate alpha ameans an ano anov anova anova_estat anova_terms anovadef aorder ap app appe appen append arch arch_dr arch_estat arch_p archlm areg areg_p args arima arima_dr arima_estat arima_p as asmprobit asmprobit_estat asmprobit_lf asmprobit_mfx__dlg asmprobit_p ass asse asser assert avplot avplot_7 avplots avplots_7 bcskew0 bgodfrey bias binreg bip0_lf biplot bipp_lf bipr_lf bipr_p biprobit bitest bitesti bitowt blogit bmemsize boot bootsamp bootstrap bootstrap_8 boxco_l boxco_p boxcox boxcox_6 boxcox_p bprobit br break brier bro brow brows browse brr brrstat bs bs_7 bsampl_w bsample bsample_7 bsqreg bstat bstat_7 bstat_8 bstrap bstrap_7 bubble bubbleplot ca ca_estat ca_p cabiplot camat canon canon_8 canon_8_p canon_estat canon_p cap caprojection capt captu captur capture cat cc cchart cchart_7 cci cd censobs_table centile cf char chdir checkdlgfiles checkestimationsample checkhlpfiles checksum chelp ci cii cl class classutil clear cli clis clist clo clog clog_lf clog_p clogi clogi_sw clogit clogit_lf clogit_p clogitp clogl_sw cloglog clonevar clslistarray cluster cluster_measures cluster_stop cluster_tree cluster_tree_8 clustermat cmdlog cnr cnre cnreg cnreg_p cnreg_sw cnsreg codebook collaps4 collapse colormult_nb colormult_nw compare compress conf confi confir confirm conren cons const constr constra constrai constrain constraint continue contract copy copyright copysource cor corc corr corr2data corr_anti corr_kmo corr_smc corre correl correla correlat correlate corrgram cou coun count cox cox_p cox_sw coxbase coxhaz coxvar cprplot cprplot_7 crc cret cretu cretur creturn cross cs cscript cscript_log csi ct ct_is ctset ctst_5 ctst_st cttost cumsp cumsp_7 cumul cusum cusum_7 cutil d|0 datasig datasign datasigna datasignat datasignatu datasignatur datasignature datetof db dbeta de dec deco decod decode deff des desc descr descri describ describe destring dfbeta dfgls dfuller di di_g dir dirstats dis discard disp disp_res disp_s displ displa display distinct do doe doed doedi doedit dotplot dotplot_7 dprobit drawnorm drop ds ds_util dstdize duplicates durbina dwstat dydx e|0 ed edi edit egen eivreg emdef en enc enco encod encode eq erase ereg ereg_lf ereg_p ereg_sw ereghet ereghet_glf ereghet_glf_sh ereghet_gp ereghet_ilf ereghet_ilf_sh ereghet_ip eret eretu eretur ereturn err erro error esize est est_cfexist est_cfname est_clickable est_expand est_hold est_table est_unhold est_unholdok estat estat_default estat_summ estat_vce_only esti estimates etodow etof etomdy ex exi exit expand expandcl fac fact facto factor factor_estat factor_p factor_pca_rotated factor_rotate factormat fcast fcast_compute fcast_graph fdades fdadesc fdadescr fdadescri fdadescrib fdadescribe fdasav fdasave fdause fh_st file open file read file close file filefilter fillin find_hlp_file findfile findit findit_7 fit fl fli flis flist for5_0 forest forestplot form forma format fpredict frac_154 frac_adj frac_chk frac_cox frac_ddp frac_dis frac_dv frac_in frac_mun frac_pp frac_pq frac_pv frac_wgt frac_xo fracgen fracplot fracplot_7 fracpoly fracpred fron_ex fron_hn fron_p fron_tn fron_tn2 frontier ftodate ftoe ftomdy ftowdate funnel funnelplot g|0 gamhet_glf gamhet_gp gamhet_ilf gamhet_ip gamma gamma_d2 gamma_p gamma_sw gammahet gdi_hexagon gdi_spokes ge gen gene gener genera generat generate genrank genstd genvmean gettoken gl gladder gladder_7 glim_l01 glim_l02 glim_l03 glim_l04 glim_l05 glim_l06 glim_l07 glim_l08 glim_l09 glim_l10 glim_l11 glim_l12 glim_lf glim_mu glim_nw1 glim_nw2 glim_nw3 glim_p glim_v1 glim_v2 glim_v3 glim_v4 glim_v5 glim_v6 glim_v7 glm glm_6 glm_p glm_sw glmpred glo glob globa global glogit glogit_8 glogit_p gmeans gnbre_lf gnbreg gnbreg_5 gnbreg_p gomp_lf gompe_sw gomper_p gompertz gompertzhet gomphet_glf gomphet_glf_sh gomphet_gp gomphet_ilf gomphet_ilf_sh gomphet_ip gphdot gphpen gphprint gprefs gprobi_p gprobit gprobit_8 gr gr7 gr_copy gr_current gr_db gr_describe gr_dir gr_draw gr_draw_replay gr_drop gr_edit gr_editviewopts gr_example gr_example2 gr_export gr_print gr_qscheme gr_query gr_read gr_rename gr_replay gr_save gr_set gr_setscheme gr_table gr_undo gr_use graph graph7 grebar greigen greigen_7 greigen_8 grmeanby grmeanby_7 gs_fileinfo gs_filetype gs_graphinfo gs_stat gsort gwood h|0 hadimvo hareg hausman haver he heck_d2 heckma_p heckman heckp_lf heckpr_p heckprob hel help hereg hetpr_lf hetpr_p hetprob hettest hexdump hilite hist hist_7 histogram hlogit hlu hmeans hotel hotelling hprobit hreg hsearch icd9 icd9_ff icd9p iis impute imtest inbase include inf infi infil infile infix inp inpu input ins insheet insp inspe inspec inspect integ inten intreg intreg_7 intreg_p intrg2_ll intrg_ll intrg_ll2 ipolate iqreg ir irf irf_create irfm iri is_svy is_svysum isid istdize ivprob_1_lf ivprob_lf ivprobit ivprobit_p ivreg ivreg_footnote ivtob_1_lf ivtob_lf ivtobit ivtobit_p jackknife jacknife jknife jknife_6 jknife_8 jkstat joinby kalarma1 kap kap_3 kapmeier kappa kapwgt kdensity kdensity_7 keep ksm ksmirnov ktau kwallis l|0 la lab labbe labbeplot labe label labelbook ladder levels levelsof leverage lfit lfit_p li lincom line linktest lis list lloghet_glf lloghet_glf_sh lloghet_gp lloghet_ilf lloghet_ilf_sh lloghet_ip llogi_sw llogis_p llogist llogistic llogistichet lnorm_lf lnorm_sw lnorma_p lnormal lnormalhet lnormhet_glf lnormhet_glf_sh lnormhet_gp lnormhet_ilf lnormhet_ilf_sh lnormhet_ip lnskew0 loadingplot loc loca local log logi logis_lf logistic logistic_p logit logit_estat logit_p loglogs logrank loneway lookfor lookup lowess lowess_7 lpredict lrecomp lroc lroc_7 lrtest ls lsens lsens_7 lsens_x lstat ltable ltable_7 ltriang lv lvr2plot lvr2plot_7 m|0 ma mac macr macro makecns man manova manova_estat manova_p manovatest mantel mark markin markout marksample mat mat_capp mat_order mat_put_rr mat_rapp mata mata_clear mata_describe mata_drop mata_matdescribe mata_matsave mata_matuse mata_memory mata_mlib mata_mosave mata_rename mata_which matalabel matcproc matlist matname matr matri matrix matrix_input__dlg matstrik mcc mcci md0_ md1_ md1debug_ md2_ md2debug_ mds mds_estat mds_p mdsconfig mdslong mdsmat mdsshepard mdytoe mdytof me_derd mean means median memory memsize menl meqparse mer merg merge meta mfp mfx mhelp mhodds minbound mixed_ll mixed_ll_reparm mkassert mkdir mkmat mkspline ml ml_5 ml_adjs ml_bhhhs ml_c_d ml_check ml_clear ml_cnt ml_debug ml_defd ml_e0 ml_e0_bfgs ml_e0_cycle ml_e0_dfp ml_e0i ml_e1 ml_e1_bfgs ml_e1_bhhh ml_e1_cycle ml_e1_dfp ml_e2 ml_e2_cycle ml_ebfg0 ml_ebfr0 ml_ebfr1 ml_ebh0q ml_ebhh0 ml_ebhr0 ml_ebr0i ml_ecr0i ml_edfp0 ml_edfr0 ml_edfr1 ml_edr0i ml_eds ml_eer0i ml_egr0i ml_elf ml_elf_bfgs ml_elf_bhhh ml_elf_cycle ml_elf_dfp ml_elfi ml_elfs ml_enr0i ml_enrr0 ml_erdu0 ml_erdu0_bfgs ml_erdu0_bhhh ml_erdu0_bhhhq ml_erdu0_cycle ml_erdu0_dfp ml_erdu0_nrbfgs ml_exde ml_footnote ml_geqnr ml_grad0 ml_graph ml_hbhhh ml_hd0 ml_hold ml_init ml_inv ml_log ml_max ml_mlout ml_mlout_8 ml_model ml_nb0 ml_opt ml_p ml_plot ml_query ml_rdgrd ml_repor ml_s_e ml_score ml_searc ml_technique ml_unhold mleval mlf_ mlmatbysum mlmatsum mlog mlogi mlogit mlogit_footnote mlogit_p mlopts mlsum mlvecsum mnl0_ mor more mov move mprobit mprobit_lf mprobit_p mrdu0_ mrdu1_ mvdecode mvencode mvreg mvreg_estat n|0 nbreg nbreg_al nbreg_lf nbreg_p nbreg_sw nestreg net newey newey_7 newey_p news nl nl_7 nl_9 nl_9_p nl_p nl_p_7 nlcom nlcom_p nlexp2 nlexp2_7 nlexp2a nlexp2a_7 nlexp3 nlexp3_7 nlgom3 nlgom3_7 nlgom4 nlgom4_7 nlinit nllog3 nllog3_7 nllog4 nllog4_7 nlog_rd nlogit nlogit_p nlogitgen nlogittree nlpred no nobreak noi nois noisi noisil noisily note notes notes_dlg nptrend numlabel numlist odbc old_ver olo olog ologi ologi_sw ologit ologit_p ologitp on one onew onewa oneway op_colnm op_comp op_diff op_inv op_str opr opro oprob oprob_sw oprobi oprobi_p oprobit oprobitp opts_exclusive order orthog orthpoly ou out outf outfi outfil outfile outs outsh outshe outshee outsheet ovtest pac pac_7 palette parse parse_dissim pause pca pca_8 pca_display pca_estat pca_p pca_rotate pcamat pchart pchart_7 pchi pchi_7 pcorr pctile pentium pergram pergram_7 permute permute_8 personal peto_st pkcollapse pkcross pkequiv pkexamine pkexamine_7 pkshape pksumm pksumm_7 pl plo plot plugin pnorm pnorm_7 poisgof poiss_lf poiss_sw poisso_p poisson poisson_estat post postclose postfile postutil pperron pr prais prais_e prais_e2 prais_p predict predictnl preserve print pro prob probi probit probit_estat probit_p proc_time procoverlay procrustes procrustes_estat procrustes_p profiler prog progr progra program prop proportion prtest prtesti pwcorr pwd q\\s qby qbys qchi qchi_7 qladder qladder_7 qnorm qnorm_7 qqplot qqplot_7 qreg qreg_c qreg_p qreg_sw qu quadchk quantile quantile_7 que quer query range ranksum ratio rchart rchart_7 rcof recast reclink recode reg reg3 reg3_p regdw regr regre regre_p2 regres regres_p regress regress_estat regriv_p remap ren rena renam rename renpfix repeat replace report reshape restore ret retu retur return rm rmdir robvar roccomp roccomp_7 roccomp_8 rocf_lf rocfit rocfit_8 rocgold rocplot rocplot_7 roctab roctab_7 rolling rologit rologit_p rot rota rotat rotate rotatemat rreg rreg_p ru run runtest rvfplot rvfplot_7 rvpplot rvpplot_7 sa safesum sample sampsi sav save savedresults saveold sc sca scal scala scalar scatter scm_mine sco scob_lf scob_p scobi_sw scobit scor score scoreplot scoreplot_help scree screeplot screeplot_help sdtest sdtesti se search separate seperate serrbar serrbar_7 serset set set_defaults sfrancia sh she shel shell shewhart shewhart_7 signestimationsample signrank signtest simul simul_7 simulate simulate_8 sktest sleep slogit slogit_d2 slogit_p smooth snapspan so sor sort spearman spikeplot spikeplot_7 spikeplt spline_x split sqreg sqreg_p sret sretu sretur sreturn ssc st st_ct st_hc st_hcd st_hcd_sh st_is st_issys st_note st_promo st_set st_show st_smpl st_subid stack statsby statsby_8 stbase stci stci_7 stcox stcox_estat stcox_fr stcox_fr_ll stcox_p stcox_sw stcoxkm stcoxkm_7 stcstat stcurv stcurve stcurve_7 stdes stem stepwise stereg stfill stgen stir stjoin stmc stmh stphplot stphplot_7 stphtest stphtest_7 stptime strate strate_7 streg streg_sw streset sts sts_7 stset stsplit stsum sttocc sttoct stvary stweib su suest suest_8 sum summ summa summar summari summariz summarize sunflower sureg survcurv survsum svar svar_p svmat svy svy_disp svy_dreg svy_est svy_est_7 svy_estat svy_get svy_gnbreg_p svy_head svy_header svy_heckman_p svy_heckprob_p svy_intreg_p svy_ivreg_p svy_logistic_p svy_logit_p svy_mlogit_p svy_nbreg_p svy_ologit_p svy_oprobit_p svy_poisson_p svy_probit_p svy_regress_p svy_sub svy_sub_7 svy_x svy_x_7 svy_x_p svydes svydes_8 svygen svygnbreg svyheckman svyheckprob svyintreg svyintreg_7 svyintrg svyivreg svylc svylog_p svylogit svymarkout svymarkout_8 svymean svymlog svymlogit svynbreg svyolog svyologit svyoprob svyoprobit svyopts svypois svypois_7 svypoisson svyprobit svyprobt svyprop svyprop_7 svyratio svyreg svyreg_p svyregress svyset svyset_7 svyset_8 svytab svytab_7 svytest svytotal sw sw_8 swcnreg swcox swereg swilk swlogis swlogit swologit swoprbt swpois swprobit swqreg swtobit swweib symmetry symmi symplot symplot_7 syntax sysdescribe sysdir sysuse szroeter ta tab tab1 tab2 tab_or tabd tabdi tabdis tabdisp tabi table tabodds tabodds_7 tabstat tabu tabul tabula tabulat tabulate te tempfile tempname tempvar tes test testnl testparm teststd tetrachoric time_it timer tis tob tobi tobit tobit_p tobit_sw token tokeni tokeniz tokenize tostring total translate translator transmap treat_ll treatr_p treatreg trim trimfill trnb_cons trnb_mean trpoiss_d2 trunc_ll truncr_p truncreg tsappend tset tsfill tsline tsline_ex tsreport tsrevar tsrline tsset tssmooth tsunab ttest ttesti tut_chk tut_wait tutorial tw tware_st two twoway twoway__fpfit_serset twoway__function_gen twoway__histogram_gen twoway__ipoint_serset twoway__ipoints_serset twoway__kdensity_gen twoway__lfit_serset twoway__normgen_gen twoway__pci_serset twoway__qfit_serset twoway__scatteri_serset twoway__sunflower_gen twoway_ksm_serset ty typ type typeof u|0 unab unabbrev unabcmd update us use uselabel var var_mkcompanion var_p varbasic varfcast vargranger varirf varirf_add varirf_cgraph varirf_create varirf_ctable varirf_describe varirf_dir varirf_drop varirf_erase varirf_graph varirf_ograph varirf_rename varirf_set varirf_table varlist varlmar varnorm varsoc varstable varstable_w varstable_w2 varwle vce vec vec_fevd vec_mkphi vec_p vec_p_w vecirf_create veclmar veclmar_w vecnorm vecnorm_w vecrank vecstable verinst vers versi versio version view viewsource vif vwls wdatetof webdescribe webseek webuse weib1_lf weib2_lf weib_lf weib_lf0 weibhet_glf weibhet_glf_sh weibhet_glfa weibhet_glfa_sh weibhet_gp weibhet_ilf weibhet_ilf_sh weibhet_ilfa weibhet_ilfa_sh weibhet_ip weibu_sw weibul_p weibull weibull_c weibull_s weibullhet wh whelp whi which whil while wilc_st wilcoxon win wind windo window winexec wntestb wntestb_7 wntestq xchart xchart_7 xcorr xcorr_7 xi xi_6 xmlsav xmlsave xmluse xpose xsh xshe xshel xshell xt_iis xt_tis xtab_p xtabond xtbin_p xtclog xtcloglog xtcloglog_8 xtcloglog_d2 xtcloglog_pa_p xtcloglog_re_p xtcnt_p xtcorr xtdata xtdes xtfront_p xtfrontier xtgee xtgee_elink xtgee_estat xtgee_makeivar xtgee_p xtgee_plink xtgls xtgls_p xthaus xthausman xtht_p xthtaylor xtile xtint_p xtintreg xtintreg_8 xtintreg_d2 xtintreg_p xtivp_1 xtivp_2 xtivreg xtline xtline_ex xtlogit xtlogit_8 xtlogit_d2 xtlogit_fe_p xtlogit_pa_p xtlogit_re_p xtmixed xtmixed_estat xtmixed_p xtnb_fe xtnb_lf xtnbreg xtnbreg_pa_p xtnbreg_refe_p xtpcse xtpcse_p xtpois xtpoisson xtpoisson_d2 xtpoisson_pa_p xtpoisson_refe_p xtpred xtprobit xtprobit_8 xtprobit_d2 xtprobit_re_p xtps_fe xtps_lf xtps_ren xtps_ren_8 xtrar_p xtrc xtrc_p xtrchh xtrefe_p xtreg xtreg_be xtreg_fe xtreg_ml xtreg_pa_p xtreg_re xtregar xtrere_p xtset xtsf_ll xtsf_llti xtsum xttab xttest0 xttobit xttobit_8 xttobit_p xttrans yx yxview__barlike_draw yxview_area_draw yxview_bar_draw yxview_dot_draw yxview_dropline_draw yxview_function_draw yxview_iarrow_draw yxview_ilabels_draw yxview_normal_draw yxview_pcarrow_draw yxview_pcbarrow_draw yxview_pccapsym_draw yxview_pcscatter_draw yxview_pcspike_draw yxview_rarea_draw yxview_rbar_draw yxview_rbarm_draw yxview_rcap_draw yxview_rcapsym_draw yxview_rconnected_draw yxview_rline_draw yxview_rscatter_draw yxview_rspike_draw yxview_spike_draw yxview_sunflower_draw zap_s zinb zinb_llf zinb_plf zip zip_llf zip_p zip_plf zt_ct_5 zt_hc_5 zt_hcd_5 zt_is_5 zt_iss_5 zt_sho_5 zt_smp_5 ztbase_5 ztcox_5 ztdes_5 ztereg_5 ztfill_5 ztgen_5 ztir_5 ztjoin_5 ztnb ztnb_p ztp ztp_p zts_5 ztset_5 ztspli_5 ztsum_5 zttoct_5 ztvary_5 ztweib_5",contains:[{className:"symbol",begin:/`[a-zA-Z0-9_]+'/},{className:"variable",begin:/\$\{?[a-zA-Z0-9_]+\}?/,relevance:0},{className:"string",variants:[{begin:'`"[^\r\n]*?"\''},{begin:'"[^\r\n"]*"'}]},{className:"built_in",variants:[{begin:"\\b(abs|acos|asin|atan|atan2|atanh|ceil|cloglog|comb|cos|digamma|exp|floor|invcloglog|invlogit|ln|lnfact|lnfactorial|lngamma|log|log10|max|min|mod|reldif|round|sign|sin|sqrt|sum|tan|tanh|trigamma|trunc|betaden|Binomial|binorm|binormal|chi2|chi2tail|dgammapda|dgammapdada|dgammapdadx|dgammapdx|dgammapdxdx|F|Fden|Ftail|gammaden|gammap|ibeta|invbinomial|invchi2|invchi2tail|invF|invFtail|invgammap|invibeta|invnchi2|invnFtail|invnibeta|invnorm|invnormal|invttail|nbetaden|nchi2|nFden|nFtail|nibeta|norm|normal|normalden|normd|npnchi2|tden|ttail|uniform|abbrev|char|index|indexnot|length|lower|ltrim|match|plural|proper|real|regexm|regexr|regexs|reverse|rtrim|string|strlen|strlower|strltrim|strmatch|strofreal|strpos|strproper|strreverse|strrtrim|strtrim|strupper|subinstr|subinword|substr|trim|upper|word|wordcount|_caller|autocode|byteorder|chop|clip|cond|e|epsdouble|epsfloat|group|inlist|inrange|irecode|matrix|maxbyte|maxdouble|maxfloat|maxint|maxlong|mi|minbyte|mindouble|minfloat|minint|minlong|missing|r|recode|replay|return|s|scalar|d|date|day|dow|doy|halfyear|mdy|month|quarter|week|year|d|daily|dofd|dofh|dofm|dofq|dofw|dofy|h|halfyearly|hofd|m|mofd|monthly|q|qofd|quarterly|tin|twithin|w|weekly|wofd|y|yearly|yh|ym|yofd|yq|yw|cholesky|colnumb|colsof|corr|det|diag|diag0cnt|el|get|hadamard|I|inv|invsym|issym|issymmetric|J|matmissing|matuniform|mreldif|nullmat|rownumb|rowsof|sweep|syminv|trace|vec|vecdiag)(?=\\()"}]},e.COMMENT("^[ \t]*\\*.*$",!1),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]}}),zh)),zf.registerLanguage("step21",(Hh||(Hh=1,qh=function(e){return{name:"STEP Part 21",aliases:["p21","step","stp"],case_insensitive:!0,keywords:{$pattern:"[A-Z_][A-Z0-9_.]*",keyword:["HEADER","ENDSEC","DATA"]},contains:[{className:"meta",begin:"ISO-10303-21;",relevance:10},{className:"meta",begin:"END-ISO-10303-21;",relevance:10},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.COMMENT("/\\*\\*!","\\*/"),e.C_NUMBER_MODE,e.inherit(e.APOS_STRING_MODE,{illegal:null}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),{className:"string",begin:"'",end:"'"},{className:"symbol",variants:[{begin:"#",end:"\\d+",illegal:"\\W"}]}]}}),qh)),zf.registerLanguage("stylus",function(){if($h)return Vh;$h=1;const e=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],t=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),r=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),n=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),a=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();return Vh=function(i){const o=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(i),s={className:"variable",begin:"\\$"+i.IDENT_RE},l="(?=[.\\s\\n[:,(])";return{name:"Stylus",aliases:["styl"],case_insensitive:!1,keywords:"if else for in",illegal:"("+["\\?","(\\bReturn\\b)","(\\bEnd\\b)","(\\bend\\b)","(\\bdef\\b)",";","#\\s","\\*\\s","===\\s","\\|","%"].join("|")+")",contains:[i.QUOTE_STRING_MODE,i.APOS_STRING_MODE,i.C_LINE_COMMENT_MODE,i.C_BLOCK_COMMENT_MODE,o.HEXCOLOR,{begin:"\\.[a-zA-Z][a-zA-Z0-9_-]*"+l,className:"selector-class"},{begin:"#[a-zA-Z][a-zA-Z0-9_-]*"+l,className:"selector-id"},{begin:"\\b("+e.join("|")+")"+l,className:"selector-tag"},{className:"selector-pseudo",begin:"&?:("+r.join("|")+")"+l},{className:"selector-pseudo",begin:"&?:(:)?("+n.join("|")+")"+l},o.ATTRIBUTE_SELECTOR_MODE,{className:"keyword",begin:/@media/,starts:{end:/[{;}]/,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:t.join(" ")},contains:[o.CSS_NUMBER_MODE]}},{className:"keyword",begin:"@((-(o|moz|ms|webkit)-)?("+["charset","css","debug","extend","font-face","for","import","include","keyframes","media","mixin","page","warn","while"].join("|")+"))\\b"},s,o.CSS_NUMBER_MODE,{className:"function",begin:"^[a-zA-Z][a-zA-Z0-9_-]*\\(.*\\)",illegal:"[\\n]",returnBegin:!0,contains:[{className:"title",begin:"\\b[a-zA-Z][a-zA-Z0-9_-]*"},{className:"params",begin:/\(/,end:/\)/,contains:[o.HEXCOLOR,s,i.APOS_STRING_MODE,o.CSS_NUMBER_MODE,i.QUOTE_STRING_MODE]}]},o.CSS_VARIABLE,{className:"attribute",begin:"\\b("+a.join("|")+")\\b",starts:{end:/;|$/,contains:[o.HEXCOLOR,s,i.APOS_STRING_MODE,i.QUOTE_STRING_MODE,o.CSS_NUMBER_MODE,i.C_BLOCK_COMMENT_MODE,o.IMPORTANT,o.FUNCTION_DISPATCH],illegal:/\./,relevance:0}},o.FUNCTION_DISPATCH]}},Vh}()),zf.registerLanguage("subunit",jh?Wh:(jh=1,Wh=function(e){return{name:"SubUnit",case_insensitive:!0,contains:[{className:"string",begin:"\\[\n(multipart)?",end:"\\]\n"},{className:"string",begin:"\\d{4}-\\d{2}-\\d{2}(\\s+)\\d{2}:\\d{2}:\\d{2}.\\d+Z"},{className:"string",begin:"(\\+|-)\\d+"},{className:"keyword",relevance:10,variants:[{begin:"^(test|testing|success|successful|failure|error|skip|xfail|uxsuccess)(:?)\\s+(test)?"},{begin:"^progress(:?)(\\s+)?(pop|push)?"},{begin:"^tags:"},{begin:"^time:"}]}]}})),zf.registerLanguage("swift",function(){if(Kh)return Qh;function e(e){return e?"string"==typeof e?e:e.source:null}function t(e){return r("(?=",e,")")}function r(...t){return t.map(t=>e(t)).join("")}function n(...t){const r=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(t);return"("+(r.capture?"":"?:")+t.map(t=>e(t)).join("|")+")"}Kh=1;const a=e=>r(/\b/,e,/\w$/.test(e)?/\b/:/\B/),i=["Protocol","Type"].map(a),o=["init","self"].map(a),s=["Any","Self"],l=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],c=["false","nil","true"],d=["assignment","associativity","higherThan","left","lowerThan","none","right"],u=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],p=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],_=n(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),m=n(_,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),g=r(_,m,"*"),h=n(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),f=n(h,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),E=r(h,f,"*"),b=r(/[A-Z]/,f,"*"),S=["attached","autoclosure",r(/convention\(/,n("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",r(/objc\(/,E,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],v=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];return Qh=function(e){const _={match:/\s+/,relevance:0},h=e.COMMENT("/\\*","\\*/",{contains:["self"]}),T=[e.C_LINE_COMMENT_MODE,h],y={match:[/\./,n(...i,...o)],className:{2:"keyword"}},C={match:r(/\./,n(...l)),relevance:0},N=l.filter(e=>"string"==typeof e).concat(["_|0"]),R={variants:[{className:"keyword",match:n(...l.filter(e=>"string"!=typeof e).concat(s).map(a),...o)}]},A={$pattern:n(/\b\w+/,/#\w+/),keyword:N.concat(u),literal:c},O=[y,C,R],I=[{match:r(/\./,n(...p)),relevance:0},{className:"built_in",match:r(/\b/,n(...p),/(?=\()/)}],x={match:/->/,relevance:0},w=[x,{className:"operator",relevance:0,variants:[{match:g},{match:`\\.(\\.|${m})+`}]}],D="([0-9]_*)+",M="([0-9a-fA-F]_*)+",k={className:"number",relevance:0,variants:[{match:`\\b(${D})(\\.(${D}))?([eE][+-]?(${D}))?\\b`},{match:`\\b0x(${M})(\\.(${M}))?([pP][+-]?(${D}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},L=(e="")=>({className:"subst",variants:[{match:r(/\\/,e,/[0\\tnr"']/)},{match:r(/\\/,e,/u\{[0-9a-fA-F]{1,8}\}/)}]}),P=(e="")=>({className:"subst",match:r(/\\/,e,/[\t ]*(?:[\r\n]|\r\n)/)}),F=(e="")=>({className:"subst",label:"interpol",begin:r(/\\/,e,/\(/),end:/\)/}),B=(e="")=>({begin:r(e,/"""/),end:r(/"""/,e),contains:[L(e),P(e),F(e)]}),U=(e="")=>({begin:r(e,/"/),end:r(/"/,e),contains:[L(e),F(e)]}),G={className:"string",variants:[B(),B("#"),B("##"),B("###"),U(),U("#"),U("##"),U("###")]},z=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}],Y={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:z},q=e=>{const t=r(e,/\//),n=r(/\//,e);return{begin:t,end:n,contains:[...z,{scope:"comment",begin:`#(?!.*${n})`,end:/$/}]}},H={scope:"regexp",variants:[q("###"),q("##"),q("#"),Y]},V={match:r(/`/,E,/`/)},$=[V,{className:"variable",match:/\$\d+/},{className:"variable",match:`\\$${f}+`}],W=[{match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:v,contains:[...w,k,G]}]}},{scope:"keyword",match:r(/@/,n(...S),t(n(/\(/,/\s+/)))},{scope:"meta",match:r(/@/,E)}],j={match:t(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:r(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,f,"+")},{className:"type",match:b,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:r(/\s+&\s+/,t(b)),relevance:0}]},Q={begin:/</,end:/>/,keywords:A,contains:[...T,...O,...W,x,j]};j.contains.push(Q);const K={begin:/\(/,end:/\)/,relevance:0,keywords:A,contains:["self",{match:r(E,/\s*:/),keywords:"_|0",relevance:0},...T,H,...O,...I,...w,k,G,...$,...W,j]},X={begin:/</,end:/>/,keywords:"repeat each",contains:[...T,j]},Z={begin:/\(/,end:/\)/,keywords:A,contains:[{begin:n(t(r(E,/\s*:/)),t(r(E,/\s+/,E,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:E}]},...T,...O,...w,k,G,...W,j,K],endsParent:!0,illegal:/["']/},J={match:[/(func|macro)/,/\s+/,n(V.match,E,g)],className:{1:"keyword",3:"title.function"},contains:[X,Z,_],illegal:[/\[/,/%/]},ee={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[X,Z,_],illegal:/\[|%/},te={match:[/operator/,/\s+/,g],className:{1:"keyword",3:"title"}},re={begin:[/precedencegroup/,/\s+/,b],className:{1:"keyword",3:"title"},contains:[j],keywords:[...d,...c],end:/}/},ne={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,E,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:A,contains:[X,...O,{begin:/:/,end:/\{/,keywords:A,contains:[{scope:"title.class.inherited",match:b},...O],relevance:0}]};for(const e of G.variants){const t=e.contains.find(e=>"interpol"===e.label);t.keywords=A;const r=[...O,...I,...w,k,G,...$];t.contains=[...r,{begin:/\(/,end:/\)/,contains:["self",...r]}]}return{name:"Swift",keywords:A,contains:[...T,J,ee,{match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},{match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},ne,te,re,{beginKeywords:"import",end:/$/,contains:[...T],relevance:0},H,...O,...I,...w,k,G,...$,...W,j,K]}},Qh}()),zf.registerLanguage("taggerscript",Zh?Xh:(Zh=1,Xh=function(e){return{name:"Tagger Script",contains:[{className:"comment",begin:/\$noop\(/,end:/\)/,contains:[{begin:/\\[()]/},{begin:/\(/,end:/\)/,contains:[{begin:/\\[()]/},"self"]}],relevance:10},{className:"keyword",begin:/\$[_a-zA-Z0-9]+(?=\()/},{className:"variable",begin:/%[_a-zA-Z0-9:]+%/},{className:"symbol",begin:/\\[\\nt$%,()]/},{className:"symbol",begin:/\\u[a-fA-F0-9]{4}/}]}})),zf.registerLanguage("yaml",(ef||(ef=1,Jh=function(e){const t="true false yes no null",r="[\\w#;/?:@&=+$,.~*'()[\\]]+",n={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},a=e.inherit(n,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),i={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},o={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},s={begin:/\{/,end:/\}/,contains:[o],illegal:"\\n",relevance:0},l={begin:"\\[",end:"\\]",contains:[o],illegal:"\\n",relevance:0},c=[{className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+r},{className:"type",begin:"!<"+r+">"},{className:"type",begin:"!"+r},{className:"type",begin:"!!"+r},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},i,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},s,l,{className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},n],d=[...c];return d.pop(),d.push(a),o.contains=d,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:c}}),Jh)),zf.registerLanguage("tap",(rf||(rf=1,tf=function(e){return{name:"Test Anything Protocol",case_insensitive:!0,contains:[e.HASH_COMMENT_MODE,{className:"meta",variants:[{begin:"^TAP version (\\d+)$"},{begin:"^1\\.\\.(\\d+)$"}]},{begin:/---$/,end:"\\.\\.\\.$",subLanguage:"yaml",relevance:0},{className:"number",begin:" (\\d+) "},{className:"symbol",variants:[{begin:"^ok"},{begin:"^not ok"}]}]}}),tf)),zf.registerLanguage("tcl",(af||(af=1,nf=function(e){const t=e.regex,r=/[a-zA-Z_][a-zA-Z0-9_]*/,n={className:"number",variants:[e.BINARY_NUMBER_MODE,e.C_NUMBER_MODE]};return{name:"Tcl",aliases:["tk"],keywords:["after","append","apply","array","auto_execok","auto_import","auto_load","auto_mkindex","auto_mkindex_old","auto_qualify","auto_reset","bgerror","binary","break","catch","cd","chan","clock","close","concat","continue","dde","dict","encoding","eof","error","eval","exec","exit","expr","fblocked","fconfigure","fcopy","file","fileevent","filename","flush","for","foreach","format","gets","glob","global","history","http","if","incr","info","interp","join","lappend|10","lassign|10","lindex|10","linsert|10","list","llength|10","load","lrange|10","lrepeat|10","lreplace|10","lreverse|10","lsearch|10","lset|10","lsort|10","mathfunc","mathop","memory","msgcat","namespace","open","package","parray","pid","pkg::create","pkg_mkIndex","platform","platform::shell","proc","puts","pwd","read","refchan","regexp","registry","regsub|10","rename","return","safe","scan","seek","set","socket","source","split","string","subst","switch","tcl_endOfWord","tcl_findLibrary","tcl_startOfNextWord","tcl_startOfPreviousWord","tcl_wordBreakAfter","tcl_wordBreakBefore","tcltest","tclvars","tell","time","tm","trace","unknown","unload","unset","update","uplevel","upvar","variable","vwait","while"],contains:[e.COMMENT(";[ \\t]*#","$"),e.COMMENT("^[ \\t]*#","$"),{beginKeywords:"proc",end:"[\\{]",excludeEnd:!0,contains:[{className:"title",begin:"[ \\t\\n\\r]+(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*",end:"[ \\t\\n\\r]",endsWithParent:!0,excludeEnd:!0}]},{className:"variable",variants:[{begin:t.concat(/\$/,t.optional(/::/),r,"(::",r,")*")},{begin:"\\$\\{(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*",end:"\\}",contains:[n]}]},{className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.inherit(e.QUOTE_STRING_MODE,{illegal:null})]},n]}}),nf)),zf.registerLanguage("thrift",(sf||(sf=1,of=function(e){const t=["bool","byte","i16","i32","i64","double","string","binary"];return{name:"Thrift",keywords:{keyword:["namespace","const","typedef","struct","enum","service","exception","void","oneway","set","list","map","required","optional"],type:t,literal:"true false"},contains:[e.QUOTE_STRING_MODE,e.NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"class",beginKeywords:"struct enum service exception",end:/\{/,illegal:/\n/,contains:[e.inherit(e.TITLE_MODE,{starts:{endsWithParent:!0,excludeEnd:!0}})]},{begin:"\\b(set|list|map)\\s*<",keywords:{type:[...t,"set","list","map"]},end:">",contains:["self"]}]}}),of)),zf.registerLanguage("tp",(cf||(cf=1,lf=function(e){const t={className:"number",begin:"[1-9][0-9]*",relevance:0},r={className:"symbol",begin:":[^\\]]+"};return{name:"TP",keywords:{keyword:["ABORT","ACC","ADJUST","AND","AP_LD","BREAK","CALL","CNT","COL","CONDITION","CONFIG","DA","DB","DIV","DETECT","ELSE","END","ENDFOR","ERR_NUM","ERROR_PROG","FINE","FOR","GP","GUARD","INC","IF","JMP","LINEAR_MAX_SPEED","LOCK","MOD","MONITOR","OFFSET","Offset","OR","OVERRIDE","PAUSE","PREG","PTH","RT_LD","RUN","SELECT","SKIP","Skip","TA","TB","TO","TOOL_OFFSET","Tool_Offset","UF","UT","UFRAME_NUM","UTOOL_NUM","UNLOCK","WAIT","X","Y","Z","W","P","R","STRLEN","SUBSTR","FINDSTR","VOFFSET","PROG","ATTR","MN","POS"],literal:["ON","OFF","max_speed","LPOS","JPOS","ENABLE","DISABLE","START","STOP","RESET"]},contains:[{className:"built_in",begin:"(AR|P|PAYLOAD|PR|R|SR|RSR|LBL|VR|UALM|MESSAGE|UTOOL|UFRAME|TIMER|TIMER_OVERFLOW|JOINT_MAX_SPEED|RESUME_PROG|DIAG_REC)\\[",end:"\\]",contains:["self",t,r]},{className:"built_in",begin:"(AI|AO|DI|DO|F|RI|RO|UI|UO|GI|GO|SI|SO)\\[",end:"\\]",contains:["self",t,e.QUOTE_STRING_MODE,r]},{className:"keyword",begin:"/(PROG|ATTR|MN|POS|END)\\b"},{className:"keyword",begin:"(CALL|RUN|POINT_LOGIC|LBL)\\b"},{className:"keyword",begin:"\\b(ACC|CNT|Skip|Offset|PSPD|RT_LD|AP_LD|Tool_Offset)"},{className:"number",begin:"\\d+(sec|msec|mm/sec|cm/min|inch/min|deg/sec|mm|in|cm)?\\b",relevance:0},e.COMMENT("//","[;$]"),e.COMMENT("!","[;$]"),e.COMMENT("--eg:","$"),e.QUOTE_STRING_MODE,{className:"string",begin:"'",end:"'"},e.C_NUMBER_MODE,{className:"variable",begin:"\\$[A-Za-z0-9_]+"}]}}),lf)),zf.registerLanguage("twig",(uf||(uf=1,df=function(e){const t=e.regex,r=["absolute_url","asset|0","asset_version","attribute","block","constant","controller|0","country_timezones","csrf_token","cycle","date","dump","expression","form|0","form_end","form_errors","form_help","form_label","form_rest","form_row","form_start","form_widget","html_classes","include","is_granted","logout_path","logout_url","max","min","parent","path|0","random","range","relative_path","render","render_esi","source","template_from_string","url|0"];let n=["apply","autoescape","block","cache","deprecated","do","embed","extends","filter","flush","for","form_theme","from","if","import","include","macro","sandbox","set","stopwatch","trans","trans_default_domain","transchoice","use","verbatim","with"];n=n.concat(n.map(e=>`end${e}`));const a={scope:"string",variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/}]},i={scope:"number",match:/\d+/},o={begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,contains:[a,i]},s={beginKeywords:r.join(" "),keywords:{name:r},relevance:0,contains:[o]},l={match:/\|(?=[A-Za-z_]+:?)/,beginScope:"punctuation",relevance:0,contains:[{match:/[A-Za-z_]+:?/,keywords:["abs","abbr_class","abbr_method","batch","capitalize","column","convert_encoding","country_name","currency_name","currency_symbol","data_uri","date","date_modify","default","escape","file_excerpt","file_link","file_relative","filter","first","format","format_args","format_args_as_text","format_currency","format_date","format_datetime","format_file","format_file_from_text","format_number","format_time","html_to_markdown","humanize","inky_to_html","inline_css","join","json_encode","keys","language_name","last","length","locale_name","lower","map","markdown","markdown_to_html","merge","nl2br","number_format","raw","reduce","replace","reverse","round","slice","slug","sort","spaceless","split","striptags","timezone_name","title","trans","transchoice","trim","u|0","upper","url_encode","yaml_dump","yaml_encode"]}]},c=(e,{relevance:r})=>({beginScope:{1:"template-tag",3:"name"},relevance:r||2,endScope:"template-tag",begin:[/\{%/,/\s*/,t.either(...e)],end:/%\}/,keywords:"in",contains:[l,s,a,i]}),d=c(n,{relevance:2}),u=c([/[a-z_]+/],{relevance:1});return{name:"Twig",aliases:["craftcms"],case_insensitive:!0,subLanguage:"xml",contains:[e.COMMENT(/\{#/,/#\}/),d,u,{className:"template-variable",begin:/\{\{/,end:/\}\}/,contains:["self",l,s,a,i]}]}}),df)),zf.registerLanguage("typescript",function(){if(_f)return pf;_f=1;const e="[A-Za-z$_][0-9A-Za-z$_]*",t=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],r=["true","false","null","undefined","NaN","Infinity"],n=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],a=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],i=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],o=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],s=[].concat(i,n,a);function l(l){const c=l.regex,d=e,u="<>",p="</>",_={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const r=e[0].length+e.index,n=e.input[r];if("<"===n||","===n)return void t.ignoreMatch();let a;">"===n&&(((e,{after:t})=>{const r="</"+e[0].slice(1);return-1!==e.input.indexOf(r,t)})(e,{after:r})||t.ignoreMatch());const i=e.input.substring(r);((a=i.match(/^\s*=/))||(a=i.match(/^\s+extends\s+/))&&0===a.index)&&t.ignoreMatch()}},m={$pattern:e,keyword:t,literal:r,built_in:s,"variable.language":o},g="[0-9](_?[0-9])*",h=`\\.(${g})`,f="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",E={className:"number",variants:[{begin:`(\\b(${f})((${h})|\\.)?|(${h}))[eE][+-]?(${g})\\b`},{begin:`\\b(${f})\\b((${h})\\b|\\.)?|(${h})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},b={className:"subst",begin:"\\$\\{",end:"\\}",keywords:m,contains:[]},S={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[l.BACKSLASH_ESCAPE,b],subLanguage:"xml"}},v={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[l.BACKSLASH_ESCAPE,b],subLanguage:"css"}},T={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[l.BACKSLASH_ESCAPE,b],subLanguage:"graphql"}},y={className:"string",begin:"`",end:"`",contains:[l.BACKSLASH_ESCAPE,b]},C={className:"comment",variants:[l.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:d+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),l.C_BLOCK_COMMENT_MODE,l.C_LINE_COMMENT_MODE]},N=[l.APOS_STRING_MODE,l.QUOTE_STRING_MODE,S,v,T,y,{match:/\$\d+/},E];b.contains=N.concat({begin:/\{/,end:/\}/,keywords:m,contains:["self"].concat(N)});const R=[].concat(C,b.contains),A=R.concat([{begin:/(\s*)\(/,end:/\)/,keywords:m,contains:["self"].concat(R)}]),O={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:m,contains:A},I={variants:[{match:[/class/,/\s+/,d,/\s+/,/extends/,/\s+/,c.concat(d,"(",c.concat(/\./,d),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,d],scope:{1:"keyword",3:"title.class"}}]},x={relevance:0,match:c.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...n,...a]}},w={variants:[{match:[/function/,/\s+/,d,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[O],illegal:/%/};const D={match:c.concat(/\b/,function(e){return c.concat("(?!",e.join("|"),")")}([...i,"super","import"].map(e=>`${e}\\s*\\(`)),d,c.lookahead(/\s*\(/)),className:"title.function",relevance:0},M={begin:c.concat(/\./,c.lookahead(c.concat(d,/(?![0-9A-Za-z$_(])/))),end:d,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},k={match:[/get|set/,/\s+/,d,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},O]},L="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+l.UNDERSCORE_IDENT_RE+")\\s*=>",P={match:[/const|var|let/,/\s+/,d,/\s*/,/=\s*/,/(async\s*)?/,c.lookahead(L)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[O]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:m,exports:{PARAMS_CONTAINS:A,CLASS_REFERENCE:x},illegal:/#(?![$_A-z])/,contains:[l.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},l.APOS_STRING_MODE,l.QUOTE_STRING_MODE,S,v,T,y,C,{match:/\$\d+/},E,x,{scope:"attr",match:d+c.lookahead(":"),relevance:0},P,{begin:"("+l.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[C,l.REGEXP_MODE,{className:"function",begin:L,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:l.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:m,contains:A}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:u,end:p},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:_.begin,"on:begin":_.isTrulyOpeningTag,end:_.end}],subLanguage:"xml",contains:[{begin:_.begin,end:_.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+l.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[O,l.inherit(l.TITLE_MODE,{begin:d,className:"title.function"})]},{match:/\.\.\./,relevance:0},M,{match:"\\$"+d,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[O]},D,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},I,k,{match:/\$[(.]/}]}}return pf=function(n){const a=n.regex,i=l(n),c=e,d=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],u={begin:[/namespace/,/\s+/,n.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},p={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:d},contains:[i.exports.CLASS_REFERENCE]},_={$pattern:e,keyword:t.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:r,built_in:s.concat(d),"variable.language":o},m={className:"meta",begin:"@"+c},g=(e,t,r)=>{const n=e.contains.findIndex(e=>e.label===t);if(-1===n)throw new Error("can not find mode to replace");e.contains.splice(n,1,r)};Object.assign(i.keywords,_),i.exports.PARAMS_CONTAINS.push(m);const h=i.contains.find(e=>"attr"===e.scope),f=Object.assign({},h,{match:a.concat(c,a.lookahead(/\s*\?:/))});return i.exports.PARAMS_CONTAINS.push([i.exports.CLASS_REFERENCE,h,f]),i.contains=i.contains.concat([m,u,p,f]),g(i,"shebang",n.SHEBANG()),g(i,"use_strict",{className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/}),i.contains.find(e=>"func.def"===e.label).relevance=0,Object.assign(i,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),i},pf}()),zf.registerLanguage("vala",(gf||(gf=1,mf=function(e){return{name:"Vala",keywords:{keyword:"char uchar unichar int uint long ulong short ushort int8 int16 int32 int64 uint8 uint16 uint32 uint64 float double bool struct enum string void weak unowned owned async signal static abstract interface override virtual delegate if while do for foreach else switch case break default return try catch public private protected internal using new this get set const stdout stdin stderr var",built_in:"DBus GLib CCode Gee Object Gtk Posix",literal:"false true null"},contains:[{className:"class",beginKeywords:"class interface namespace",end:/\{/,excludeEnd:!0,illegal:"[^,:\\n\\s\\.]",contains:[e.UNDERSCORE_TITLE_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"string",begin:'"""',end:'"""',relevance:5},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.C_NUMBER_MODE,{className:"meta",begin:"^#",end:"$"}]}}),mf)),zf.registerLanguage("vbnet",(ff||(ff=1,hf=function(e){const t=e.regex,r=/\d{1,2}\/\d{1,2}\/\d{4}/,n=/\d{4}-\d{1,2}-\d{1,2}/,a=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,i=/\d{1,2}(:\d{1,2}){1,2}/,o={className:"literal",variants:[{begin:t.concat(/# */,t.either(n,r),/ *#/)},{begin:t.concat(/# */,i,/ *#/)},{begin:t.concat(/# */,a,/ *#/)},{begin:t.concat(/# */,t.either(n,r),/ +/,t.either(a,i),/ *#/)}]},s=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),l=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]});return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0,classNameAliases:{label:"symbol"},keywords:{keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort",type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort",literal:"true false nothing"},illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[{className:"string",begin:/"(""|[^/n])"C\b/},{className:"string",begin:/"/,end:/"/,illegal:/\n/,contains:[{begin:/""/}]},o,{className:"number",relevance:0,variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},{className:"label",begin:/^\w+:/},s,l,{className:"meta",begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,end:/$/,keywords:{keyword:"const disable else elseif enable end externalsource if region then"},contains:[l]}]}}),hf)),zf.registerLanguage("vbscript",(bf||(bf=1,Ef=function(e){const t=e.regex,r=["lcase","month","vartype","instrrev","ubound","setlocale","getobject","rgb","getref","string","weekdayname","rnd","dateadd","monthname","now","day","minute","isarray","cbool","round","formatcurrency","conversions","csng","timevalue","second","year","space","abs","clng","timeserial","fixs","len","asc","isempty","maths","dateserial","atn","timer","isobject","filter","weekday","datevalue","ccur","isdate","instr","datediff","formatdatetime","replace","isnull","right","sgn","array","snumeric","log","cdbl","hex","chr","lbound","msgbox","ucase","getlocale","cos","cdate","cbyte","rtrim","join","hour","oct","typename","trim","strcomp","int","createobject","loadpicture","tan","formatnumber","mid","split","cint","sin","datepart","ltrim","sqr","time","derived","eval","date","formatpercent","exp","inputbox","left","ascw","chrw","regexp","cstr","err"];return{name:"VBScript",aliases:["vbs"],case_insensitive:!0,keywords:{keyword:["call","class","const","dim","do","loop","erase","execute","executeglobal","exit","for","each","next","function","if","then","else","on","error","option","explicit","new","private","property","let","get","public","randomize","redim","rem","select","case","set","stop","sub","while","wend","with","end","to","elseif","is","or","xor","and","not","class_initialize","class_terminate","default","preserve","in","me","byval","byref","step","resume","goto"],built_in:["server","response","request","scriptengine","scriptenginebuildversion","scriptengineminorversion","scriptenginemajorversion"],literal:["true","false","null","nothing","empty"]},illegal:"//",contains:[{begin:t.concat(t.either(...r),"\\s*\\("),relevance:0,keywords:{built_in:r}},e.inherit(e.QUOTE_STRING_MODE,{contains:[{begin:'""'}]}),e.COMMENT(/'/,/$/,{relevance:0}),e.C_NUMBER_MODE]}}),Ef)),zf.registerLanguage("vbscript-html",vf?Sf:(vf=1,Sf=function(e){return{name:"VBScript in HTML",subLanguage:"xml",contains:[{begin:"<%",end:"%>",subLanguage:"vbscript"}]}})),zf.registerLanguage("verilog",(yf||(yf=1,Tf=function(e){const t=e.regex,r=["begin_keywords","celldefine","default_nettype","default_decay_time","default_trireg_strength","define","delay_mode_distributed","delay_mode_path","delay_mode_unit","delay_mode_zero","else","elsif","end_keywords","endcelldefine","endif","ifdef","ifndef","include","line","nounconnected_drive","pragma","resetall","timescale","unconnected_drive","undef","undefineall"];return{name:"Verilog",aliases:["v","sv","svh"],case_insensitive:!1,keywords:{$pattern:/\$?[\w]+(\$[\w]+)*/,keyword:["accept_on","alias","always","always_comb","always_ff","always_latch","and","assert","assign","assume","automatic","before","begin","bind","bins","binsof","bit","break","buf|0","bufif0","bufif1","byte","case","casex","casez","cell","chandle","checker","class","clocking","cmos","config","const","constraint","context","continue","cover","covergroup","coverpoint","cross","deassign","default","defparam","design","disable","dist","do","edge","else","end","endcase","endchecker","endclass","endclocking","endconfig","endfunction","endgenerate","endgroup","endinterface","endmodule","endpackage","endprimitive","endprogram","endproperty","endspecify","endsequence","endtable","endtask","enum","event","eventually","expect","export","extends","extern","final","first_match","for","force","foreach","forever","fork","forkjoin","function","generate|5","genvar","global","highz0","highz1","if","iff","ifnone","ignore_bins","illegal_bins","implements","implies","import","incdir","include","initial","inout","input","inside","instance","int","integer","interconnect","interface","intersect","join","join_any","join_none","large","let","liblist","library","local","localparam","logic","longint","macromodule","matches","medium","modport","module","nand","negedge","nettype","new","nexttime","nmos","nor","noshowcancelled","not","notif0","notif1","or","output","package","packed","parameter","pmos","posedge","primitive","priority","program","property","protected","pull0","pull1","pulldown","pullup","pulsestyle_ondetect","pulsestyle_onevent","pure","rand","randc","randcase","randsequence","rcmos","real","realtime","ref","reg","reject_on","release","repeat","restrict","return","rnmos","rpmos","rtran","rtranif0","rtranif1","s_always","s_eventually","s_nexttime","s_until","s_until_with","scalared","sequence","shortint","shortreal","showcancelled","signed","small","soft","solve","specify","specparam","static","string","strong","strong0","strong1","struct","super","supply0","supply1","sync_accept_on","sync_reject_on","table","tagged","task","this","throughout","time","timeprecision","timeunit","tran","tranif0","tranif1","tri","tri0","tri1","triand","trior","trireg","type","typedef","union","unique","unique0","unsigned","until","until_with","untyped","use","uwire","var","vectored","virtual","void","wait","wait_order","wand","weak","weak0","weak1","while","wildcard","wire","with","within","wor","xnor","xor"],literal:["null"],built_in:["$finish","$stop","$exit","$fatal","$error","$warning","$info","$realtime","$time","$printtimescale","$bitstoreal","$bitstoshortreal","$itor","$signed","$cast","$bits","$stime","$timeformat","$realtobits","$shortrealtobits","$rtoi","$unsigned","$asserton","$assertkill","$assertpasson","$assertfailon","$assertnonvacuouson","$assertoff","$assertcontrol","$assertpassoff","$assertfailoff","$assertvacuousoff","$isunbounded","$sampled","$fell","$changed","$past_gclk","$fell_gclk","$changed_gclk","$rising_gclk","$steady_gclk","$coverage_control","$coverage_get","$coverage_save","$set_coverage_db_name","$rose","$stable","$past","$rose_gclk","$stable_gclk","$future_gclk","$falling_gclk","$changing_gclk","$display","$coverage_get_max","$coverage_merge","$get_coverage","$load_coverage_db","$typename","$unpacked_dimensions","$left","$low","$increment","$clog2","$ln","$log10","$exp","$sqrt","$pow","$floor","$ceil","$sin","$cos","$tan","$countbits","$onehot","$isunknown","$fatal","$warning","$dimensions","$right","$high","$size","$asin","$acos","$atan","$atan2","$hypot","$sinh","$cosh","$tanh","$asinh","$acosh","$atanh","$countones","$onehot0","$error","$info","$random","$dist_chi_square","$dist_erlang","$dist_exponential","$dist_normal","$dist_poisson","$dist_t","$dist_uniform","$q_initialize","$q_remove","$q_exam","$async$and$array","$async$nand$array","$async$or$array","$async$nor$array","$sync$and$array","$sync$nand$array","$sync$or$array","$sync$nor$array","$q_add","$q_full","$psprintf","$async$and$plane","$async$nand$plane","$async$or$plane","$async$nor$plane","$sync$and$plane","$sync$nand$plane","$sync$or$plane","$sync$nor$plane","$system","$display","$displayb","$displayh","$displayo","$strobe","$strobeb","$strobeh","$strobeo","$write","$readmemb","$readmemh","$writememh","$value$plusargs","$dumpvars","$dumpon","$dumplimit","$dumpports","$dumpportson","$dumpportslimit","$writeb","$writeh","$writeo","$monitor","$monitorb","$monitorh","$monitoro","$writememb","$dumpfile","$dumpoff","$dumpall","$dumpflush","$dumpportsoff","$dumpportsall","$dumpportsflush","$fclose","$fdisplay","$fdisplayb","$fdisplayh","$fdisplayo","$fstrobe","$fstrobeb","$fstrobeh","$fstrobeo","$swrite","$swriteb","$swriteh","$swriteo","$fscanf","$fread","$fseek","$fflush","$feof","$fopen","$fwrite","$fwriteb","$fwriteh","$fwriteo","$fmonitor","$fmonitorb","$fmonitorh","$fmonitoro","$sformat","$sformatf","$fgetc","$ungetc","$fgets","$sscanf","$rewind","$ftell","$ferror"]},contains:[e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.QUOTE_STRING_MODE,{scope:"number",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/\b((\d+'([bhodBHOD]))[0-9xzXZa-fA-F_]+)/},{begin:/\B(('([bhodBHOD]))[0-9xzXZa-fA-F_]+)/},{begin:/\b[0-9][0-9_]*/,relevance:0}]},{scope:"variable",variants:[{begin:"#\\((?!parameter).+\\)"},{begin:"\\.\\w+",relevance:0}]},{scope:"variable.constant",match:t.concat(/`/,t.either("__FILE__","__LINE__"))},{scope:"meta",begin:t.concat(/`/,t.either(...r)),end:/$|\/\/|\/\*/,returnEnd:!0,keywords:r}]}}),Tf)),zf.registerLanguage("vhdl",(Nf||(Nf=1,Cf=function(e){const t="\\d(_|\\d)*",r="[eE][-+]?"+t,n="\\b("+t+"#\\w+(\\.\\w+)?#("+r+")?|"+t+"(\\."+t+")?("+r+")?)";return{name:"VHDL",case_insensitive:!0,keywords:{keyword:["abs","access","after","alias","all","and","architecture","array","assert","assume","assume_guarantee","attribute","begin","block","body","buffer","bus","case","component","configuration","constant","context","cover","disconnect","downto","default","else","elsif","end","entity","exit","fairness","file","for","force","function","generate","generic","group","guarded","if","impure","in","inertial","inout","is","label","library","linkage","literal","loop","map","mod","nand","new","next","nor","not","null","of","on","open","or","others","out","package","parameter","port","postponed","procedure","process","property","protected","pure","range","record","register","reject","release","rem","report","restrict","restrict_guarantee","return","rol","ror","select","sequence","severity","shared","signal","sla","sll","sra","srl","strong","subtype","then","to","transport","type","unaffected","units","until","use","variable","view","vmode","vprop","vunit","wait","when","while","with","xnor","xor"],built_in:["boolean","bit","character","integer","time","delay_length","natural","positive","string","bit_vector","file_open_kind","file_open_status","std_logic","std_logic_vector","unsigned","signed","boolean_vector","integer_vector","std_ulogic","std_ulogic_vector","unresolved_unsigned","u_unsigned","unresolved_signed","u_signed","real_vector","time_vector"],literal:["false","true","note","warning","error","failure","line","text","side","width"]},illegal:/\{/,contains:[e.C_BLOCK_COMMENT_MODE,e.COMMENT("--","$"),e.QUOTE_STRING_MODE,{className:"number",begin:n,relevance:0},{className:"string",begin:"'(U|X|0|1|Z|W|L|H|-)'",contains:[e.BACKSLASH_ESCAPE]},{className:"symbol",begin:"'[A-Za-z](_?[A-Za-z0-9])*",contains:[e.BACKSLASH_ESCAPE]}]}}),Cf)),zf.registerLanguage("vim",(Af||(Af=1,Rf=function(e){return{name:"Vim Script",keywords:{$pattern:/[!#@\w]+/,keyword:"N|0 P|0 X|0 a|0 ab abc abo al am an|0 ar arga argd arge argdo argg argl argu as au aug aun b|0 bN ba bad bd be bel bf bl bm bn bo bp br brea breaka breakd breakl bro bufdo buffers bun bw c|0 cN cNf ca cabc caddb cad caddf cal cat cb cc ccl cd ce cex cf cfir cgetb cgete cg changes chd che checkt cl cla clo cm cmapc cme cn cnew cnf cno cnorea cnoreme co col colo com comc comp con conf cope cp cpf cq cr cs cst cu cuna cunme cw delm deb debugg delc delf dif diffg diffo diffp diffpu diffs diffthis dig di dl dell dj dli do doautoa dp dr ds dsp e|0 ea ec echoe echoh echom echon el elsei em en endfo endf endt endw ene ex exe exi exu f|0 files filet fin fina fini fir fix fo foldc foldd folddoc foldo for fu go gr grepa gu gv ha helpf helpg helpt hi hid his ia iabc if ij il im imapc ime ino inorea inoreme int is isp iu iuna iunme j|0 ju k|0 keepa kee keepj lN lNf l|0 lad laddb laddf la lan lat lb lc lch lcl lcs le lefta let lex lf lfir lgetb lgete lg lgr lgrepa lh ll lla lli lmak lm lmapc lne lnew lnf ln loadk lo loc lockv lol lope lp lpf lr ls lt lu lua luad luaf lv lvimgrepa lw m|0 ma mak map mapc marks mat me menut mes mk mks mksp mkv mkvie mod mz mzf nbc nb nbs new nm nmapc nme nn nnoreme noa no noh norea noreme norm nu nun nunme ol o|0 om omapc ome on ono onoreme opt ou ounme ow p|0 profd prof pro promptr pc ped pe perld po popu pp pre prev ps pt ptN ptf ptj ptl ptn ptp ptr pts pu pw py3 python3 py3d py3f py pyd pyf quita qa rec red redi redr redraws reg res ret retu rew ri rightb rub rubyd rubyf rund ru rv sN san sa sal sav sb sbN sba sbf sbl sbm sbn sbp sbr scrip scripte scs se setf setg setl sf sfir sh sim sig sil sl sla sm smap smapc sme sn sni sno snor snoreme sor so spelld spe spelli spellr spellu spellw sp spr sre st sta startg startr star stopi stj sts sun sunm sunme sus sv sw sy synti sync tN tabN tabc tabdo tabe tabf tabfir tabl tabm tabnew tabn tabo tabp tabr tabs tab ta tags tc tcld tclf te tf th tj tl tm tn to tp tr try ts tu u|0 undoj undol una unh unl unlo unm unme uns up ve verb vert vim vimgrepa vi viu vie vm vmapc vme vne vn vnoreme vs vu vunme windo w|0 wN wa wh wi winc winp wn wp wq wqa ws wu wv x|0 xa xmapc xm xme xn xnoreme xu xunme y|0 z|0 ~ Next Print append abbreviate abclear aboveleft all amenu anoremenu args argadd argdelete argedit argglobal arglocal argument ascii autocmd augroup aunmenu buffer bNext ball badd bdelete behave belowright bfirst blast bmodified bnext botright bprevious brewind break breakadd breakdel breaklist browse bunload bwipeout change cNext cNfile cabbrev cabclear caddbuffer caddexpr caddfile call catch cbuffer cclose center cexpr cfile cfirst cgetbuffer cgetexpr cgetfile chdir checkpath checktime clist clast close cmap cmapclear cmenu cnext cnewer cnfile cnoremap cnoreabbrev cnoremenu copy colder colorscheme command comclear compiler continue confirm copen cprevious cpfile cquit crewind cscope cstag cunmap cunabbrev cunmenu cwindow delete delmarks debug debuggreedy delcommand delfunction diffupdate diffget diffoff diffpatch diffput diffsplit digraphs display deletel djump dlist doautocmd doautoall deletep drop dsearch dsplit edit earlier echo echoerr echohl echomsg else elseif emenu endif endfor endfunction endtry endwhile enew execute exit exusage file filetype find finally finish first fixdel fold foldclose folddoopen folddoclosed foldopen function global goto grep grepadd gui gvim hardcopy help helpfind helpgrep helptags highlight hide history insert iabbrev iabclear ijump ilist imap imapclear imenu inoremap inoreabbrev inoremenu intro isearch isplit iunmap iunabbrev iunmenu join jumps keepalt keepmarks keepjumps lNext lNfile list laddexpr laddbuffer laddfile last language later lbuffer lcd lchdir lclose lcscope left leftabove lexpr lfile lfirst lgetbuffer lgetexpr lgetfile lgrep lgrepadd lhelpgrep llast llist lmake lmap lmapclear lnext lnewer lnfile lnoremap loadkeymap loadview lockmarks lockvar lolder lopen lprevious lpfile lrewind ltag lunmap luado luafile lvimgrep lvimgrepadd lwindow move mark make mapclear match menu menutranslate messages mkexrc mksession mkspell mkvimrc mkview mode mzscheme mzfile nbclose nbkey nbsart next nmap nmapclear nmenu nnoremap nnoremenu noautocmd noremap nohlsearch noreabbrev noremenu normal number nunmap nunmenu oldfiles open omap omapclear omenu only onoremap onoremenu options ounmap ounmenu ownsyntax print profdel profile promptfind promptrepl pclose pedit perl perldo pop popup ppop preserve previous psearch ptag ptNext ptfirst ptjump ptlast ptnext ptprevious ptrewind ptselect put pwd py3do py3file python pydo pyfile quit quitall qall read recover redo redir redraw redrawstatus registers resize retab return rewind right rightbelow ruby rubydo rubyfile rundo runtime rviminfo substitute sNext sandbox sargument sall saveas sbuffer sbNext sball sbfirst sblast sbmodified sbnext sbprevious sbrewind scriptnames scriptencoding scscope set setfiletype setglobal setlocal sfind sfirst shell simalt sign silent sleep slast smagic smapclear smenu snext sniff snomagic snoremap snoremenu sort source spelldump spellgood spellinfo spellrepall spellundo spellwrong split sprevious srewind stop stag startgreplace startreplace startinsert stopinsert stjump stselect sunhide sunmap sunmenu suspend sview swapname syntax syntime syncbind tNext tabNext tabclose tabedit tabfind tabfirst tablast tabmove tabnext tabonly tabprevious tabrewind tag tcl tcldo tclfile tearoff tfirst throw tjump tlast tmenu tnext topleft tprevious trewind tselect tunmenu undo undojoin undolist unabbreviate unhide unlet unlockvar unmap unmenu unsilent update vglobal version verbose vertical vimgrep vimgrepadd visual viusage view vmap vmapclear vmenu vnew vnoremap vnoremenu vsplit vunmap vunmenu write wNext wall while winsize wincmd winpos wnext wprevious wqall wsverb wundo wviminfo xit xall xmapclear xmap xmenu xnoremap xnoremenu xunmap xunmenu yank",built_in:"synIDtrans atan2 range matcharg did_filetype asin feedkeys xor argv complete_check add getwinposx getqflist getwinposy screencol clearmatches empty extend getcmdpos mzeval garbagecollect setreg ceil sqrt diff_hlID inputsecret get getfperm getpid filewritable shiftwidth max sinh isdirectory synID system inputrestore winline atan visualmode inputlist tabpagewinnr round getregtype mapcheck hasmapto histdel argidx findfile sha256 exists toupper getcmdline taglist string getmatches bufnr strftime winwidth bufexists strtrans tabpagebuflist setcmdpos remote_read printf setloclist getpos getline bufwinnr float2nr len getcmdtype diff_filler luaeval resolve libcallnr foldclosedend reverse filter has_key bufname str2float strlen setline getcharmod setbufvar index searchpos shellescape undofile foldclosed setqflist buflisted strchars str2nr virtcol floor remove undotree remote_expr winheight gettabwinvar reltime cursor tabpagenr finddir localtime acos getloclist search tanh matchend rename gettabvar strdisplaywidth type abs py3eval setwinvar tolower wildmenumode log10 spellsuggest bufloaded synconcealed nextnonblank server2client complete settabwinvar executable input wincol setmatches getftype hlID inputsave searchpair or screenrow line settabvar histadd deepcopy strpart remote_peek and eval getftime submatch screenchar winsaveview matchadd mkdir screenattr getfontname libcall reltimestr getfsize winnr invert pow getbufline byte2line soundfold repeat fnameescape tagfiles sin strwidth spellbadword trunc maparg log lispindent hostname setpos globpath remote_foreground getchar synIDattr fnamemodify cscope_connection stridx winbufnr indent min complete_add nr2char searchpairpos inputdialog values matchlist items hlexists strridx browsedir expand fmod pathshorten line2byte argc count getwinvar glob foldtextresult getreg foreground cosh matchdelete has char2nr simplify histget searchdecl iconv winrestcmd pumvisible writefile foldlevel haslocaldir keys cos matchstr foldtext histnr tan tempname getcwd byteidx getbufvar islocked escape eventhandler remote_send serverlist winrestview synstack pyeval prevnonblank readfile cindent filereadable changenr exp"},illegal:/;/,contains:[e.NUMBER_MODE,{className:"string",begin:"'",end:"'",illegal:"\\n"},{className:"string",begin:/"(\\"|\n\\|[^"\n])*"/},e.COMMENT('"',"$"),{className:"variable",begin:/[bwtglsav]:[\w\d_]+/},{begin:[/\b(?:function|function!)/,/\s+/,e.IDENT_RE],className:{1:"keyword",3:"title"},end:"$",relevance:0,contains:[{className:"params",begin:"\\(",end:"\\)"}]},{className:"symbol",begin:/<[\w-]+>/}]}}),Rf)),zf.registerLanguage("wasm",(If||(If=1,Of=function(e){e.regex;const t=e.COMMENT(/\(;/,/;\)/);return t.contains.push("self"),{name:"WebAssembly",keywords:{$pattern:/[\w.]+/,keyword:["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"]},contains:[e.COMMENT(/;;/,/$/),t,{match:[/(?:offset|align)/,/\s*/,/=/],className:{1:"keyword",3:"operator"}},{className:"variable",begin:/\$[\w_]+/},{match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},{begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword",3:"title.function"}},e.QUOTE_STRING_MODE,{match:/(i32|i64|f32|f64)(?!\.)/,className:"type"},{className:"keyword",match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/},{className:"number",relevance:0,match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/}]}}),Of)),zf.registerLanguage("wren",(wf||(wf=1,xf=function(e){const t=e.regex,r=/[a-zA-Z]\w*/,n=["as","break","class","construct","continue","else","for","foreign","if","import","in","is","return","static","var","while"],a=["true","false","null"],i=["this","super"],o=["-","~",/\*/,"%",/\.\.\./,/\.\./,/\+/,"<<",">>",">=","<=","<",">",/\^/,/!=/,/!/,/\bis\b/,"==","&&","&",/\|\|/,/\|/,/\?:/,"="],s={relevance:0,match:t.concat(/\b(?!(if|while|for|else|super)\b)/,r,/(?=\s*[({])/),className:"title.function"},l={match:t.concat(t.either(t.concat(/\b(?!(if|while|for|else|super)\b)/,r),t.either(...o)),/(?=\s*\([^)]+\)\s*\{)/),className:"title.function",starts:{contains:[{begin:/\(/,end:/\)/,contains:[{relevance:0,scope:"params",match:r}]}]}},c={variants:[{match:[/class\s+/,r,/\s+is\s+/,r]},{match:[/class\s+/,r]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:n},d={relevance:0,match:t.either(...o),className:"operator"},u={className:"property",begin:t.concat(/\./,t.lookahead(r)),end:r,excludeBegin:!0,relevance:0},p={relevance:0,match:t.concat(/\b_/,r),scope:"variable"},_={relevance:0,match:/\b[A-Z]+[a-z]+([A-Z]+[a-z]+)*/,scope:"title.class",keywords:{_:["Bool","Class","Fiber","Fn","List","Map","Null","Num","Object","Range","Sequence","String","System"]}},m=e.C_NUMBER_MODE,g={match:[r,/\s*/,/=/,/\s*/,/\(/,r,/\)\s*\{/],scope:{1:"title.function",3:"operator",6:"params"}},h=e.COMMENT(/\/\*\*/,/\*\//,{contains:[{match:/@[a-z]+/,scope:"doctag"},"self"]}),f={scope:"subst",begin:/%\(/,end:/\)/,contains:[m,_,s,p,d]},E={scope:"string",begin:/"/,end:/"/,contains:[f,{scope:"char.escape",variants:[{match:/\\\\|\\["0%abefnrtv]/},{match:/\\x[0-9A-F]{2}/},{match:/\\u[0-9A-F]{4}/},{match:/\\U[0-9A-F]{8}/}]}]};f.contains.push(E);const b=[...n,...i,...a],S={relevance:0,match:t.concat("\\b(?!",b.join("|"),"\\b)",/[a-zA-Z_]\w*(?:[?!]|\b)/),className:"variable"};return{name:"Wren",keywords:{keyword:n,"variable.language":i,literal:a},contains:[{scope:"comment",variants:[{begin:[/#!?/,/[A-Za-z_]+(?=\()/],beginScope:{},keywords:{literal:a},contains:[],end:/\)/},{begin:[/#!?/,/[A-Za-z_]+/],beginScope:{},end:/$/}]},m,E,{className:"string",begin:/"""/,end:/"""/},h,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,_,c,g,l,s,d,p,u,S]}}),xf)),zf.registerLanguage("x86asm",(Mf||(Mf=1,Df=function(e){return{name:"Intel x86 Assembly",case_insensitive:!0,keywords:{$pattern:"[.%]?"+e.IDENT_RE,keyword:"lock rep repe repz repne repnz xaquire xrelease bnd nobnd aaa aad aam aas adc add and arpl bb0_reset bb1_reset bound bsf bsr bswap bt btc btr bts call cbw cdq cdqe clc cld cli clts cmc cmp cmpsb cmpsd cmpsq cmpsw cmpxchg cmpxchg486 cmpxchg8b cmpxchg16b cpuid cpu_read cpu_write cqo cwd cwde daa das dec div dmint emms enter equ f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcmovb fcmovbe fcmove fcmovnb fcmovnbe fcmovne fcmovnu fcmovu fcom fcomi fcomip fcomp fcompp fcos fdecstp fdisi fdiv fdivp fdivr fdivrp femms feni ffree ffreep fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisttp fisub fisubr fld fld1 fldcw fldenv fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnstcw fnstenv fnstsw fpatan fprem fprem1 fptan frndint frstor fsave fscale fsetpm fsin fsincos fsqrt fst fstcw fstenv fstp fstsw fsub fsubp fsubr fsubrp ftst fucom fucomi fucomip fucomp fucompp fxam fxch fxtract fyl2x fyl2xp1 hlt ibts icebp idiv imul in inc incbin insb insd insw int int01 int1 int03 int3 into invd invpcid invlpg invlpga iret iretd iretq iretw jcxz jecxz jrcxz jmp jmpe lahf lar lds lea leave les lfence lfs lgdt lgs lidt lldt lmsw loadall loadall286 lodsb lodsd lodsq lodsw loop loope loopne loopnz loopz lsl lss ltr mfence monitor mov movd movq movsb movsd movsq movsw movsx movsxd movzx mul mwait neg nop not or out outsb outsd outsw packssdw packsswb packuswb paddb paddd paddsb paddsiw paddsw paddusb paddusw paddw pand pandn pause paveb pavgusb pcmpeqb pcmpeqd pcmpeqw pcmpgtb pcmpgtd pcmpgtw pdistib pf2id pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin pfmul pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd pmachriw pmaddwd pmagw pmulhriw pmulhrwa pmulhrwc pmulhw pmullw pmvgezb pmvlzb pmvnzb pmvzb pop popa popad popaw popf popfd popfq popfw por prefetch prefetchw pslld psllq psllw psrad psraw psrld psrlq psrlw psubb psubd psubsb psubsiw psubsw psubusb psubusw psubw punpckhbw punpckhdq punpckhwd punpcklbw punpckldq punpcklwd push pusha pushad pushaw pushf pushfd pushfq pushfw pxor rcl rcr rdshr rdmsr rdpmc rdtsc rdtscp ret retf retn rol ror rdm rsdc rsldt rsm rsts sahf sal salc sar sbb scasb scasd scasq scasw sfence sgdt shl shld shr shrd sidt sldt skinit smi smint smintold smsw stc std sti stosb stosd stosq stosw str sub svdc svldt svts swapgs syscall sysenter sysexit sysret test ud0 ud1 ud2b ud2 ud2a umov verr verw fwait wbinvd wrshr wrmsr xadd xbts xchg xlatb xlat xor cmove cmovz cmovne cmovnz cmova cmovnbe cmovae cmovnb cmovb cmovnae cmovbe cmovna cmovg cmovnle cmovge cmovnl cmovl cmovnge cmovle cmovng cmovc cmovnc cmovo cmovno cmovs cmovns cmovp cmovpe cmovnp cmovpo je jz jne jnz ja jnbe jae jnb jb jnae jbe jna jg jnle jge jnl jl jnge jle jng jc jnc jo jno js jns jpo jnp jpe jp sete setz setne setnz seta setnbe setae setnb setnc setb setnae setcset setbe setna setg setnle setge setnl setl setnge setle setng sets setns seto setno setpe setp setpo setnp addps addss andnps andps cmpeqps cmpeqss cmpleps cmpless cmpltps cmpltss cmpneqps cmpneqss cmpnleps cmpnless cmpnltps cmpnltss cmpordps cmpordss cmpunordps cmpunordss cmpps cmpss comiss cvtpi2ps cvtps2pi cvtsi2ss cvtss2si cvttps2pi cvttss2si divps divss ldmxcsr maxps maxss minps minss movaps movhps movlhps movlps movhlps movmskps movntps movss movups mulps mulss orps rcpps rcpss rsqrtps rsqrtss shufps sqrtps sqrtss stmxcsr subps subss ucomiss unpckhps unpcklps xorps fxrstor fxrstor64 fxsave fxsave64 xgetbv xsetbv xsave xsave64 xsaveopt xsaveopt64 xrstor xrstor64 prefetchnta prefetcht0 prefetcht1 prefetcht2 maskmovq movntq pavgb pavgw pextrw pinsrw pmaxsw pmaxub pminsw pminub pmovmskb pmulhuw psadbw pshufw pf2iw pfnacc pfpnacc pi2fw pswapd maskmovdqu clflush movntdq movnti movntpd movdqa movdqu movdq2q movq2dq paddq pmuludq pshufd pshufhw pshuflw pslldq psrldq psubq punpckhqdq punpcklqdq addpd addsd andnpd andpd cmpeqpd cmpeqsd cmplepd cmplesd cmpltpd cmpltsd cmpneqpd cmpneqsd cmpnlepd cmpnlesd cmpnltpd cmpnltsd cmpordpd cmpordsd cmpunordpd cmpunordsd cmppd comisd cvtdq2pd cvtdq2ps cvtpd2dq cvtpd2pi cvtpd2ps cvtpi2pd cvtps2dq cvtps2pd cvtsd2si cvtsd2ss cvtsi2sd cvtss2sd cvttpd2pi cvttpd2dq cvttps2dq cvttsd2si divpd divsd maxpd maxsd minpd minsd movapd movhpd movlpd movmskpd movupd mulpd mulsd orpd shufpd sqrtpd sqrtsd subpd subsd ucomisd unpckhpd unpcklpd xorpd addsubpd addsubps haddpd haddps hsubpd hsubps lddqu movddup movshdup movsldup clgi stgi vmcall vmclear vmfunc vmlaunch vmload vmmcall vmptrld vmptrst vmread vmresume vmrun vmsave vmwrite vmxoff vmxon invept invvpid pabsb pabsw pabsd palignr phaddw phaddd phaddsw phsubw phsubd phsubsw pmaddubsw pmulhrsw pshufb psignb psignw psignd extrq insertq movntsd movntss lzcnt blendpd blendps blendvpd blendvps dppd dpps extractps insertps movntdqa mpsadbw packusdw pblendvb pblendw pcmpeqq pextrb pextrd pextrq phminposuw pinsrb pinsrd pinsrq pmaxsb pmaxsd pmaxud pmaxuw pminsb pminsd pminud pminuw pmovsxbw pmovsxbd pmovsxbq pmovsxwd pmovsxwq pmovsxdq pmovzxbw pmovzxbd pmovzxbq pmovzxwd pmovzxwq pmovzxdq pmuldq pmulld ptest roundpd roundps roundsd roundss crc32 pcmpestri pcmpestrm pcmpistri pcmpistrm pcmpgtq popcnt getsec pfrcpv pfrsqrtv movbe aesenc aesenclast aesdec aesdeclast aesimc aeskeygenassist vaesenc vaesenclast vaesdec vaesdeclast vaesimc vaeskeygenassist vaddpd vaddps vaddsd vaddss vaddsubpd vaddsubps vandpd vandps vandnpd vandnps vblendpd vblendps vblendvpd vblendvps vbroadcastss vbroadcastsd vbroadcastf128 vcmpeq_ospd vcmpeqpd vcmplt_ospd vcmpltpd vcmple_ospd vcmplepd vcmpunord_qpd vcmpunordpd vcmpneq_uqpd vcmpneqpd vcmpnlt_uspd vcmpnltpd vcmpnle_uspd vcmpnlepd vcmpord_qpd vcmpordpd vcmpeq_uqpd vcmpnge_uspd vcmpngepd vcmpngt_uspd vcmpngtpd vcmpfalse_oqpd vcmpfalsepd vcmpneq_oqpd vcmpge_ospd vcmpgepd vcmpgt_ospd vcmpgtpd vcmptrue_uqpd vcmptruepd vcmplt_oqpd vcmple_oqpd vcmpunord_spd vcmpneq_uspd vcmpnlt_uqpd vcmpnle_uqpd vcmpord_spd vcmpeq_uspd vcmpnge_uqpd vcmpngt_uqpd vcmpfalse_ospd vcmpneq_ospd vcmpge_oqpd vcmpgt_oqpd vcmptrue_uspd vcmppd vcmpeq_osps vcmpeqps vcmplt_osps vcmpltps vcmple_osps vcmpleps vcmpunord_qps vcmpunordps vcmpneq_uqps vcmpneqps vcmpnlt_usps vcmpnltps vcmpnle_usps vcmpnleps vcmpord_qps vcmpordps vcmpeq_uqps vcmpnge_usps vcmpngeps vcmpngt_usps vcmpngtps vcmpfalse_oqps vcmpfalseps vcmpneq_oqps vcmpge_osps vcmpgeps vcmpgt_osps vcmpgtps vcmptrue_uqps vcmptrueps vcmplt_oqps vcmple_oqps vcmpunord_sps vcmpneq_usps vcmpnlt_uqps vcmpnle_uqps vcmpord_sps vcmpeq_usps vcmpnge_uqps vcmpngt_uqps vcmpfalse_osps vcmpneq_osps vcmpge_oqps vcmpgt_oqps vcmptrue_usps vcmpps vcmpeq_ossd vcmpeqsd vcmplt_ossd vcmpltsd vcmple_ossd vcmplesd vcmpunord_qsd vcmpunordsd vcmpneq_uqsd vcmpneqsd vcmpnlt_ussd vcmpnltsd vcmpnle_ussd vcmpnlesd vcmpord_qsd vcmpordsd vcmpeq_uqsd vcmpnge_ussd vcmpngesd vcmpngt_ussd vcmpngtsd vcmpfalse_oqsd vcmpfalsesd vcmpneq_oqsd vcmpge_ossd vcmpgesd vcmpgt_ossd vcmpgtsd vcmptrue_uqsd vcmptruesd vcmplt_oqsd vcmple_oqsd vcmpunord_ssd vcmpneq_ussd vcmpnlt_uqsd vcmpnle_uqsd vcmpord_ssd vcmpeq_ussd vcmpnge_uqsd vcmpngt_uqsd vcmpfalse_ossd vcmpneq_ossd vcmpge_oqsd vcmpgt_oqsd vcmptrue_ussd vcmpsd vcmpeq_osss vcmpeqss vcmplt_osss vcmpltss vcmple_osss vcmpless vcmpunord_qss vcmpunordss vcmpneq_uqss vcmpneqss vcmpnlt_usss vcmpnltss vcmpnle_usss vcmpnless vcmpord_qss vcmpordss vcmpeq_uqss vcmpnge_usss vcmpngess vcmpngt_usss vcmpngtss vcmpfalse_oqss vcmpfalsess vcmpneq_oqss vcmpge_osss vcmpgess vcmpgt_osss vcmpgtss vcmptrue_uqss vcmptruess vcmplt_oqss vcmple_oqss vcmpunord_sss vcmpneq_usss vcmpnlt_uqss vcmpnle_uqss vcmpord_sss vcmpeq_usss vcmpnge_uqss vcmpngt_uqss vcmpfalse_osss vcmpneq_osss vcmpge_oqss vcmpgt_oqss vcmptrue_usss vcmpss vcomisd vcomiss vcvtdq2pd vcvtdq2ps vcvtpd2dq vcvtpd2ps vcvtps2dq vcvtps2pd vcvtsd2si vcvtsd2ss vcvtsi2sd vcvtsi2ss vcvtss2sd vcvtss2si vcvttpd2dq vcvttps2dq vcvttsd2si vcvttss2si vdivpd vdivps vdivsd vdivss vdppd vdpps vextractf128 vextractps vhaddpd vhaddps vhsubpd vhsubps vinsertf128 vinsertps vlddqu vldqqu vldmxcsr vmaskmovdqu vmaskmovps vmaskmovpd vmaxpd vmaxps vmaxsd vmaxss vminpd vminps vminsd vminss vmovapd vmovaps vmovd vmovq vmovddup vmovdqa vmovqqa vmovdqu vmovqqu vmovhlps vmovhpd vmovhps vmovlhps vmovlpd vmovlps vmovmskpd vmovmskps vmovntdq vmovntqq vmovntdqa vmovntpd vmovntps vmovsd vmovshdup vmovsldup vmovss vmovupd vmovups vmpsadbw vmulpd vmulps vmulsd vmulss vorpd vorps vpabsb vpabsw vpabsd vpacksswb vpackssdw vpackuswb vpackusdw vpaddb vpaddw vpaddd vpaddq vpaddsb vpaddsw vpaddusb vpaddusw vpalignr vpand vpandn vpavgb vpavgw vpblendvb vpblendw vpcmpestri vpcmpestrm vpcmpistri vpcmpistrm vpcmpeqb vpcmpeqw vpcmpeqd vpcmpeqq vpcmpgtb vpcmpgtw vpcmpgtd vpcmpgtq vpermilpd vpermilps vperm2f128 vpextrb vpextrw vpextrd vpextrq vphaddw vphaddd vphaddsw vphminposuw vphsubw vphsubd vphsubsw vpinsrb vpinsrw vpinsrd vpinsrq vpmaddwd vpmaddubsw vpmaxsb vpmaxsw vpmaxsd vpmaxub vpmaxuw vpmaxud vpminsb vpminsw vpminsd vpminub vpminuw vpminud vpmovmskb vpmovsxbw vpmovsxbd vpmovsxbq vpmovsxwd vpmovsxwq vpmovsxdq vpmovzxbw vpmovzxbd vpmovzxbq vpmovzxwd vpmovzxwq vpmovzxdq vpmulhuw vpmulhrsw vpmulhw vpmullw vpmulld vpmuludq vpmuldq vpor vpsadbw vpshufb vpshufd vpshufhw vpshuflw vpsignb vpsignw vpsignd vpslldq vpsrldq vpsllw vpslld vpsllq vpsraw vpsrad vpsrlw vpsrld vpsrlq vptest vpsubb vpsubw vpsubd vpsubq vpsubsb vpsubsw vpsubusb vpsubusw vpunpckhbw vpunpckhwd vpunpckhdq vpunpckhqdq vpunpcklbw vpunpcklwd vpunpckldq vpunpcklqdq vpxor vrcpps vrcpss vrsqrtps vrsqrtss vroundpd vroundps vroundsd vroundss vshufpd vshufps vsqrtpd vsqrtps vsqrtsd vsqrtss vstmxcsr vsubpd vsubps vsubsd vsubss vtestps vtestpd vucomisd vucomiss vunpckhpd vunpckhps vunpcklpd vunpcklps vxorpd vxorps vzeroall vzeroupper pclmullqlqdq pclmulhqlqdq pclmullqhqdq pclmulhqhqdq pclmulqdq vpclmullqlqdq vpclmulhqlqdq vpclmullqhqdq vpclmulhqhqdq vpclmulqdq vfmadd132ps vfmadd132pd vfmadd312ps vfmadd312pd vfmadd213ps vfmadd213pd vfmadd123ps vfmadd123pd vfmadd231ps vfmadd231pd vfmadd321ps vfmadd321pd vfmaddsub132ps vfmaddsub132pd vfmaddsub312ps vfmaddsub312pd vfmaddsub213ps vfmaddsub213pd vfmaddsub123ps vfmaddsub123pd vfmaddsub231ps vfmaddsub231pd vfmaddsub321ps vfmaddsub321pd vfmsub132ps vfmsub132pd vfmsub312ps vfmsub312pd vfmsub213ps vfmsub213pd vfmsub123ps vfmsub123pd vfmsub231ps vfmsub231pd vfmsub321ps vfmsub321pd vfmsubadd132ps vfmsubadd132pd vfmsubadd312ps vfmsubadd312pd vfmsubadd213ps vfmsubadd213pd vfmsubadd123ps vfmsubadd123pd vfmsubadd231ps vfmsubadd231pd vfmsubadd321ps vfmsubadd321pd vfnmadd132ps vfnmadd132pd vfnmadd312ps vfnmadd312pd vfnmadd213ps vfnmadd213pd vfnmadd123ps vfnmadd123pd vfnmadd231ps vfnmadd231pd vfnmadd321ps vfnmadd321pd vfnmsub132ps vfnmsub132pd vfnmsub312ps vfnmsub312pd vfnmsub213ps vfnmsub213pd vfnmsub123ps vfnmsub123pd vfnmsub231ps vfnmsub231pd vfnmsub321ps vfnmsub321pd vfmadd132ss vfmadd132sd vfmadd312ss vfmadd312sd vfmadd213ss vfmadd213sd vfmadd123ss vfmadd123sd vfmadd231ss vfmadd231sd vfmadd321ss vfmadd321sd vfmsub132ss vfmsub132sd vfmsub312ss vfmsub312sd vfmsub213ss vfmsub213sd vfmsub123ss vfmsub123sd vfmsub231ss vfmsub231sd vfmsub321ss vfmsub321sd vfnmadd132ss vfnmadd132sd vfnmadd312ss vfnmadd312sd vfnmadd213ss vfnmadd213sd vfnmadd123ss vfnmadd123sd vfnmadd231ss vfnmadd231sd vfnmadd321ss vfnmadd321sd vfnmsub132ss vfnmsub132sd vfnmsub312ss vfnmsub312sd vfnmsub213ss vfnmsub213sd vfnmsub123ss vfnmsub123sd vfnmsub231ss vfnmsub231sd vfnmsub321ss vfnmsub321sd rdfsbase rdgsbase rdrand wrfsbase wrgsbase vcvtph2ps vcvtps2ph adcx adox rdseed clac stac xstore xcryptecb xcryptcbc xcryptctr xcryptcfb xcryptofb montmul xsha1 xsha256 llwpcb slwpcb lwpval lwpins vfmaddpd vfmaddps vfmaddsd vfmaddss vfmaddsubpd vfmaddsubps vfmsubaddpd vfmsubaddps vfmsubpd vfmsubps vfmsubsd vfmsubss vfnmaddpd vfnmaddps vfnmaddsd vfnmaddss vfnmsubpd vfnmsubps vfnmsubsd vfnmsubss vfrczpd vfrczps vfrczsd vfrczss vpcmov vpcomb vpcomd vpcomq vpcomub vpcomud vpcomuq vpcomuw vpcomw vphaddbd vphaddbq vphaddbw vphadddq vphaddubd vphaddubq vphaddubw vphaddudq vphadduwd vphadduwq vphaddwd vphaddwq vphsubbw vphsubdq vphsubwd vpmacsdd vpmacsdqh vpmacsdql vpmacssdd vpmacssdqh vpmacssdql vpmacsswd vpmacssww vpmacswd vpmacsww vpmadcsswd vpmadcswd vpperm vprotb vprotd vprotq vprotw vpshab vpshad vpshaq vpshaw vpshlb vpshld vpshlq vpshlw vbroadcasti128 vpblendd vpbroadcastb vpbroadcastw vpbroadcastd vpbroadcastq vpermd vpermpd vpermps vpermq vperm2i128 vextracti128 vinserti128 vpmaskmovd vpmaskmovq vpsllvd vpsllvq vpsravd vpsrlvd vpsrlvq vgatherdpd vgatherqpd vgatherdps vgatherqps vpgatherdd vpgatherqd vpgatherdq vpgatherqq xabort xbegin xend xtest andn bextr blci blcic blsi blsic blcfill blsfill blcmsk blsmsk blsr blcs bzhi mulx pdep pext rorx sarx shlx shrx tzcnt tzmsk t1mskc valignd valignq vblendmpd vblendmps vbroadcastf32x4 vbroadcastf64x4 vbroadcasti32x4 vbroadcasti64x4 vcompresspd vcompressps vcvtpd2udq vcvtps2udq vcvtsd2usi vcvtss2usi vcvttpd2udq vcvttps2udq vcvttsd2usi vcvttss2usi vcvtudq2pd vcvtudq2ps vcvtusi2sd vcvtusi2ss vexpandpd vexpandps vextractf32x4 vextractf64x4 vextracti32x4 vextracti64x4 vfixupimmpd vfixupimmps vfixupimmsd vfixupimmss vgetexppd vgetexpps vgetexpsd vgetexpss vgetmantpd vgetmantps vgetmantsd vgetmantss vinsertf32x4 vinsertf64x4 vinserti32x4 vinserti64x4 vmovdqa32 vmovdqa64 vmovdqu32 vmovdqu64 vpabsq vpandd vpandnd vpandnq vpandq vpblendmd vpblendmq vpcmpltd vpcmpled vpcmpneqd vpcmpnltd vpcmpnled vpcmpd vpcmpltq vpcmpleq vpcmpneqq vpcmpnltq vpcmpnleq vpcmpq vpcmpequd vpcmpltud vpcmpleud vpcmpnequd vpcmpnltud vpcmpnleud vpcmpud vpcmpequq vpcmpltuq vpcmpleuq vpcmpnequq vpcmpnltuq vpcmpnleuq vpcmpuq vpcompressd vpcompressq vpermi2d vpermi2pd vpermi2ps vpermi2q vpermt2d vpermt2pd vpermt2ps vpermt2q vpexpandd vpexpandq vpmaxsq vpmaxuq vpminsq vpminuq vpmovdb vpmovdw vpmovqb vpmovqd vpmovqw vpmovsdb vpmovsdw vpmovsqb vpmovsqd vpmovsqw vpmovusdb vpmovusdw vpmovusqb vpmovusqd vpmovusqw vpord vporq vprold vprolq vprolvd vprolvq vprord vprorq vprorvd vprorvq vpscatterdd vpscatterdq vpscatterqd vpscatterqq vpsraq vpsravq vpternlogd vpternlogq vptestmd vptestmq vptestnmd vptestnmq vpxord vpxorq vrcp14pd vrcp14ps vrcp14sd vrcp14ss vrndscalepd vrndscaleps vrndscalesd vrndscaless vrsqrt14pd vrsqrt14ps vrsqrt14sd vrsqrt14ss vscalefpd vscalefps vscalefsd vscalefss vscatterdpd vscatterdps vscatterqpd vscatterqps vshuff32x4 vshuff64x2 vshufi32x4 vshufi64x2 kandnw kandw kmovw knotw kortestw korw kshiftlw kshiftrw kunpckbw kxnorw kxorw vpbroadcastmb2q vpbroadcastmw2d vpconflictd vpconflictq vplzcntd vplzcntq vexp2pd vexp2ps vrcp28pd vrcp28ps vrcp28sd vrcp28ss vrsqrt28pd vrsqrt28ps vrsqrt28sd vrsqrt28ss vgatherpf0dpd vgatherpf0dps vgatherpf0qpd vgatherpf0qps vgatherpf1dpd vgatherpf1dps vgatherpf1qpd vgatherpf1qps vscatterpf0dpd vscatterpf0dps vscatterpf0qpd vscatterpf0qps vscatterpf1dpd vscatterpf1dps vscatterpf1qpd vscatterpf1qps prefetchwt1 bndmk bndcl bndcu bndcn bndmov bndldx bndstx sha1rnds4 sha1nexte sha1msg1 sha1msg2 sha256rnds2 sha256msg1 sha256msg2 hint_nop0 hint_nop1 hint_nop2 hint_nop3 hint_nop4 hint_nop5 hint_nop6 hint_nop7 hint_nop8 hint_nop9 hint_nop10 hint_nop11 hint_nop12 hint_nop13 hint_nop14 hint_nop15 hint_nop16 hint_nop17 hint_nop18 hint_nop19 hint_nop20 hint_nop21 hint_nop22 hint_nop23 hint_nop24 hint_nop25 hint_nop26 hint_nop27 hint_nop28 hint_nop29 hint_nop30 hint_nop31 hint_nop32 hint_nop33 hint_nop34 hint_nop35 hint_nop36 hint_nop37 hint_nop38 hint_nop39 hint_nop40 hint_nop41 hint_nop42 hint_nop43 hint_nop44 hint_nop45 hint_nop46 hint_nop47 hint_nop48 hint_nop49 hint_nop50 hint_nop51 hint_nop52 hint_nop53 hint_nop54 hint_nop55 hint_nop56 hint_nop57 hint_nop58 hint_nop59 hint_nop60 hint_nop61 hint_nop62 hint_nop63",built_in:"ip eip rip al ah bl bh cl ch dl dh sil dil bpl spl r8b r9b r10b r11b r12b r13b r14b r15b ax bx cx dx si di bp sp r8w r9w r10w r11w r12w r13w r14w r15w eax ebx ecx edx esi edi ebp esp eip r8d r9d r10d r11d r12d r13d r14d r15d rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15 cs ds es fs gs ss st st0 st1 st2 st3 st4 st5 st6 st7 mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 xmm16 xmm17 xmm18 xmm19 xmm20 xmm21 xmm22 xmm23 xmm24 xmm25 xmm26 xmm27 xmm28 xmm29 xmm30 xmm31 ymm0 ymm1 ymm2 ymm3 ymm4 ymm5 ymm6 ymm7 ymm8 ymm9 ymm10 ymm11 ymm12 ymm13 ymm14 ymm15 ymm16 ymm17 ymm18 ymm19 ymm20 ymm21 ymm22 ymm23 ymm24 ymm25 ymm26 ymm27 ymm28 ymm29 ymm30 ymm31 zmm0 zmm1 zmm2 zmm3 zmm4 zmm5 zmm6 zmm7 zmm8 zmm9 zmm10 zmm11 zmm12 zmm13 zmm14 zmm15 zmm16 zmm17 zmm18 zmm19 zmm20 zmm21 zmm22 zmm23 zmm24 zmm25 zmm26 zmm27 zmm28 zmm29 zmm30 zmm31 k0 k1 k2 k3 k4 k5 k6 k7 bnd0 bnd1 bnd2 bnd3 cr0 cr1 cr2 cr3 cr4 cr8 dr0 dr1 dr2 dr3 dr8 tr3 tr4 tr5 tr6 tr7 r0 r1 r2 r3 r4 r5 r6 r7 r0b r1b r2b r3b r4b r5b r6b r7b r0w r1w r2w r3w r4w r5w r6w r7w r0d r1d r2d r3d r4d r5d r6d r7d r0h r1h r2h r3h r0l r1l r2l r3l r4l r5l r6l r7l r8l r9l r10l r11l r12l r13l r14l r15l db dw dd dq dt ddq do dy dz resb resw resd resq rest resdq reso resy resz incbin equ times byte word dword qword nosplit rel abs seg wrt strict near far a32 ptr",meta:"%define %xdefine %+ %undef %defstr %deftok %assign %strcat %strlen %substr %rotate %elif %else %endif %if %ifmacro %ifctx %ifidn %ifidni %ifid %ifnum %ifstr %iftoken %ifempty %ifenv %error %warning %fatal %rep %endrep %include %push %pop %repl %pathsearch %depend %use %arg %stacksize %local %line %comment %endcomment .nolist __FILE__ __LINE__ __SECT__ __BITS__ __OUTPUT_FORMAT__ __DATE__ __TIME__ __DATE_NUM__ __TIME_NUM__ __UTC_DATE__ __UTC_TIME__ __UTC_DATE_NUM__ __UTC_TIME_NUM__ __PASS__ struc endstruc istruc at iend align alignb sectalign daz nodaz up down zero default option assume public bits use16 use32 use64 default section segment absolute extern global common cpu float __utf16__ __utf16le__ __utf16be__ __utf32__ __utf32le__ __utf32be__ __float8__ __float16__ __float32__ __float64__ __float80m__ __float80e__ __float128l__ __float128h__ __Infinity__ __QNaN__ __SNaN__ Inf NaN QNaN SNaN float8 float16 float32 float64 float80m float80e float128l float128h __FLOAT_DAZ__ __FLOAT_ROUND__ __FLOAT__"},contains:[e.COMMENT(";","$",{relevance:0}),{className:"number",variants:[{begin:"\\b(?:([0-9][0-9_]*)?\\.[0-9_]*(?:[eE][+-]?[0-9_]+)?|(0[Xx])?[0-9][0-9_]*(\\.[0-9_]*)?(?:[pP](?:[+-]?[0-9_]+)?)?)\\b",relevance:0},{begin:"\\$[0-9][0-9A-Fa-f]*",relevance:0},{begin:"\\b(?:[0-9A-Fa-f][0-9A-Fa-f_]*[Hh]|[0-9][0-9_]*[DdTt]?|[0-7][0-7_]*[QqOo]|[0-1][0-1_]*[BbYy])\\b"},{begin:"\\b(?:0[Xx][0-9A-Fa-f_]+|0[DdTt][0-9_]+|0[QqOo][0-7_]+|0[BbYy][0-1_]+)\\b"}]},e.QUOTE_STRING_MODE,{className:"string",variants:[{begin:"'",end:"[^\\\\]'"},{begin:"`",end:"[^\\\\]`"}],relevance:0},{className:"symbol",variants:[{begin:"^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)"},{begin:"^\\s*%%[A-Za-z0-9_$#@~.?]*:"}],relevance:0},{className:"subst",begin:"%[0-9]+",relevance:0},{className:"subst",begin:"%!S+",relevance:0},{className:"meta",begin:/^\s*\.[\w_-]+/}]}}),Df)),zf.registerLanguage("xl",(Lf||(Lf=1,kf=function(e){const t={$pattern:/[a-zA-Z][a-zA-Z0-9_?]*/,keyword:["if","then","else","do","while","until","for","loop","import","with","is","as","where","when","by","data","constant","integer","real","text","name","boolean","symbol","infix","prefix","postfix","block","tree"],literal:["true","false","nil"],built_in:["in","mod","rem","and","or","xor","not","abs","sign","floor","ceil","sqrt","sin","cos","tan","asin","acos","atan","exp","expm1","log","log2","log10","log1p","pi","at","text_length","text_range","text_find","text_replace","contains","page","slide","basic_slide","title_slide","title","subtitle","fade_in","fade_out","fade_at","clear_color","color","line_color","line_width","texture_wrap","texture_transform","texture","scale_?x","scale_?y","scale_?z?","translate_?x","translate_?y","translate_?z?","rotate_?x","rotate_?y","rotate_?z?","rectangle","circle","ellipse","sphere","path","line_to","move_to","quad_to","curve_to","theme","background","contents","locally","time","mouse_?x","mouse_?y","mouse_buttons"].concat(["ObjectLoader","Animate","MovieCredits","Slides","Filters","Shading","Materials","LensFlare","Mapping","VLCAudioVideo","StereoDecoder","PointCloud","NetworkAccess","RemoteControl","RegExp","ChromaKey","Snowfall","NodeJS","Speech","Charts"])},r={className:"string",begin:'"',end:'"',illegal:"\\n"},n={beginKeywords:"import",end:"$",keywords:t,contains:[r]},a={className:"function",begin:/[a-z][^\n]*->/,returnBegin:!0,end:/->/,contains:[e.inherit(e.TITLE_MODE,{starts:{endsWithParent:!0,keywords:t}})]};return{name:"XL",aliases:["tao"],keywords:t,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,r,{className:"string",begin:"'",end:"'",illegal:"\\n"},{className:"string",begin:"<<",end:">>"},a,n,{className:"number",begin:"[0-9]+#[0-9A-Z_]+(\\.[0-9-A-Z_]+)?#?([Ee][+-]?[0-9]+)?"},e.NUMBER_MODE]}}),kf)),zf.registerLanguage("xquery",Ff?Pf:(Ff=1,Pf=function(e){return{name:"XQuery",aliases:["xpath","xq","xqm"],case_insensitive:!1,illegal:/(proc)|(abstract)|(extends)|(until)|(#)/,keywords:{$pattern:/[a-zA-Z$][a-zA-Z0-9_:-]*/,keyword:["module","schema","namespace","boundary-space","preserve","no-preserve","strip","default","collation","base-uri","ordering","context","decimal-format","decimal-separator","copy-namespaces","empty-sequence","except","exponent-separator","external","grouping-separator","inherit","no-inherit","lax","minus-sign","per-mille","percent","schema-attribute","schema-element","strict","unordered","zero-digit","declare","import","option","function","validate","variable","for","at","in","let","where","order","group","by","return","if","then","else","tumbling","sliding","window","start","when","only","end","previous","next","stable","ascending","descending","allowing","empty","greatest","least","some","every","satisfies","switch","case","typeswitch","try","catch","and","or","to","union","intersect","instance","of","treat","as","castable","cast","map","array","delete","insert","into","replace","value","rename","copy","modify","update"],type:["item","document-node","node","attribute","document","element","comment","namespace","namespace-node","processing-instruction","text","construction","xs:anyAtomicType","xs:untypedAtomic","xs:duration","xs:time","xs:decimal","xs:float","xs:double","xs:gYearMonth","xs:gYear","xs:gMonthDay","xs:gMonth","xs:gDay","xs:boolean","xs:base64Binary","xs:hexBinary","xs:anyURI","xs:QName","xs:NOTATION","xs:dateTime","xs:dateTimeStamp","xs:date","xs:string","xs:normalizedString","xs:token","xs:language","xs:NMTOKEN","xs:Name","xs:NCName","xs:ID","xs:IDREF","xs:ENTITY","xs:integer","xs:nonPositiveInteger","xs:negativeInteger","xs:long","xs:int","xs:short","xs:byte","xs:nonNegativeInteger","xs:unisignedLong","xs:unsignedInt","xs:unsignedShort","xs:unsignedByte","xs:positiveInteger","xs:yearMonthDuration","xs:dayTimeDuration"],literal:["eq","ne","lt","le","gt","ge","is","self::","child::","descendant::","descendant-or-self::","attribute::","following::","following-sibling::","parent::","ancestor::","ancestor-or-self::","preceding::","preceding-sibling::","NaN"]},contains:[{className:"variable",begin:/[$][\w\-:]+/},{className:"built_in",variants:[{begin:/\barray:/,end:/(?:append|filter|flatten|fold-(?:left|right)|for-each(?:-pair)?|get|head|insert-before|join|put|remove|reverse|size|sort|subarray|tail)\b/},{begin:/\bmap:/,end:/(?:contains|entry|find|for-each|get|keys|merge|put|remove|size)\b/},{begin:/\bmath:/,end:/(?:a(?:cos|sin|tan[2]?)|cos|exp(?:10)?|log(?:10)?|pi|pow|sin|sqrt|tan)\b/},{begin:/\bop:/,end:/\(/,excludeEnd:!0},{begin:/\bfn:/,end:/\(/,excludeEnd:!0},{begin:/[^</$:'"-]\b(?:abs|accumulator-(?:after|before)|adjust-(?:date(?:Time)?|time)-to-timezone|analyze-string|apply|available-(?:environment-variables|system-properties)|avg|base-uri|boolean|ceiling|codepoints?-(?:equal|to-string)|collation-key|collection|compare|concat|contains(?:-token)?|copy-of|count|current(?:-)?(?:date(?:Time)?|time|group(?:ing-key)?|output-uri|merge-(?:group|key))?data|dateTime|days?-from-(?:date(?:Time)?|duration)|deep-equal|default-(?:collation|language)|distinct-values|document(?:-uri)?|doc(?:-available)?|element-(?:available|with-id)|empty|encode-for-uri|ends-with|environment-variable|error|escape-html-uri|exactly-one|exists|false|filter|floor|fold-(?:left|right)|for-each(?:-pair)?|format-(?:date(?:Time)?|time|integer|number)|function-(?:arity|available|lookup|name)|generate-id|has-children|head|hours-from-(?:dateTime|duration|time)|id(?:ref)?|implicit-timezone|in-scope-prefixes|index-of|innermost|insert-before|iri-to-uri|json-(?:doc|to-xml)|key|lang|last|load-xquery-module|local-name(?:-from-QName)?|(?:lower|upper)-case|matches|max|minutes-from-(?:dateTime|duration|time)|min|months?-from-(?:date(?:Time)?|duration)|name(?:space-uri-?(?:for-prefix|from-QName)?)?|nilled|node-name|normalize-(?:space|unicode)|not|number|one-or-more|outermost|parse-(?:ietf-date|json)|path|position|(?:prefix-from-)?QName|random-number-generator|regex-group|remove|replace|resolve-(?:QName|uri)|reverse|root|round(?:-half-to-even)?|seconds-from-(?:dateTime|duration|time)|snapshot|sort|starts-with|static-base-uri|stream-available|string-?(?:join|length|to-codepoints)?|subsequence|substring-?(?:after|before)?|sum|system-property|tail|timezone-from-(?:date(?:Time)?|time)|tokenize|trace|trans(?:form|late)|true|type-available|unordered|unparsed-(?:entity|text)?-?(?:public-id|uri|available|lines)?|uri-collection|xml-to-json|years?-from-(?:date(?:Time)?|duration)|zero-or-one)\b/},{begin:/\blocal:/,end:/\(/,excludeEnd:!0},{begin:/\bzip:/,end:/(?:zip-file|(?:xml|html|text|binary)-entry| (?:update-)?entries)\b/},{begin:/\b(?:util|db|functx|app|xdmp|xmldb):/,end:/\(/,excludeEnd:!0}]},{className:"string",variants:[{begin:/"/,end:/"/,contains:[{begin:/""/,relevance:0}]},{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]}]},{className:"number",begin:/(\b0[0-7_]+)|(\b0x[0-9a-fA-F_]+)|(\b[1-9][0-9_]*(\.[0-9_]+)?)|[0_]\b/,relevance:0},{className:"comment",begin:/\(:/,end:/:\)/,relevance:10,contains:[{className:"doctag",begin:/@\w+/}]},{className:"meta",begin:/%[\w\-:]+/},{className:"title",begin:/\bxquery version "[13]\.[01]"\s?(?:encoding ".+")?/,end:/;/},{beginKeywords:"element attribute comment document processing-instruction",end:/\{/,excludeEnd:!0},{begin:/<([\w._:-]+)(\s+\S*=('|").*('|"))?>/,end:/(\/[\w._:-]+>)/,subLanguage:"xml",contains:[{begin:/\{/,end:/\}/,subLanguage:"xquery"},"self"]}]}})),zf.registerLanguage("zephir",(Uf||(Uf=1,Bf=function(e){const t={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.inherit(e.APOS_STRING_MODE,{illegal:null}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null})]},r=e.UNDERSCORE_TITLE_MODE,n={variants:[e.BINARY_NUMBER_MODE,e.C_NUMBER_MODE]},a="namespace class interface use extends function return abstract final public protected private static deprecated throw try catch Exception echo empty isset instanceof unset let var new const self require if else elseif switch case default do while loop for continue break likely unlikely __LINE__ __FILE__ __DIR__ __FUNCTION__ __CLASS__ __TRAIT__ __METHOD__ __NAMESPACE__ array boolean float double integer object resource string char long unsigned bool int uint ulong uchar true false null undefined";return{name:"Zephir",aliases:["zep"],keywords:a,contains:[e.C_LINE_COMMENT_MODE,e.COMMENT(/\/\*/,/\*\//,{contains:[{className:"doctag",begin:/@[A-Za-z]+/}]}),{className:"string",begin:/<<<['"]?\w+['"]?$/,end:/^\w+;/,contains:[e.BACKSLASH_ESCAPE]},{begin:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{className:"function",beginKeywords:"function fn",end:/[;{]/,excludeEnd:!0,illegal:/\$|\[|%/,contains:[r,{className:"params",begin:/\(/,end:/\)/,keywords:a,contains:["self",e.C_BLOCK_COMMENT_MODE,t,n]}]},{className:"class",beginKeywords:"class interface",end:/\{/,excludeEnd:!0,illegal:/[:($"]/,contains:[{beginKeywords:"extends implements"},r]},{beginKeywords:"namespace",end:/;/,illegal:/[.']/,contains:[r]},{beginKeywords:"use",end:/;/,contains:[r]},{begin:/=>/},t,n]}}),Bf)),zf.HighlightJS=zf,zf.default=zf;var Yf=pr(zf);function qf(e){e.options.highlight=function(e,t){if(t&&Yf.getLanguage(t))try{return Yf.highlight(e,{language:t}).value}catch(e){return""}return""}}var Hf=function(e){e.core.ruler.push("caption_plugin",function(t){for(var r=t.tokens,n=new Set,a=new Map,i=function(e){return!(e<0||e+2>=r.length)&&("paragraph_open"===r[e].type&&"inline"===r[e+1].type&&"paragraph_close"===r[e+2].type&&r[e+1].content.startsWith(": "))},o=function(e){if(e<0||e+2>=r.length)return!1;if("paragraph_open"===r[e].type&&"inline"===r[e+1].type&&"paragraph_close"===r[e+2].type){var t=r[e+1];if(t.children&&1===t.children.length&&"image"===t.children[0].type)return!0}return!1},s=function(e){if(e<0||e>=r.length)return!1;var t=r[e];return"html_block"===t.type&&/^\s*<table\b/i.test(t.content||"")},l=function(e){if(e<0||e>=r.length)return!1;var t=r[e];return"html_block"===t.type&&/^\s*<img\b/i.test(t.content||"")},d=function(e){if(e<0||e+2>=r.length)return!1;if("paragraph_open"===r[e].type&&"inline"===r[e+1].type&&"paragraph_close"===r[e+2].type){var t=r[e+1];if(!t.children||1!==t.children.length)return!1;var n=t.children[0];return"html_inline"===n.type&&/^\s*<img\b/i.test(n.content||"")}return!1},u=0;u<r.length;u++){var p=null,_=-1;if("table_open"===r[u].type){p="table";for(var m=1,g=u+1;g<r.length;g++)if("table_open"===r[g].type?m++:"table_close"===r[g].type&&m--,0===m){_=g;break}}else o(u)?(p="figure",_=u+2):s(u)?(p="html_table",_=u):l(u)?(p="html_img_block",_=u):d(u)&&(p="html_figure",_=u+2);if(p&&-1!==_){var h=-1,f=null;if(u>=3&&"paragraph_close"===r[u-1].type){var E=u-3;i(E)&&!n.has(E)&&(h=E,f="top")}if(-1===h){var b=_+1;b<r.length&&i(b)&&!n.has(b)&&(h=b,f="bottom")}if(-1!==h){if("html_table"===p){var S=r[u].content||"";if(/<caption\b/i.test(S))continue}n.add(h),a.set(u,{idx:h,pos:f,targetType:p})}}}for(var v=[],T=function(i){if(n.has(i))return y=i+=2,1;if(a.has(i)){var o=a.get(i),s=r[o.idx+1],l=s.content.slice(2),d=e.renderInline(l),u=[];s.children&&(u=s.children.map(function(e){return Object.assign(new t.Token(e.type,e.tag,e.nesting),e)})).length>0&&"text"===u[0].type&&u[0].content.startsWith(": ")&&(u[0].content=u[0].content.slice(2));var p=function(e){var r=new t.Token("".concat(e,"_open"),e,1),n=new t.Token("".concat(e,"_close"),e,-1),a=new t.Token("inline","",0);return a.content=l,a.children=u,[r,a,n]};if("html_table"===o.targetType){var _=r[i],m=Object.assign(new t.Token(_.type,_.tag,_.nesting),_),g=m.content||"",h=g.match(/<table\b[^>]*>/i);h&&(m.content=g.replace(h[0],"".concat(h[0],"\n<caption>").concat(d,"</caption>"))),v.push(m)}else if("table_open"===r[i].type)v.push(r[i]),v.push.apply(v,c(p("caption")));else{var f=new t.Token("figure_open","figure",1);f.map=r[i].map,v.push(f),"html_img_block"===o.targetType?v.push(r[i]):v.push(r[i+1]),v.push.apply(v,c(p("figcaption")));var E=new t.Token("figure_close","figure",-1);v.push(E),"figure"!==o.targetType&&"html_figure"!==o.targetType||(i+=2)}}else v.push(r[i]);y=i},y=0;y<r.length;y++)T(y);t.tokens=v})},Vf=function(e){!1!==(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).enable&&e.core.ruler.push("img_frame",function(e){for(var t=e.tokens,r=0;r<t.length;r++){var n=t[r];if("paragraph_open"===n.type){if(r+2<t.length){var a=t[r+1],i=t[r+2];if("inline"===a.type&&"paragraph_close"===i.type){var o=a.children||[],s=o.filter(function(e){return"image"===e.type});if(1===s.length&&1===o.length){var l=s[0].content||"";n.attrJoin("class","img-frame"),n.attrSet("data-alt",l)}}}}else if("figure_open"===n.type&&r+1<t.length){var c=t[r+1];if("inline"===c.type){var d=(c.children||[]).filter(function(e){return"image"===e.type});if(1===d.length){var u=d[0].content||"";n.attrJoin("class","img-frame"),n.attrSet("data-alt",u)}}}}})},$f=function(e){var t=e.renderer.rules.html_block||function(e,t){return e[t].content};e.renderer.rules.html_block=function(e,r,n,a,i){var o=e[r],s=t(e,r,n,a,i);if(!a||!a.lineNumbers||!o.attrs)return s;var l=o.attrGet("data-line");if(!l)return s;var c=s.match(/<([a-zA-Z0-9-]+)([^>]*)>/);if(c){var d=c[1],u=c[2],p=' data-line="'.concat(l,'"');return u=u.includes('class="')?u.replace('class="','class="line '):u.includes("class='")?u.replace("class='","class='line "):' class="line"'.concat(u),s.replace(/<([a-zA-Z0-9-]+)([^>]*)>/,"<".concat(d).concat(p).concat(u,">"))}return s};var r=e.renderer.rules.fence||function(t,r,n,a,i){var o=t[r],s=o.info?e.utils.unescapeAll(o.info).trim():"",l=s?s.split(/\s+/g)[0]:"",c=n.highlight&&n.highlight(o.content,l,"")||e.utils.escapeHtml(o.content);return 0===c.indexOf("<pre")?c+"\n":(s&&o.attrJoin("class",n.langPrefix+l),"<pre><code"+i.renderAttrs(o)+">"+c+"</code></pre>\n")};e.renderer.rules.fence=function(t,n,a,i,o){if(!i||!i.lineNumbers)return r(t,n,a,i,o);var s,l=t[n],c=l.info?e.utils.unescapeAll(l.info).trim():"",d="";if(c&&(d=c.split(/\s+/g)[0]),0===(s=a.highlight&&a.highlight(l.content,d,"")||e.utils.escapeHtml(l.content)).indexOf("<pre"))return s+"\n";var u=d?"".concat(a.langPrefix).concat(d):"";return"<pre"+o.renderAttrs(l)+"><code"+(u?' class="'.concat(u,'"'):"")+">"+s+"</code></pre>\n"},e.core.ruler.push("line_numbers",function(e){if(e.env&&e.env.lineNumbers){var t=!1!==(e.env.lineNumbersOptions||{}).nested;e.tokens.forEach(function(e){(t||0===e.level)&&e.map&&(e.type.endsWith("_open")||"fence"===e.type||"html_block"===e.type||"code_block"===e.type||"hr"===e.type||"math_block"===e.type||"toc_open"===e.type)&&(e.attrSet("data-line",String(e.map[0])),"html_block"!==e.type&&e.attrJoin("class","line"))})}})},Wf=/^(?:<!--[\s\S]*?-->|<\/?[a-z][a-z0-9:-]*(?=[\s/>])(?:[^<>"']|"[^"]*"|'[^']*')*>)/i,jf=/^<\/?(?:table|thead|tbody|tfoot|tr|td|th)(?=[\s/>])/i,Qf=/^<(code|pre|kbd|samp|script|style|textarea)(?=[\s/>])/i;function Kf(e,t){var r;return"<"===e[t]?null===(r=e.slice(t).match(Wf))||void 0===r?void 0:r[0]:void 0}function Xf(e,t){for(var r=0;"\\"===e[--t];)r++;return r%2==1}function Zf(e,t,r){var n,a=null===(n=e.slice(t).match(/^(`+|~{3,})/))||void 0===n?void 0:n[0];if(!a)return t;var i=a.length>=3&&/^[ \t]*$/.test(e.slice(r,t));if("~"===a[0]&&!i)return t;for(var o=t+a.length;o<e.length;){var s=Kf(e,o);if(s&&jf.test(s))return i?o:t+a.length;if(s)o+=s.length;else if(e[o]===a[0]){for(var l=o+1;e[l]===a[0];)l++;if(!i&&l-o===a.length)return l;if(i&&l-o>=a.length){var c=e.slice(e.lastIndexOf("\n",o-1)+1,o),d=e.indexOf("\n",l),u=e.slice(l,d<0?e.length:d);if(/^[ \t]*$/.test(c)&&/^[ \t]*$/.test(u))return l}o=l}else o++}return i?e.length:t+a.length}function Jf(e,t,r){for(var n=t+r.length;n<e.length;){var a=Kf(e,n);if(a){if(jf.test(a))return-1;n+=a.length}else{if(e.startsWith(r,n)&&!Xf(e,n))return n===t+r.length||"$"===e[n+r.length]?-1:n+r.length;n++}}return-1}var eE,tE=(eE=function(e){return"undefined"==typeof DOMParser?null:(new DOMParser).parseFromString(e,"text/html").querySelector("table")},function(e){e.block.ruler.before("html_block","html_table",function(e,t,r,n){var a=e.bMarks[t]+e.tShift[t],i=e.eMarks[t],o=e.src.slice(a,i);if(!/^<table/i.test(o))return!1;for(var s=t,l=!1,c="";s<r;s++){var d=e.bMarks[s]+e.tShift[s],u=e.eMarks[s],p=e.src.slice(d,u);if(c+=p+"\n",/<\/table>/i.test(p)){l=!0,s++;break}}if(!l)return!1;if(n)return!0;var _=function(e,t){for(var r=t(e.replace(/&#(?:x[0-9a-f]+|[0-9]+);?/gi,function(e){return e.endsWith(";")?e:"".concat(e,";")})),n="SOMARKDOWNMATH";e.includes(n)||r.includes(n);)n+="X";for(var a=[],i=[],o=0,s=0,l=0,c=0;c<e.length;){var d=Kf(e,c);if(d){/^<(?:td|th)(?=[\s/>])/i.test(d)&&o++,/^<\/(?:td|th)(?=[\s/>])/i.test(d)&&(o=Math.max(0,o-1)),c+=d.length,/^<(?:td|th)(?=[\s/>])/i.test(d)&&(s=c);var u=d.match(Qf);if(u&&!/\/>$/.test(d)){var p=new RegExp("</".concat(u[1],"\\s*>"),"ig");p.lastIndex=c,c=p.exec(e)?p.lastIndex:e.length}}else{if("\n"===e[c]&&(s=c+1),o&&("`"===e[c]||"~"===e[c])&&!Xf(e,c)){var _=Zf(e,c,s);if(_>c){c=_,s=Math.max(s,e.lastIndexOf("\n",c-1)+1);continue}}if(o&&"$"===e[c]&&"$"!==e[c-1]&&"\\"!==e[c-1]){var m=Jf(e,c,"$"===e[c+1]?"$$":"$");if(-1!==m){i.push(e.slice(l,c),"".concat(n).concat(a.length,"END")),a.push(e.slice(c,m)),c=m,l=m,s=Math.max(s,e.lastIndexOf("\n",c-1)+1);continue}}c++}}return i.push(e.slice(l)),{html:i.join(""),restore:function(e){return e.replace(new RegExp("".concat(n,"(\\d+)END"),"g"),function(e,t){var r;return null!==(r=a[Number(t)])&&void 0!==r?r:e})}}}(c,e.md.utils.unescapeAll),m=eE(_.html);if(!m)return!1;var g=e.push("table_open","table",1);g.map=[t,s],Array.from(m.attributes).forEach(function(e){g.attrs=g.attrs||[],g.attrs.push([e.name,e.value])});var h=function(t){var r=e.push("tr_open","tr",1);Array.from(t.attributes).forEach(function(e){r.attrs=r.attrs||[],r.attrs.push([e.name,e.value])}),Array.from(t.children).forEach(function(t){var r=t.tagName.toLowerCase();if("td"===r||"th"===r){var n=e.push(r+"_open",r,1);Array.from(t.attributes).forEach(function(e){n.attrs=n.attrs||[],n.attrs.push([e.name,e.value])});var a=_.restore(t.innerHTML);e.md.parse(a,e.env).forEach(function(t){"inline"===t.type&&(t.content=""),e.tokens.push(t)}),e.push(r+"_close",r,-1)}}),e.push("tr_close","tr",-1)};return Array.from(m.children).forEach(function(t){var r=t.tagName.toLowerCase();if("thead"===r||"tbody"===r||"tfoot"===r){var n=e.push(r+"_open",r,1);Array.from(t.attributes).forEach(function(e){n.attrs=n.attrs||[],n.attrs.push([e.name,e.value])}),Array.from(t.children).forEach(function(e){"TR"===e.tagName&&h(e)}),e.push(r+"_close",r,-1)}else"tr"===r&&h(t)}),e.push("table_close","table",-1),e.line=s,!0})}),rE=function(){return r(function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t(this,e),this.config=o(o(o({},ur),r),{},{lineNumbers:o(o({},ur.lineNumbers),r.lineNumbers||{})}),this.md=new nr(this.config),this.md.use(qf),this.md.use(fc,o(o({},this.config.katex),{},{smiles:this.config.smiles})),this.md.use(yc,this.config.toc),this.md.use(Hf),this.md.use(Vf,{enable:this.config.imgDescEnabled}),this.md.use(or),this.md.use(cr),this.md.use(dr),this.md.use($f),this.md.use(tE)},[{key:"render",value:function(e){var t={lineNumbers:this.config.lineNumbers.enable,lineNumbersOptions:{nested:this.config.lineNumbers.nested}};return this.md.render(e,t)}}])}();return rE});
+//# sourceMappingURL=somarkdown.umd.min.js.map
diff --git a/oxr/server/demo_api.py b/oxr/server/demo_api.py
new file mode 100644
index 0000000..ed24f77
--- /dev/null
+++ b/oxr/server/demo_api.py
@@ -0,0 +1,210 @@
+"""The OXR Online Demo's upload, preview, and result endpoints."""
+
+import asyncio
+from contextlib import suppress
+import logging
+import math
+from pathlib import Path
+import time
+
+import cv2
+from fastapi import APIRouter, File, Form, Request, UploadFile
+from fastapi.responses import FileResponse, JSONResponse
+
+from oxr.pipeline import orchestrator
+from oxr.pipeline.errors import get_public_error_message
+from oxr.server.demo_store import DemoStore
+
+
+router = APIRouter(tags=["OXR Online Demo"])
+LOGGER = logging.getLogger(__name__)
+MAX_UPLOAD_BYTES = 100 * 1024 * 1024
+SUPPORTED_EXTENSIONS = {".pdf", ".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"}
+
+
+def _error(message: str, status: int) -> JSONResponse:
+ return JSONResponse({"code": status, "message": message, "data": None}, status_code=status)
+
+
+def _response(data: dict) -> dict:
+ return {"code": 0, "message": "success", "data": data}
+
+
+def _decode_and_publish(store: DemoStore, job_id: str, data: bytes, file_name: str):
+ images = orchestrator._decode_document_images(data, file_name)
+ directory = store.job_dir(job_id) / "images"
+ pages = []
+ assets = []
+ for page_num, image in enumerate(images):
+ asset_id = f"page-{page_num:04d}.png"
+ if not cv2.imwrite(str(directory / asset_id), image):
+ raise OSError("Unable to create the page preview. Temporary storage may be full.")
+ store.ensure_capacity()
+ height, width = image.shape[:2]
+ pages.append({
+ "page_num": page_num,
+ "page_size": {"w": width, "h": height},
+ "image_url": f"/v1/demo/jobs/{job_id}/assets/{asset_id}",
+ })
+ assets.append(asset_id)
+ store.update(job_id, status="processing", pages=pages, assets=assets)
+ return images
+
+
+async def _process_job(
+ store: DemoStore, job_id: str, data: bytes, file_name: str,
+ model_options: dict[str, float] | None = None,
+) -> None:
+ decode_task = None
+ publish_task = None
+ try:
+ started_at = time.perf_counter()
+ store.update(job_id, status="rendering")
+ decode_task = asyncio.create_task(asyncio.to_thread(_decode_and_publish, store, job_id, data, file_name))
+ images = await asyncio.shield(decode_task)
+ result = await orchestrator.process_decoded_document(
+ images,
+ file_name,
+ ["markdown", "json"],
+ model_options=model_options,
+ demo=True,
+ asset_dir=store.job_dir(job_id) / "images",
+ asset_url_prefix=f"/v1/demo/jobs/{job_id}/assets/",
+ started_at=started_at,
+ )
+ publish_task = asyncio.create_task(asyncio.to_thread(store.publish_result, job_id, result))
+ await asyncio.shield(publish_task)
+ except asyncio.CancelledError:
+ # Threads cannot be cancelled: finish publication before writing failed,
+ # so a late decoder cannot resurrect a stopped job as processing.
+ if decode_task is not None:
+ await asyncio.gather(decode_task, return_exceptions=True)
+ if publish_task is not None:
+ await asyncio.gather(publish_task, return_exceptions=True)
+ with suppress(KeyError):
+ if store.get(job_id)["status"] != "success":
+ store.update(job_id, status="failed", error="The server stopped while processing this document.")
+ raise
+ except Exception as error:
+ LOGGER.warning(
+ "Demo processing failed (job_id=%s, error_type=%s)", job_id, type(error).__name__,
+ )
+ if isinstance(error, OSError):
+ with suppress(OSError):
+ store.discard_payload(job_id)
+ public_message = (
+ "Temporary storage is unavailable or full. Try again later."
+ if isinstance(error, OSError) else get_public_error_message(error)
+ )
+ with suppress(KeyError, OSError):
+ store.update(
+ job_id, status="failed", error=public_message,
+ **({"pages": [], "assets": []} if isinstance(error, OSError) else {}),
+ )
+
+
+async def _maintain_jobs(app) -> None:
+ while True:
+ await asyncio.sleep(30)
+ # Keep active work alive even when recognition lasts longer than the TTL.
+ for job_id in tuple(app.state.demo_tasks):
+ with suppress(KeyError, FileNotFoundError):
+ app.state.demo_store.keep_alive(job_id)
+ await asyncio.to_thread(app.state.demo_store.cleanup)
+
+
+async def start_demo(app) -> None:
+ app.state.demo_store = DemoStore()
+ app.state.demo_tasks = {}
+ await asyncio.to_thread(app.state.demo_store.cleanup)
+ app.state.demo_maintenance = asyncio.create_task(_maintain_jobs(app))
+
+
+async def stop_demo(app) -> None:
+ app.state.demo_maintenance.cancel()
+ tasks = list(app.state.demo_tasks.values())
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(app.state.demo_maintenance, *tasks, return_exceptions=True)
+
+
+# OXR Online Demo: independent of the existing SoMark-compatible parse API.
[email protected]("/demo/jobs")
+async def submit_demo_job(
+ request: Request,
+ file: UploadFile = File(...),
+ temperature: str = Form("0"),
+ top_p: str = Form("1"),
+ repetition_penalty: str = Form("1"),
+):
+ # Read the raw form as well: FastAPI substitutes defaults for empty fields,
+ # but explicitly blank model parameters must be rejected rather than reset.
+ form = await request.form()
+ model_options = {}
+ for name, default, minimum, maximum in (
+ ("temperature", temperature, 0.0, 2.0),
+ ("top_p", top_p, 0.0, 1.0),
+ ("repetition_penalty", repetition_penalty, 0.1, 2.0),
+ ):
+ try:
+ value = float(form.get(name, default))
+ except (TypeError, ValueError):
+ await file.close()
+ return _error(f"{name} must be a number between {minimum:g} and {maximum:g}.", 422)
+ if not math.isfinite(value) or not minimum <= value <= maximum:
+ await file.close()
+ return _error(f"{name} must be a finite number between {minimum:g} and {maximum:g}.", 422)
+ model_options[name] = value
+ file_name = Path((file.filename or "").replace("\\", "/")).name
+ if Path(file_name).suffix.lower() not in SUPPORTED_EXTENSIONS:
+ await file.close()
+ return _error("Upload a PDF or a supported image file.", 415)
+ data = bytearray()
+ try:
+ while chunk := await file.read(1024 * 1024):
+ data.extend(chunk)
+ if len(data) > MAX_UPLOAD_BYTES:
+ return _error("The file exceeds the 100 MiB upload limit.", 413)
+ finally:
+ await file.close()
+ if not data:
+ return _error("The uploaded file is empty.", 422)
+ store = request.app.state.demo_store
+ try:
+ manifest = await asyncio.to_thread(store.create, file_name)
+ except OSError:
+ return _error("The demo's temporary storage is unavailable or full. Try again later.", 503)
+ job_id = manifest["id"]
+ task = asyncio.create_task(_process_job(store, job_id, bytes(data), file_name, model_options))
+ request.app.state.demo_tasks[job_id] = task
+ task.add_done_callback(lambda _: request.app.state.demo_tasks.pop(job_id, None))
+ return _response({"id": job_id, "status": "queued"})
+
+
[email protected]("/demo/jobs/{job_id}")
+async def demo_job_status(request: Request, job_id: str):
+ try:
+ manifest = request.app.state.demo_store.get(job_id)
+ except KeyError:
+ return _error("This document is unavailable or has expired. Upload it again.", 404)
+ return _response({key: value for key, value in manifest.items() if key not in {"assets", "expires_at"}})
+
+
[email protected]("/demo/jobs/{job_id}/result")
+async def demo_job_result(request: Request, job_id: str):
+ try:
+ result = await asyncio.to_thread(request.app.state.demo_store.result, job_id)
+ except (KeyError, FileNotFoundError):
+ return _error("This document is unavailable or has expired. Upload it again.", 404)
+ except ValueError:
+ return _error("The document is not ready yet.", 409)
+ return _response(result)
+
+
[email protected]("/demo/jobs/{job_id}/assets/{asset_id}")
+async def demo_job_asset(request: Request, job_id: str, asset_id: str):
+ try:
+ path = request.app.state.demo_store.asset(job_id, asset_id)
+ except KeyError:
+ return _error("The image is unavailable or has expired.", 404)
+ return FileResponse(path, headers={"Cache-Control": "private, max-age=3600"})
diff --git a/oxr/server/demo_store.py b/oxr/server/demo_store.py
new file mode 100644
index 0000000..e81d351
--- /dev/null
+++ b/oxr/server/demo_store.py
@@ -0,0 +1,200 @@
+"""Short-lived demo jobs shared by the API's local worker processes."""
+
+from contextlib import contextmanager
+import getpass
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import tempfile
+import time
+import uuid
+
+
+JOB_TTL_SECONDS = 60 * 60
+MAX_JOBS = 32
+MAX_CACHE_BYTES = 1024 * 1024 * 1024
+JOB_ID = re.compile(r"^[0-9a-f]{32}$")
+ASSET_ID = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*\.(?:png|jpg|jpeg|webp)$")
+
+
+def default_store_root() -> Path:
+ installation = hashlib.sha256(str(Path(__file__).resolve().parent).encode()).hexdigest()[:12]
+ user = hashlib.sha256(getpass.getuser().encode()).hexdigest()[:12]
+ return Path(tempfile.gettempdir()) / f"oxr-demo-{user}-{installation}"
+
+
+@contextmanager
+def _admission_lock(path: Path):
+ with path.open("a+b") as lock:
+ if os.name == "nt":
+ import msvcrt
+
+ if lock.tell() == 0:
+ lock.write(b"\0")
+ lock.flush()
+ lock.seek(0)
+ msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
+ try:
+ yield
+ finally:
+ lock.seek(0)
+ msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ try:
+ yield
+ finally:
+ fcntl.flock(lock, fcntl.LOCK_UN)
+
+
+class DemoStore:
+ def __init__(self, root: Path | None = None, ttl: int = JOB_TTL_SECONDS,
+ max_jobs: int = MAX_JOBS, max_bytes: int = MAX_CACHE_BYTES):
+ self.root = root if root is not None else default_store_root()
+ self.ttl = ttl
+ self.max_jobs = max_jobs
+ self.max_bytes = max_bytes
+ self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
+
+ def job_dir(self, job_id: str) -> Path:
+ if not JOB_ID.fullmatch(job_id):
+ raise KeyError(job_id)
+ return self.root / job_id
+
+ @staticmethod
+ def _write_json(path: Path, data: dict) -> None:
+ temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
+ try:
+ temporary.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
+ temporary.replace(path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+ def create(self, file_name: str) -> dict:
+ # Admission is shared by workers as well as concurrent upload threads.
+ with _admission_lock(self.root / ".admission.lock"):
+ return self._create(file_name)
+
+ def _create(self, file_name: str) -> dict:
+ self.cleanup()
+ jobs = sum(1 for path in self.root.iterdir() if path.is_dir() and JOB_ID.fullmatch(path.name))
+ if jobs >= self.max_jobs:
+ raise OSError("The demo has reached its temporary document limit. Try again later.")
+ self.ensure_capacity()
+ job_id = uuid.uuid4().hex
+ directory = self.job_dir(job_id)
+ (directory / "images").mkdir(parents=True, mode=0o700)
+ (directory / "lease").touch()
+ now = time.time()
+ manifest = {
+ "id": job_id,
+ "status": "queued",
+ "file_name": file_name,
+ "pages": [],
+ "metadata": {},
+ "error": None,
+ "result_url": None,
+ "assets": [],
+ "expires_at": now + self.ttl,
+ }
+ try:
+ self._write_json(directory / "manifest.json", manifest)
+ except OSError:
+ shutil.rmtree(directory, ignore_errors=True)
+ raise
+ return manifest
+
+ def ensure_capacity(self, extra_bytes: int = 0) -> None:
+ total = extra_bytes
+ for path in self.root.rglob("*"):
+ try:
+ if path.is_file() and not path.is_symlink():
+ total += path.stat().st_size
+ except FileNotFoundError:
+ continue
+ if total > self.max_bytes:
+ raise OSError("The demo's temporary storage is full. Try again later.")
+
+ def discard_payload(self, job_id: str) -> None:
+ directory = self.job_dir(job_id)
+ shutil.rmtree(directory / "images", ignore_errors=True)
+ (directory / "result.json").unlink(missing_ok=True)
+
+ def get(self, job_id: str) -> dict:
+ try:
+ manifest = json.loads((self.job_dir(job_id) / "manifest.json").read_text(encoding="utf-8"))
+ except (FileNotFoundError, json.JSONDecodeError):
+ raise KeyError(job_id) from None
+ if self._expires_at(self.job_dir(job_id), manifest) <= time.time():
+ raise KeyError(job_id)
+ return manifest
+
+ def _expires_at(self, directory: Path, manifest: dict) -> float:
+ try:
+ return max(manifest["expires_at"], (directory / "lease").stat().st_mtime + self.ttl)
+ except FileNotFoundError:
+ return manifest["expires_at"]
+
+ def keep_alive(self, job_id: str) -> None:
+ # A separate lease prevents heartbeat writes racing manifest publication.
+ (self.job_dir(job_id) / "lease").touch(exist_ok=True)
+
+ def update(self, job_id: str, **changes) -> dict:
+ manifest = self.get(job_id)
+ manifest.update(changes, expires_at=time.time() + self.ttl)
+ self._write_json(self.job_dir(job_id) / "manifest.json", manifest)
+ return manifest
+
+ def publish_result(self, job_id: str, result: dict) -> None:
+ directory = self.job_dir(job_id)
+ self._write_json(directory / "result.json", result)
+ self.ensure_capacity()
+ assets = sorted(
+ path.name for path in (directory / "images").iterdir()
+ if ASSET_ID.fullmatch(path.name) and path.is_file() and not path.is_symlink()
+ )
+ self.update(
+ job_id,
+ status="success",
+ metadata=result.get("metadata", {}),
+ result_url=f"/v1/demo/jobs/{job_id}/result",
+ assets=assets,
+ )
+
+ def result(self, job_id: str) -> dict:
+ manifest = self.get(job_id)
+ if manifest["status"] != "success":
+ raise ValueError("The document is not ready yet.")
+ return json.loads((self.job_dir(job_id) / "result.json").read_text(encoding="utf-8"))
+
+ def asset(self, job_id: str, asset_id: str) -> Path:
+ manifest = self.get(job_id)
+ if not ASSET_ID.fullmatch(asset_id) or asset_id not in manifest["assets"]:
+ raise KeyError(asset_id)
+ directory = self.job_dir(job_id) / "images"
+ path = directory / asset_id
+ if path.is_symlink() or not path.is_file() or path.resolve().parent != directory.resolve():
+ raise KeyError(asset_id)
+ return path
+
+ def cleanup(self) -> None:
+ now = time.time()
+ for directory in self.root.iterdir():
+ if not directory.is_dir() or not JOB_ID.fullmatch(directory.name):
+ continue
+ try:
+ manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8"))
+ expired = self._expires_at(directory, manifest) <= now
+ except (FileNotFoundError, json.JSONDecodeError):
+ # Also reclaim interrupted job creation after the normal TTL.
+ try:
+ expired = directory.stat().st_mtime + self.ttl <= now
+ except FileNotFoundError:
+ continue
+ if expired:
+ shutil.rmtree(directory, ignore_errors=True)
diff --git a/oxr/server/queue/__init__.py b/oxr/server/queue/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/oxr/server/queue/memory_store.py b/oxr/server/queue/memory_store.py
new file mode 100644
index 0000000..0bea5ce
--- /dev/null
+++ b/oxr/server/queue/memory_store.py
@@ -0,0 +1,50 @@
+import asyncio
+from typing import Dict, Any, Optional
+
+
+def _build_task_payload(task_id: str) -> Dict[str, Any]:
+ return {
+ "record_id": None,
+ "task_id": task_id,
+ "status": "queuing",
+ "file_name": None,
+ "result": {},
+ "error": None,
+ "metadata": {},
+ }
+
+
+class MemoryTaskStore:
+ def __init__(self):
+ self._store: Dict[str, Dict[str, Any]] = {}
+ self._lock = asyncio.Lock()
+
+ async def create(self, task_id: str, file_name: Optional[str] = None) -> None:
+ async with self._lock:
+ self._store[task_id] = _build_task_payload(task_id)
+ self._store[task_id]["file_name"] = file_name
+
+ async def set_processing(self, task_id: str) -> None:
+ async with self._lock:
+ if task_id in self._store:
+ self._store[task_id]["status"] = "processing"
+
+ async def set_success(self, task_id: str, result: Dict[str, Any]) -> None:
+ async with self._lock:
+ if task_id in self._store:
+ self._store[task_id].update(
+ status="success",
+ file_name=result.get("file_name", self._store[task_id].get("file_name")),
+ result=result.get("result", {}),
+ metadata=result.get("metadata", {}),
+ error=None,
+ )
+
+ async def set_failed(self, task_id: str, error: str) -> None:
+ async with self._lock:
+ if task_id in self._store:
+ self._store[task_id].update(status="failed", error=error)
+
+ async def get(self, task_id: str) -> Optional[Dict[str, Any]]:
+ async with self._lock:
+ return self._store.get(task_id)
diff --git a/oxr/server/routes.py b/oxr/server/routes.py
new file mode 100644
index 0000000..d107f9c
--- /dev/null
+++ b/oxr/server/routes.py
@@ -0,0 +1,401 @@
+import json
+import logging
+import uuid
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+from fastapi import APIRouter, UploadFile, File, Form, BackgroundTasks, Request
+from fastapi.responses import JSONResponse
+from oxr.pipeline.errors import get_public_error_message
+from oxr.server.schemas import (
+ SyncParseResponse,
+ SyncParseData,
+ AsyncSubmitResponse,
+ AsyncSubmitData,
+ AsyncQueryResponse,
+ AsyncQueryData
+)
+from oxr.pipeline.orchestrator import process_document
+from oxr.server.queue.memory_store import MemoryTaskStore
+
+router = APIRouter()
+LOGGER = logging.getLogger(__name__)
+
+DEFAULT_OUTPUT_FORMATS = ["markdown", "json"]
+SUPPORTED_OUTPUT_FORMATS = {"markdown", "json"}
+INVALID_PARAM_CODE = 1133
+DEFAULT_ELEMENT_FORMATS = {
+ "image": "url",
+ "formula": "latex",
+ "table": "html",
+ "cs": "smiles",
+}
+SUPPORTED_ELEMENT_FORMATS = {
+ "image": {"url", "base64", "none", "file"},
+ "formula": {"latex", "mathml", "ascii"},
+ "table": {"html", "markdown", "image"},
+ "cs": {"smiles", "image"},
+}
+FUNCTIONAL_ELEMENT_FORMATS = {
+ "image": {"url", "base64", "none"},
+ "formula": {"latex"},
+ "table": {"html", "markdown"},
+ "cs": {"smiles", "image"},
+}
+FEATURE_CONFIG_SUPPORTED_KEYS = {"keep_header_footer"}
+MODEL_OPTION_RANGES = {
+ "temperature": (0.0, 2.0, True),
+ "top_p": (0.0, 1.0, True),
+ "repetition_penalty": (0.0, None, False),
+}
+
+
+@dataclass
+class ParseRequestOptions:
+ output_formats: List[str] = field(default_factory=lambda: DEFAULT_OUTPUT_FORMATS.copy())
+ keep_header_footer: bool = False
+ model_options: Dict[str, float] = field(default_factory=dict)
+ element_formats: Dict[str, str] = field(default_factory=lambda: DEFAULT_ELEMENT_FORMATS.copy())
+ warnings: List[str] = field(default_factory=list)
+
+
+def _api_error(message: str, code: int = INVALID_PARAM_CODE) -> JSONResponse:
+ return JSONResponse(status_code=200, content={"code": code, "message": message, "warnings": [], "data": None})
+
+
+def _format_issues(prefix: str, issues: List[str]) -> str:
+ return f"{prefix}: " + ";".join(issues)
+
+
+def _parse_output_formats(output_formats: Optional[List[str]]) -> tuple[List[str], List[str]]:
+ errors: List[str] = []
+ formats = output_formats or DEFAULT_OUTPUT_FORMATS
+ normalized = [item.strip().lower() for item in formats if item and item.strip()]
+ if not normalized:
+ return DEFAULT_OUTPUT_FORMATS.copy(), errors
+
+ invalid = [item for item in normalized if item not in SUPPORTED_OUTPUT_FORMATS]
+ for item in invalid:
+ if item == "zip":
+ errors.append("output_formats=zip is not supported by open-source OXR; zip packaging is not implemented.")
+ else:
+ errors.append(
+ f"output_formats={item} is invalid; supported values are markdown and json."
+ )
+ return [item for item in normalized if item in SUPPORTED_OUTPUT_FORMATS], errors
+
+
+def _parse_model_option(config: Dict[str, Any], key: str) -> Optional[float]:
+ if key not in config:
+ return None
+
+ value = config[key]
+ if isinstance(value, bool):
+ raise ValueError(f"extra.{key} must be a number.")
+
+ try:
+ parsed_value = float(value)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"extra.{key} must be a number.") from exc
+
+ minimum, maximum, include_minimum = MODEL_OPTION_RANGES[key]
+ if include_minimum:
+ if parsed_value < minimum:
+ raise ValueError(f"extra.{key} must be between {minimum} and {maximum}.")
+ elif parsed_value <= minimum:
+ raise ValueError(f"extra.{key} must be greater than {minimum}.")
+
+ if maximum is not None and parsed_value > maximum:
+ raise ValueError(f"extra.{key} must be between {minimum} and {maximum}.")
+
+ return parsed_value
+
+
+def _parse_feature_config(feature_config: Optional[str]) -> tuple[bool, List[str], List[str]]:
+ warnings: List[str] = []
+ errors: List[str] = []
+ if not feature_config:
+ return False, warnings, errors
+ try:
+ config = json.loads(feature_config)
+ except json.JSONDecodeError as exc:
+ errors.append("feature_config must be a JSON object.")
+ return False, warnings, errors
+
+ if not isinstance(config, dict):
+ errors.append("feature_config must be a JSON object.")
+ return False, warnings, errors
+
+ keep_header_footer = config.get("keep_header_footer", False)
+ if not isinstance(keep_header_footer, bool):
+ errors.append("feature_config.keep_header_footer must be a boolean.")
+ keep_header_footer = False
+
+ for key, value in sorted(config.items()):
+ if key in FEATURE_CONFIG_SUPPORTED_KEYS:
+ continue
+ if not isinstance(value, bool):
+ errors.append(f"feature_config.{key} must be a boolean.")
+ elif value:
+ warnings.append(
+ f"feature_config.{key}=true is accepted but ignored; open-source OXR only implements feature_config.keep_header_footer."
+ )
+ return keep_header_footer, warnings, errors
+
+
+def _parse_extra(extra: Optional[str]) -> tuple[Dict[str, float], List[str]]:
+ errors: List[str] = []
+ if not extra:
+ return {}, errors
+ try:
+ config = json.loads(extra)
+ except json.JSONDecodeError as exc:
+ errors.append("extra must be a JSON object.")
+ return {}, errors
+
+ if not isinstance(config, dict):
+ errors.append("extra must be a JSON object.")
+ return {}, errors
+
+ allowed_keys = set(MODEL_OPTION_RANGES)
+ extra_keys = set(config) - allowed_keys
+ for key in sorted(extra_keys):
+ supported_keys = ", ".join(sorted(allowed_keys))
+ errors.append(f"extra.{key} is unsupported; supported extra keys are {supported_keys}.")
+
+ model_options = {}
+ for key in MODEL_OPTION_RANGES:
+ try:
+ value = _parse_model_option(config, key)
+ except ValueError as exc:
+ errors.append(str(exc))
+ continue
+ if value is not None:
+ model_options[key] = value
+ return model_options, errors
+
+
+def _parse_element_formats(element_formats: Optional[str]) -> tuple[Dict[str, str], List[str]]:
+ errors: List[str] = []
+ parsed = DEFAULT_ELEMENT_FORMATS.copy()
+ if not element_formats:
+ return parsed, errors
+
+ try:
+ config = json.loads(element_formats)
+ except json.JSONDecodeError:
+ errors.append("element_formats must be a JSON object.")
+ return parsed, errors
+
+ if not isinstance(config, dict):
+ errors.append("element_formats must be a JSON object.")
+ return parsed, errors
+
+ for key, value in sorted(config.items()):
+ if key not in SUPPORTED_ELEMENT_FORMATS:
+ supported_keys = ", ".join(sorted(SUPPORTED_ELEMENT_FORMATS))
+ errors.append(f"element_formats.{key} is invalid; supported keys are {supported_keys}.")
+ continue
+ if not isinstance(value, str):
+ errors.append(f"element_formats.{key} must be a string.")
+ continue
+
+ normalized = value.strip().lower()
+ if normalized not in SUPPORTED_ELEMENT_FORMATS[key]:
+ supported_values = ", ".join(sorted(SUPPORTED_ELEMENT_FORMATS[key]))
+ errors.append(
+ f"element_formats.{key}={normalized} is invalid; supported values are {supported_values}."
+ )
+ continue
+
+ if normalized not in FUNCTIONAL_ELEMENT_FORMATS[key]:
+ if key == "image" and normalized == "file":
+ errors.append(
+ "element_formats.image=file is not supported by open-source OXR because output_formats=zip is not implemented."
+ )
+ elif key == "formula":
+ errors.append(
+ f"element_formats.formula={normalized} is not supported by open-source OXR; use element_formats.formula=latex."
+ )
+ elif key == "table" and normalized == "image":
+ errors.append(
+ "element_formats.table=image is not supported by open-source OXR; use element_formats.table=html or markdown."
+ )
+ continue
+
+ parsed[key] = normalized
+
+ return parsed, errors
+
+
+def _parse_request_options(
+ output_formats: Optional[List[str]],
+ feature_config: Optional[str],
+ extra: Optional[str],
+ element_formats: Optional[str],
+) -> tuple[Optional[ParseRequestOptions], List[str]]:
+ errors: List[str] = []
+ parsed_output_formats, output_errors = _parse_output_formats(output_formats)
+ element_format_options, element_errors = _parse_element_formats(element_formats)
+ keep_header_footer, feature_warnings, feature_errors = _parse_feature_config(feature_config)
+ model_options, extra_errors = _parse_extra(extra)
+ errors.extend(output_errors)
+ errors.extend(element_errors)
+ errors.extend(feature_errors)
+ errors.extend(extra_errors)
+ if errors:
+ return None, errors
+ return ParseRequestOptions(
+ output_formats=parsed_output_formats,
+ keep_header_footer=keep_header_footer,
+ model_options=model_options,
+ element_formats=element_format_options,
+ warnings=feature_warnings,
+ ), errors
+
+
+def _build_result_payload(result: dict) -> dict:
+ return {
+ "file_name": result["file_name"],
+ "outputs": result["outputs"],
+ }
+
+async def process_task_background(
+ task_store: MemoryTaskStore,
+ task_id: str,
+ file_bytes: bytes,
+ file_name: str,
+ output_formats: List[str],
+ keep_header_footer: bool,
+ model_options: Dict[str, float],
+ element_formats: Dict[str, str],
+):
+ await task_store.set_processing(task_id)
+ try:
+ result = await process_document(
+ file_bytes,
+ file_name,
+ output_formats,
+ keep_header_footer=keep_header_footer,
+ model_options=model_options,
+ element_formats=element_formats,
+ )
+ store_result = {
+ "file_name": result["file_name"],
+ "result": _build_result_payload(result),
+ "metadata": result["metadata"]
+ }
+ await task_store.set_success(task_id, store_result)
+ except Exception as e:
+ LOGGER.warning(
+ "Document processing failed (task_id=%s, error_type=%s)", task_id, type(e).__name__,
+ )
+ await task_store.set_failed(task_id, get_public_error_message(e))
+
[email protected]("/parse/sync", response_model=SyncParseResponse)
+async def parse_sync(
+ file: UploadFile = File(...),
+ api_key: str = Form(...),
+ output_formats: Optional[List[str]] = Form(None),
+ feature_config: Optional[str] = Form(None),
+ extra: Optional[str] = Form(None),
+ element_formats: Optional[str] = Form(None),
+):
+ options, errors = _parse_request_options(output_formats, feature_config, extra, element_formats)
+ if errors:
+ return _api_error(_format_issues("参数错误", errors))
+ assert options is not None
+
+ task_id = str(uuid.uuid4())
+ file_bytes = await file.read()
+
+ try:
+ result = await process_document(
+ file_bytes,
+ file.filename,
+ options.output_formats,
+ keep_header_footer=options.keep_header_footer,
+ model_options=options.model_options,
+ element_formats=options.element_formats,
+ )
+ return SyncParseResponse(
+ message="任务成功",
+ warnings=options.warnings,
+ data=SyncParseData(
+ task_id=task_id,
+ error=None,
+ result=_build_result_payload(result),
+ metadata=result["metadata"]
+ )
+ )
+ except Exception as e:
+ LOGGER.warning(
+ "Document processing failed (task_id=%s, error_type=%s)", task_id, type(e).__name__,
+ )
+ return _api_error(get_public_error_message(e), code=1137)
+
[email protected]("/parse/async", response_model=AsyncSubmitResponse)
+async def parse_async(
+ request: Request,
+ background_tasks: BackgroundTasks,
+ file: UploadFile = File(...),
+ api_key: str = Form(...),
+ output_formats: Optional[List[str]] = Form(None),
+ feature_config: Optional[str] = Form(None),
+ extra: Optional[str] = Form(None),
+ element_formats: Optional[str] = Form(None),
+):
+ options, errors = _parse_request_options(output_formats, feature_config, extra, element_formats)
+ if errors:
+ return _api_error(_format_issues("参数错误", errors))
+ assert options is not None
+
+ task_store: MemoryTaskStore = request.app.state.task_store
+ task_id = str(uuid.uuid4())
+ file_bytes = await file.read()
+
+ await task_store.create(task_id, file.filename)
+
+ background_tasks.add_task(
+ process_task_background,
+ task_store,
+ task_id,
+ file_bytes,
+ file.filename,
+ options.output_formats,
+ options.keep_header_footer,
+ options.model_options,
+ options.element_formats,
+ )
+
+ return AsyncSubmitResponse(
+ message="任务已提交",
+ warnings=options.warnings,
+ data=AsyncSubmitData(
+ task_id=task_id,
+ status="queuing"
+ )
+ )
+
[email protected]("/parse/async_check", response_model=AsyncQueryResponse)
+async def query_async(
+ request: Request,
+ task_id: str = Form(...),
+ api_key: str = Form(...),
+):
+ task_store: MemoryTaskStore = request.app.state.task_store
+ task = await task_store.get(task_id)
+ if not task:
+ return _api_error(f"Task not found: {task_id}")
+
+ return AsyncQueryResponse(
+ message="查询成功",
+ data=AsyncQueryData(
+ record_id=task.get("record_id"),
+ task_id=task["task_id"],
+ status=task["status"],
+ file_name=task.get("file_name"),
+ result=task.get("result") if task["status"] == "success" else None,
+ error=task.get("error"),
+ metadata=task.get("metadata", {})
+ )
+ )
diff --git a/oxr/server/schemas.py b/oxr/server/schemas.py
new file mode 100644
index 0000000..ca95a51
--- /dev/null
+++ b/oxr/server/schemas.py
@@ -0,0 +1,35 @@
+from pydantic import BaseModel
+from typing import Any, Dict, List, Optional
+
+class ResponseBase(BaseModel):
+ code: int = 0
+ message: str = "success"
+ warnings: List[str] = []
+
+class SyncParseData(BaseModel):
+ task_id: str
+ error: Optional[str] = None
+ result: Dict[str, Any]
+ metadata: Dict[str, Any]
+
+class SyncParseResponse(ResponseBase):
+ data: SyncParseData
+
+class AsyncSubmitData(BaseModel):
+ task_id: str
+ status: str
+
+class AsyncSubmitResponse(ResponseBase):
+ data: AsyncSubmitData
+
+class AsyncQueryData(BaseModel):
+ record_id: Optional[int] = None
+ task_id: str
+ status: str
+ file_name: Optional[str] = None
+ result: Optional[Dict[str, Any]] = None
+ error: Optional[str]
+ metadata: Dict[str, Any]
+
+class AsyncQueryResponse(ResponseBase):
+ data: AsyncQueryData
diff --git a/oxr/utils/__init__.py b/oxr/utils/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/oxr/utils/image.py b/oxr/utils/image.py
new file mode 100644
index 0000000..38ac8a8
--- /dev/null
+++ b/oxr/utils/image.py
@@ -0,0 +1,32 @@
+import cv2
+import numpy as np
+
+
+def resize_image(image: np.ndarray, scale: float) -> np.ndarray:
+ """Resize an image isotropically while keeping both dimensions nonzero."""
+ if scale <= 0:
+ raise ValueError("Image scale must be greater than zero.")
+ height, width = image.shape[:2]
+ target_size = (
+ max(1, round(width * scale)),
+ max(1, round(height * scale)),
+ )
+ return cv2.resize(image, target_size, interpolation=cv2.INTER_AREA)
+
+
+def crop_image(image: np.ndarray, bbox: list[float]) -> np.ndarray:
+ """
+ Crop an image using the given bounding box.
+ bbox: [x1, y1, x2, y2]
+ """
+ # D-FINE emits floating-point pixel coordinates. Quantize them to the
+ # nearest pixel so recognition crops match the reference pipeline.
+ x1, y1, x2, y2 = (round(value) for value in bbox)
+ # Ensure coordinates are within image boundaries
+ h, w = image.shape[:2]
+ x1 = max(0, x1)
+ y1 = max(0, y1)
+ x2 = min(w, x2)
+ y2 = min(h, y2)
+
+ return image[y1:y2, x1:x2].copy()
diff --git a/oxr/utils/pdf.py b/oxr/utils/pdf.py
new file mode 100644
index 0000000..5bbbdc6
--- /dev/null
+++ b/oxr/utils/pdf.py
@@ -0,0 +1,21 @@
+import threading
+
+import sopdf
+import numpy as np
+import cv2
+
+
+# PDFium requires process-wide exclusion, even for separate documents.
+_PDFIUM_LOCK = threading.Lock()
+
+def pdf_to_images(pdf_bytes: bytes, dpi: int = 150) -> list[np.ndarray]:
+ """Convert PDF bytes to a list of OpenCV images (numpy arrays, BGR format)."""
+ with _PDFIUM_LOCK:
+ images = []
+ with sopdf.open(stream=pdf_bytes) as doc:
+ for page in doc.pages:
+ png_bytes = page.render(dpi=dpi)
+ nparr = np.frombuffer(png_bytes, np.uint8)
+ cv_image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
+ images.append(cv_image)
+ return images
diff --git a/oxr/utils/table.py b/oxr/utils/table.py
new file mode 100644
index 0000000..2a9a7be
--- /dev/null
+++ b/oxr/utils/table.py
@@ -0,0 +1,161 @@
+import re
+from dataclasses import dataclass
+from html.parser import HTMLParser
+from typing import List, Optional
+
+
+@dataclass
+class _TableCell:
+ text: str
+ rowspan: int = 1
+ colspan: int = 1
+
+
+class _TableParser(HTMLParser):
+ def __init__(self):
+ super().__init__(convert_charrefs=True)
+ self.rows: List[List[_TableCell]] = []
+ self._table_depth = 0
+ self._current_row: Optional[List[_TableCell]] = None
+ self._current_cell: Optional[dict] = None
+
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None:
+ tag = tag.lower()
+ if tag == "table":
+ self._table_depth += 1
+ return
+ if self._table_depth == 0:
+ return
+ if tag == "tr":
+ self._current_row = []
+ return
+ if tag in {"td", "th"} and self._current_row is not None and self._current_cell is None:
+ attr_map = {key.lower(): value for key, value in attrs}
+ self._current_cell = {
+ "text": [],
+ "rowspan": _positive_int(attr_map.get("rowspan")),
+ "colspan": _positive_int(attr_map.get("colspan")),
+ }
+ return
+ if tag == "br" and self._current_cell is not None:
+ self._current_cell["text"].append(" ")
+ if tag == "img" and self._current_cell is not None:
+ src = dict(attrs).get("src")
+ if src:
+ self._current_cell["text"].append(f"![]({src})")
+
+ def handle_endtag(self, tag: str) -> None:
+ tag = tag.lower()
+ if tag in {"td", "th"} and self._current_cell is not None and self._current_row is not None:
+ self._current_row.append(
+ _TableCell(
+ text=_normalize_cell_text("".join(self._current_cell["text"])),
+ rowspan=self._current_cell["rowspan"],
+ colspan=self._current_cell["colspan"],
+ )
+ )
+ self._current_cell = None
+ return
+ if tag == "tr" and self._current_row is not None:
+ if self._current_row:
+ self.rows.append(self._current_row)
+ self._current_row = None
+ return
+ if tag == "table" and self._table_depth:
+ self._table_depth -= 1
+
+ def handle_data(self, data: str) -> None:
+ if self._current_cell is not None:
+ self._current_cell["text"].append(data)
+
+
+def _positive_int(value: Optional[str]) -> int:
+ try:
+ parsed = int(value or "1")
+ except ValueError:
+ return 1
+ return max(parsed, 1)
+
+
+def _normalize_cell_text(text: str) -> str:
+ return re.sub(r"\s+", " ", text).strip()
+
+
+def strip_table_code_fence(text: str) -> str:
+ text = text.strip()
+ match = re.search(r"```html\n(.*?)\n```", text, re.DOTALL | re.IGNORECASE)
+ if match:
+ return match.group(1).strip()
+ if "```" in text:
+ match = re.search(r"```(?:.*?)\n(.*?)\n```", text, re.DOTALL)
+ if match:
+ return match.group(1).strip()
+ return text
+
+
+def _expand_spans(rows: List[List[_TableCell]]) -> List[List[str]]:
+ expanded: List[List[str]] = []
+ pending: dict[int, tuple[str, int]] = {}
+
+ for source_row in rows:
+ row: List[str] = []
+ col_idx = 0
+
+ def fill_pending_cell() -> bool:
+ nonlocal col_idx
+ if col_idx not in pending:
+ return False
+ text, remaining = pending[col_idx]
+ row.append(text)
+ if remaining > 1:
+ pending[col_idx] = (text, remaining - 1)
+ else:
+ del pending[col_idx]
+ col_idx += 1
+ return True
+
+ for cell in source_row:
+ while fill_pending_cell():
+ pass
+ for _ in range(cell.colspan):
+ row.append(cell.text)
+ if cell.rowspan > 1:
+ pending[col_idx] = (cell.text, cell.rowspan - 1)
+ col_idx += 1
+
+ while pending and col_idx <= max(pending):
+ if not fill_pending_cell():
+ row.append("")
+ col_idx += 1
+
+ expanded.append(row)
+
+ return expanded
+
+
+def _escape_markdown_cell(text: str) -> str:
+ return text.replace("\\", "\\\\").replace("|", "\\|")
+
+
+def html_table_to_markdown(html: str) -> str:
+ """Convert an HTML table to Markdown, expanding rowspans and colspans."""
+ cleaned = strip_table_code_fence(html)
+ parser = _TableParser()
+ parser.feed(cleaned)
+
+ rows = _expand_spans(parser.rows)
+ if not rows:
+ return _normalize_cell_text(re.sub(r"<[^>]+>", " ", cleaned))
+
+ width = max(len(row) for row in rows)
+ padded_rows = [row + [""] * (width - len(row)) for row in rows]
+ escaped_rows = [
+ [_escape_markdown_cell(_normalize_cell_text(cell)) for cell in row]
+ for row in padded_rows
+ ]
+
+ header = escaped_rows[0]
+ separator = ["---"] * width
+ body = escaped_rows[1:]
+ markdown_rows = [header, separator, *body]
+ return "\n".join(f"| {' | '.join(row)} |" for row in markdown_rows)
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..8a5041a
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,40 @@
+[project]
+name = "somark-oxr"
+version = "0.1.0"
+description = "Optical Everything Recognition — high-performance document parsing"
+readme = "README.md"
+license = "Apache-2.0"
+license-files = ["LICENSE", "NOTICE"]
+requires-python = ">=3.10"
+dependencies = [
+ "typer",
+ "fastapi",
+ "uvicorn[standard]",
+ "python-multipart",
+ "openai",
+ "sopdf>=0.2.0",
+ "opencv-python",
+ "pydantic-settings",
+ "PyYAML",
+ "httpx",
+]
+
+[project.scripts]
+oxr = "oxr.cli.main:app"
+
+[project.urls]
+Homepage = "https://github.com/SoMarkAI/OXR"
+Repository = "https://github.com/SoMarkAI/OXR"
+Issues = "https://github.com/SoMarkAI/OXR/issues"
+"Hugging Face" = "https://huggingface.co/SoMarkAI/OXR-1.0"
+ModelScope = "https://modelscope.cn/models/SoMarkAI/OXR-1.0"
+
+[build-system]
+requires = ["setuptools>=77.0.0"]
+build-backend = "setuptools.build_meta"
+
+[tool.setuptools.packages.find]
+include = ["oxr*"]
+
+[tool.setuptools.package-data]
+"oxr.server" = ["demo/**/*", "demo/*"]
diff --git a/services/layout_analyze/.gitignore b/services/layout_analyze/.gitignore
new file mode 100644
index 0000000..e3fedc8
--- /dev/null
+++ b/services/layout_analyze/.gitignore
@@ -0,0 +1,6 @@
+__pycache__/
+*.py[cod]
+.pytest_cache/
+.venv/
+models/*
+!models/README.md
diff --git a/services/layout_analyze/README.md b/services/layout_analyze/README.md
new file mode 100644
index 0000000..7e9adb6
--- /dev/null
+++ b/services/layout_analyze/README.md
@@ -0,0 +1,240 @@
+# D-FINE Layout Analysis Service
+
+[![HuggingFace Model](https://img.shields.io/badge/HuggingFace-OXR--1.0-F59E0B?style=flat-square)](https://huggingface.co/SoMarkAI/OXR-1.0)
+[![ModelScope Model](https://img.shields.io/badge/ModelScope-OXR--1.0-624AFF?style=flat-square)](https://modelscope.cn/models/SoMarkAI/OXR-1.0)
+
+A small CPU/GPU HTTP service for a fixed D-FINE Stage-2 B2 layout-analysis
+model. This directory contains inference code for OXR's all-in-one image. Model
+weights are mounted at runtime and are not part of the source distribution.
+
+## Supported model
+
+- Architecture: HGNetv2 B2 + D-FINE Stage-2
+- Input: RGB images, resized and letterboxed to `960 x 960`
+- Classes: 12
+- Decoder layers: 4
+- Precision: FP16 autocast on CUDA; FP32 on CPU
+- Fast path: Batch1 CUDA Graph
+
+The service intentionally does not provide training, model registration,
+authentication, a task queue, or a web UI.
+
+## Requirements
+
+- Linux
+- For Docker deployment, use the [OXR all-in-one image](../../README.md#docker).
+- For native development, use Python 3.12 with PyTorch `2.10.0+cu129`,
+ matching the supported all-in-one model runtime.
+
+CUDA mode additionally requires an NVIDIA GPU, a recent driver compatible with
+CUDA 12.9, and NVIDIA Container Toolkit for Docker deployment.
+
+## Model checkpoint
+
+The layout checkpoint is bundled in the official `SoMarkAI/OXR-1.0` model
+repositories on [Hugging Face](https://huggingface.co/SoMarkAI/OXR-1.0) and
+[ModelScope](https://modelscope.cn/models/SoMarkAI/OXR-1.0):
+
+```text
+OXR-1.0/layout_analysis/last.pth
+OXR-1.0/layout_analysis/metadata.json
+```
+
+Prepare the complete release using the [model download instructions](../../README.md#model-download).
+If using Git, run `git lfs pull` first. The all-in-one container does not download weights automatically and
+mounts the complete model repository read-only at `/models/oxr-model`.
+
+The service reads `metadata.json` alongside the checkpoint (or the explicit
+`MODEL_METADATA_PATH`). Schema version 1 records the model version, checkpoint
+filename, byte size, SHA-256, architecture, preprocessing and class mapping.
+The model repository owns these values; the service does not hardcode a
+particular checkpoint's version or checksum.
+`model_version` must be a public `major.minor.patch` release version.
+
+For the current release:
+
+```text
+size: 78791307 bytes
+sha256: dff78ccf18439955362ca44a69eb28fb0b40222a7d278860589682de0176dc17
+```
+
+Startup fails before model loading if metadata is missing/malformed, weight
+size or SHA-256 differs, or architecture, input size, class IDs or preprocessing
+are unsupported. The checkpoint filename must match `MODEL_PATH`. Metadata is
+not a Transformers configuration and cannot request arbitrary architectures.
+Device, effective precision and CUDA Graph remain runtime settings.
+`/health` and `/model/info` report the public model version and configuration,
+not local checkpoint or metadata mount paths.
+
+## Start for native development
+
+For the supported single-GPU Docker deployment, follow the
+[OXR Docker instructions](../../README.md#docker). The model services remain
+internal to that container; the HTTP API is the only published endpoint.
+
+To run only this service for development, execute the following from this
+directory using the Python/PyTorch environment described above. Keep LA
+dependencies separate from the vLLM environment:
+
+```bash
+python -m venv --system-site-packages .venv
+.venv/bin/python -m pip install -r requirements.txt
+MODEL_PATH=/absolute/path/to/OXR-1.0/layout_analysis/last.pth \
+ PORT=8081 .venv/bin/python -m dfine_la
+```
+
+Wait until the service reports healthy:
+
+```bash
+curl http://127.0.0.1:8081/health
+```
+
+Stop this foreground process with Ctrl-C. Native mode binds all interfaces;
+only use it on a trusted development network.
+
+## Inference
+
+Upload one image:
+
+```bash
+curl -X POST http://127.0.0.1:8081/inference \
+```
+
+Upload a batch by repeating the same multipart field:
+
+```bash
+curl -X POST http://127.0.0.1:8081/inference \
+```
+
+Use one confidence threshold for every class:
+
+```bash
+curl -X POST http://127.0.0.1:8081/inference \
+ -F 'confidence=0.5'
+```
+
+Optionally override selected numeric class IDs with a JSON object. Classes not
+listed in `class_confidences` continue to use the global `confidence` value:
+
+| Class ID | Layout category |
+| ---: | --- |
+| `0` | Caption |
+| `1` | Footnote |
+| `2` | Formula |
+| `3` | Text |
+| `4` | Page-footer |
+| `5` | Page-header |
+| `6` | Picture |
+| `7` | Title |
+| `8` | Table |
+| `9` | Code Block |
+| `10` | Stamp |
+| `11` | Chemical Structure |
+
+```bash
+curl -X POST http://127.0.0.1:8081/inference \
+ -F 'confidence=0.5' \
+ -F 'class_confidences={"4":0.7,"8":0.3}'
+```
+
+In this example, Page-footer uses `0.7`, Table uses `0.3`, and every other
+category inherits the global `0.5` threshold.
+
+Or use the included Python client:
+
+```bash
+python examples/infer.py page.png --confidence 0.5
+```
+
+The response shape is:
+
+```json
+{
+ "status": "success",
+ "params": {},
+ "data": {
+ "labels": [[0]],
+ "boxes": [[[10.0, 20.0, 100.0, 200.0]]],
+ "scores": [[0.99]]
+ }
+}
+```
+
+Without confidence fields, `labels`, `boxes`, and `scores` contain the model's
+300 raw top-query outputs for each image, preserving the original API behavior.
+`confidence` and every per-class override must be between `0` and `1`, and a
+prediction is kept when `score >= threshold`. Filtering preserves model order
+and keeps labels, boxes, and scores aligned. The service does not apply NMS.
+
+## API
+
+| Method | Path | Purpose |
+| --- | --- | --- |
+| `POST` | `/inference` | Multipart image inference |
+| `GET` | `/health` | Readiness and runtime configuration |
+| `GET` | `/model/info` | Model and device information |
+
+Every successful inference response includes a `Server-Timing` header with
+request-read, decode, preprocess, queue, and inference durations.
+
+`POST /inference` accepts repeated `images` files plus optional multipart fields
+`confidence` (one global threshold) and `class_confidences` (a JSON object whose
+keys are numeric class IDs). If both are omitted, no filtering is applied and
+the response `params` remains `{}`. When either field is supplied, `params`
+reports the effective global threshold and normalized class overrides.
+
+## Runtime configuration
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `MODEL_PATH` | `/models/layout_analysis/last.pth` | Checkpoint path; explicitly set by the all-in-one supervisor |
+| `MODEL_METADATA_PATH` | `metadata.json` alongside `MODEL_PATH` | Model metadata path |
+| `PORT` | `8000` | Native HTTP port; explicitly set by the all-in-one supervisor |
+| `DFINE_DEVICE` | `cuda` | Inference device: `cuda`, `cpu`, or `auto` |
+| `DFINE_CUDA_GRAPH` | `1` | Enable the Batch1 CUDA Graph path |
+| `DFINE_PARALLEL_PREPROCESS` | `1` | Run CPU decode/preprocess outside the GPU critical section |
+| `LOG_LEVEL` | `info` | Uvicorn log level |
+
+CUDA Graph is used for Batch1 CUDA requests. Other batch sizes and all CPU
+requests use eager inference. `DFINE_CUDA_GRAPH=1` is safely ignored when the
+resolved device is CPU. The runtime deliberately loads one model instance per
+container.
+
+For native CPU development, start the service with:
+
+```bash
+MODEL_PATH=/absolute/path/to/OXR-1.0/layout_analysis/last.pth \
+ PORT=8081 DFINE_DEVICE=cpu DFINE_CUDA_GRAPH=0 .venv/bin/python -m dfine_la
+```
+
+CPU inference uses the same checkpoint and API contract, but is expected to be
+substantially slower than CUDA inference at the fixed `960 x 960` input size.
+
+## Development tests
+
+The unit and API-contract tests do not require a GPU or checkpoint:
+
+```bash
+python -m pip install -r requirements-dev.txt
+pytest -q
+```
+
+Final release validation should build the OXR all-in-one image, start it with
+the real checkpoint on an NVIDIA GPU, and compare its outputs with the known
+reference service. Its model runtime remains fixed to vLLM `0.19.1`, PyTorch
+`2.10.0+cu129` and Transformers `5.6.2`; there is no separate LA Docker image.
+
+## Third-party code
+
+The model implementation is an inference-only adaptation of D-FINE. See
+[`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) and
+[`third_party/D-FINE/LICENSE`](third_party/D-FINE/LICENSE).
+
+The surrounding project code is licensed under [Apache 2.0](../../LICENSE).
+See also [NOTICE](../../NOTICE). The model checkpoint has separate distribution
+terms stated by the model repositories and is not included in this code distribution.
diff --git a/services/layout_analyze/THIRD_PARTY_NOTICES.md b/services/layout_analyze/THIRD_PARTY_NOTICES.md
new file mode 100644
index 0000000..ec876ba
--- /dev/null
+++ b/services/layout_analyze/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,15 @@
+# Third-party notices
+
+This service contains a minimal inference-only adaptation of
+[D-FINE](https://github.com/Peterande/D-FINE).
+
+D-FINE is distributed under the Apache License 2.0. A copy of its license is
+included at `third_party/D-FINE/LICENSE`.
+
+The files under `dfine_la/model/` were adapted for a fixed Stage-2 B2 layout
+analysis architecture. Changes include packaging, fixed inference
+configuration, FP16 inference integration, CUDA Graph-compatible
+postprocessing, and removal of training-only entry points.
+
+The model checkpoint is not included. Its distribution terms must be provided
+separately by the publisher of the model artifact.
diff --git a/services/layout_analyze/dfine_la/__init__.py b/services/layout_analyze/dfine_la/__init__.py
new file mode 100644
index 0000000..7eb8352
--- /dev/null
+++ b/services/layout_analyze/dfine_la/__init__.py
@@ -0,0 +1,3 @@
+"""D-FINE layout-analysis inference service."""
+
+__version__ = "0.1.0"
diff --git a/services/layout_analyze/dfine_la/__main__.py b/services/layout_analyze/dfine_la/__main__.py
new file mode 100644
index 0000000..596e10b
--- /dev/null
+++ b/services/layout_analyze/dfine_la/__main__.py
@@ -0,0 +1,15 @@
+"""Start the HTTP service with ``python -m dfine_la``."""
+
+import os
+
+import uvicorn
+
+
+if __name__ == "__main__":
+ uvicorn.run(
+ "dfine_la.api:app",
+ host="0.0.0.0",
+ port=int(os.getenv("PORT", "8000")),
+ workers=1,
+ log_level=os.getenv("LOG_LEVEL", "info"),
+ )
diff --git a/services/layout_analyze/dfine_la/api.py b/services/layout_analyze/dfine_la/api.py
new file mode 100644
index 0000000..b7e6454
--- /dev/null
+++ b/services/layout_analyze/dfine_la/api.py
@@ -0,0 +1,114 @@
+"""FastAPI application for D-FINE layout analysis."""
+
+from __future__ import annotations
+
+import asyncio
+from contextlib import asynccontextmanager
+import time
+from typing import Callable, List, Optional, TYPE_CHECKING
+
+from fastapi import FastAPI, File, Form, Header, HTTPException, Response, UploadFile
+
+from .confidence import format_predictions, parse_confidence_policy
+from .config import Settings
+
+if TYPE_CHECKING:
+ from .runtime import ModelRuntime
+
+
+def _server_timing(values: dict[str, float]) -> str:
+ return ", ".join(f"{name};dur={duration:.6f}" for name, duration in values.items())
+
+
+def create_app(
+ runtime_factory: Optional[Callable[[Settings], "ModelRuntime"]] = None,
+) -> FastAPI:
+ @asynccontextmanager
+ async def lifespan(app: FastAPI):
+ settings = Settings.from_env()
+ app.state.settings = settings
+ factory = runtime_factory
+ if factory is None:
+ from .runtime import ModelRuntime
+
+ factory = ModelRuntime
+ app.state.runtime = factory(settings)
+ yield
+
+ app = FastAPI(
+ title="D-FINE LA API",
+ description="Inference API for the D-FINE Stage-2 B2 layout model",
+ version="0.1.0",
+ lifespan=lifespan,
+ docs_url=None,
+ redoc_url=None,
+ openapi_url=None,
+ )
+
+ @app.post("/inference")
+ async def inference(
+ response: Response,
+ images: List[UploadFile] = File(...),
+ confidence: Optional[float] = Form(default=None),
+ class_confidences: Optional[str] = Form(default=None),
+ x_dfine_parallel_preprocess: Optional[str] = Header(default=None),
+ ):
+ runtime = app.state.runtime
+ try:
+ global_confidence, confidence_overrides, response_params = (
+ parse_confidence_policy(
+ confidence,
+ class_confidences,
+ runtime.settings.num_classes,
+ )
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ request_started = time.perf_counter()
+ payloads = [await image.read() for image in images]
+ request_read_ms = (time.perf_counter() - request_started) * 1000
+ parallel = (
+ runtime.settings.parallel_preprocess
+ if x_dfine_parallel_preprocess is None
+ else x_dfine_parallel_preprocess == "1"
+ )
+
+ if parallel:
+ loop = asyncio.get_running_loop()
+ ready, decode_ms, preprocess_ms = await loop.run_in_executor(
+ None, lambda: runtime.prepare(payloads)
+ )
+ outputs, inference_timings = await loop.run_in_executor(
+ None, lambda: runtime.infer(ready)
+ )
+ else:
+ ready, decode_ms, preprocess_ms = runtime.prepare(payloads)
+ outputs, inference_timings = runtime.infer(ready)
+
+ response.headers["Server-Timing"] = _server_timing(
+ {
+ "request_read": request_read_ms,
+ "decode": decode_ms,
+ "preprocess": preprocess_ms,
+ **inference_timings,
+ }
+ )
+ return format_predictions(
+ outputs,
+ global_confidence,
+ confidence_overrides,
+ response_params,
+ )
+
+ @app.get("/health")
+ async def health():
+ return app.state.runtime.health()
+
+ @app.get("/model/info")
+ async def model_info():
+ return app.state.runtime.info()
+
+ return app
+
+
+app = create_app()
diff --git a/services/layout_analyze/dfine_la/confidence.py b/services/layout_analyze/dfine_la/confidence.py
new file mode 100644
index 0000000..2656cc1
--- /dev/null
+++ b/services/layout_analyze/dfine_la/confidence.py
@@ -0,0 +1,105 @@
+"""Request-level confidence filtering for layout predictions."""
+
+from __future__ import annotations
+
+import json
+import math
+from numbers import Real
+
+import numpy as np
+
+
+def _validate_confidence(value: object, field: str) -> float:
+ if isinstance(value, bool) or not isinstance(value, Real):
+ raise ValueError(f"{field} must be a number between 0 and 1")
+ confidence = float(value)
+ if not math.isfinite(confidence) or not 0 <= confidence <= 1:
+ raise ValueError(f"{field} must be a finite number between 0 and 1")
+ return confidence
+
+
+def parse_confidence_policy(
+ confidence: float | None,
+ class_confidences: str | None,
+ num_classes: int,
+) -> tuple[float, dict[int, float], dict[str, object]]:
+ """Parse the global threshold and optional JSON class overrides."""
+ global_confidence = (
+ 0.0
+ if confidence is None
+ else _validate_confidence(confidence, "confidence")
+ )
+ overrides: dict[int, float] = {}
+ raw_overrides = class_confidences.strip() if class_confidences else ""
+ if raw_overrides:
+ try:
+ parsed = json.loads(raw_overrides)
+ except json.JSONDecodeError as exc:
+ raise ValueError("class_confidences must be a JSON object") from exc
+ if not isinstance(parsed, dict):
+ raise ValueError("class_confidences must be a JSON object")
+ for raw_label, raw_confidence in parsed.items():
+ try:
+ label = int(raw_label)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(
+ f"class_confidences key {raw_label!r} must be a class id"
+ ) from exc
+ if str(label) != str(raw_label):
+ raise ValueError(
+ f"class_confidences key {raw_label!r} must be a class id"
+ )
+ if not 0 <= label < num_classes:
+ raise ValueError(
+ f"class_confidences class id {label} is outside [0, {num_classes - 1}]"
+ )
+ overrides[label] = _validate_confidence(
+ raw_confidence,
+ f"class_confidences[{label}]",
+ )
+
+ if confidence is None and not raw_overrides:
+ return global_confidence, overrides, {}
+ return global_confidence, overrides, {
+ "confidence": global_confidence,
+ "class_confidences": {
+ str(label): threshold for label, threshold in sorted(overrides.items())
+ },
+ }
+
+
+def format_predictions(
+ outputs: tuple[np.ndarray, np.ndarray, np.ndarray],
+ global_confidence: float = 0.0,
+ class_confidences: dict[int, float] | None = None,
+ params: dict[str, object] | None = None,
+) -> dict:
+ """Filter aligned labels, boxes, and scores without changing their order."""
+ labels, boxes, scores = outputs
+ overrides = class_confidences or {}
+ if global_confidence == 0.0 and not overrides:
+ filtered_labels = labels.tolist()
+ filtered_boxes = boxes.tolist()
+ filtered_scores = scores.tolist()
+ else:
+ filtered_labels = []
+ filtered_boxes = []
+ filtered_scores = []
+ for image_labels, image_boxes, image_scores in zip(labels, boxes, scores):
+ thresholds = np.full(image_scores.shape, global_confidence, dtype=np.float64)
+ for label, threshold in overrides.items():
+ thresholds[image_labels == label] = threshold
+ keep = image_scores >= thresholds
+ filtered_labels.append(image_labels[keep].tolist())
+ filtered_boxes.append(image_boxes[keep].tolist())
+ filtered_scores.append(image_scores[keep].tolist())
+
+ return {
+ "status": "success",
+ "params": params or {},
+ "data": {
+ "labels": filtered_labels,
+ "boxes": filtered_boxes,
+ "scores": filtered_scores,
+ },
+ }
diff --git a/services/layout_analyze/dfine_la/config.py b/services/layout_analyze/dfine_la/config.py
new file mode 100644
index 0000000..573cf16
--- /dev/null
+++ b/services/layout_analyze/dfine_la/config.py
@@ -0,0 +1,139 @@
+"""Fixed configuration and checkpoint validation for the LA model."""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, field, replace
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+
+
+# Capabilities of this implementation, not the identity of a specific checkpoint.
+SUPPORTED_METADATA = {
+ "schema_version": 1,
+ "model_type": "dfine",
+ "architecture": "stage2_b2",
+ "num_classes": 12,
+ "image_size": 960,
+ "color_order": "rgb",
+ "resize_backend": "opencv_lanczos4",
+ "postprocess": "model_letterbox",
+ "provides_reading_order": False,
+ "id2label": {
+ str(i): label for i, label in enumerate([
+ "Caption", "Footnote", "Formula", "Text", "Page-footer", "Page-header",
+ "Picture", "Title", "Table", "Code Block", "Stamp", "Chemical Structure",
+ ])
+ },
+}
+
+
+def _enabled(name: str, default: str = "1") -> bool:
+ return os.getenv(name, default).strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _device(name: str = "DFINE_DEVICE", default: str = "cuda") -> str:
+ value = os.getenv(name, default).strip().lower()
+ if value not in {"auto", "cpu", "cuda"}:
+ raise RuntimeError(
+ f"{name} must be one of auto, cpu, or cuda; got {value!r}"
+ )
+ return value
+
+
+@dataclass(frozen=True)
+class Settings:
+ model_path: Path
+ metadata_path: Path | None = None
+ model_version: str = "unknown"
+ checkpoint_size_bytes: int | None = None
+ checkpoint_sha256: str | None = None
+ id2label: dict[str, str] = field(default_factory=dict)
+ architecture: str = "stage2_b2"
+ num_classes: int = 12
+ image_size: int = 960
+ color_order: str = "rgb"
+ resize_backend: str = "opencv_lanczos4"
+ postprocess: str = "model_letterbox"
+ device: str = "cuda"
+ inference_precision: str = "fp16_autocast"
+ cuda_graph_enabled: bool = True
+ parallel_preprocess: bool = True
+
+ @classmethod
+ def from_env(cls) -> "Settings":
+ return cls(
+ model_path=Path(os.getenv("MODEL_PATH", "/models/layout_analysis/last.pth")),
+ metadata_path=(
+ Path(os.environ["MODEL_METADATA_PATH"])
+ if os.getenv("MODEL_METADATA_PATH") else None
+ ),
+ device=_device(),
+ cuda_graph_enabled=_enabled("DFINE_CUDA_GRAPH"),
+ parallel_preprocess=_enabled("DFINE_PARALLEL_PREPROCESS"),
+ )
+
+ def load_metadata(self) -> "Settings":
+ """Load model-owned identity and reject unsupported inference semantics."""
+ path = self.metadata_path or self.model_path.with_name("metadata.json")
+ try:
+ metadata = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ raise RuntimeError(f"unable to read model metadata: {path}") from exc
+ if not isinstance(metadata, dict):
+ raise RuntimeError("model metadata must be a JSON object")
+ for name, supported in SUPPORTED_METADATA.items():
+ value = metadata.get(name)
+ if type(value) is not type(supported) or value != supported:
+ raise RuntimeError(f"unsupported model metadata field: {name}")
+ version = metadata.get("model_version")
+ if not isinstance(version, str) or not re.fullmatch(r"\d+\.\d+\.\d+", version):
+ raise RuntimeError("model metadata requires a public model_version (major.minor.patch)")
+ # Do not resolve an arbitrary path from metadata; MODEL_PATH remains explicit.
+ if metadata.get("checkpoint") != self.model_path.name:
+ raise RuntimeError("model metadata checkpoint does not match MODEL_PATH filename")
+ size = metadata.get("checkpoint_size_bytes")
+ sha256 = metadata.get("checkpoint_sha256")
+ if type(size) is not int or size <= 0:
+ raise RuntimeError("model metadata requires positive checkpoint_size_bytes")
+ if not isinstance(sha256, str) or not re.fullmatch(r"[0-9a-f]{64}", sha256):
+ raise RuntimeError("model metadata requires a lowercase checkpoint_sha256")
+ return replace(
+ self, metadata_path=path, model_version=version,
+ checkpoint_size_bytes=size, checkpoint_sha256=sha256,
+ architecture=metadata["architecture"], num_classes=metadata["num_classes"],
+ image_size=metadata["image_size"], color_order=metadata["color_order"],
+ resize_backend=metadata["resize_backend"], postprocess=metadata["postprocess"],
+ id2label=metadata["id2label"],
+ )
+
+ def validate_checkpoint(self) -> "Settings":
+ if not self.model_path.is_file():
+ raise RuntimeError(
+ f"checkpoint not found: {self.model_path}; mount the model at this path"
+ )
+ declared = self.load_metadata()
+ actual_size = self.model_path.stat().st_size
+ if actual_size != declared.checkpoint_size_bytes:
+ raise RuntimeError(
+ f"checkpoint size mismatch: expected {declared.checkpoint_size_bytes}, got {actual_size}"
+ )
+ digest = hashlib.sha256()
+ with self.model_path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
+ digest.update(chunk)
+ actual_sha256 = digest.hexdigest()
+ if actual_sha256 != declared.checkpoint_sha256:
+ raise RuntimeError(
+ f"checkpoint SHA-256 mismatch: expected {declared.checkpoint_sha256}, got {actual_sha256}"
+ )
+ return declared
+
+ def public_dict(self) -> dict:
+ data = asdict(self)
+ # Local mount locations are operational details, not public model metadata.
+ data.pop("model_path")
+ data.pop("metadata_path")
+ return data
diff --git a/services/layout_analyze/dfine_la/cuda_graph.py b/services/layout_analyze/dfine_la/cuda_graph.py
new file mode 100644
index 0000000..2068893
--- /dev/null
+++ b/services/layout_analyze/dfine_la/cuda_graph.py
@@ -0,0 +1,77 @@
+"""Native CUDA Graph replay for fixed-shape Batch1 inference."""
+
+from __future__ import annotations
+
+import torch
+
+
+def _signature(images: torch.Tensor, sizes: torch.Tensor) -> tuple:
+ return tuple(images.shape), images.dtype, tuple(sizes.shape), sizes.dtype
+
+
+class _CapturedForward:
+ def __init__(self, model, images, sizes, warmup_iterations: int) -> None:
+ self.static_images = torch.empty_like(images)
+ self.static_sizes = torch.empty_like(sizes)
+ self.static_images.copy_(images)
+ self.static_sizes.copy_(sizes)
+
+ warmup_stream = torch.cuda.Stream(device=images.device)
+ warmup_stream.wait_stream(torch.cuda.current_stream(images.device))
+ with torch.cuda.stream(warmup_stream), torch.no_grad():
+ for _ in range(warmup_iterations):
+ model(self.static_images, self.static_sizes)
+ torch.cuda.current_stream(images.device).wait_stream(warmup_stream)
+
+ self.graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(self.graph), torch.no_grad():
+ self.static_outputs = model(self.static_images, self.static_sizes)
+
+ def __call__(self, images, sizes):
+ self.static_images.copy_(images)
+ self.static_sizes.copy_(sizes)
+ self.graph.replay()
+ return self.static_outputs
+
+
+class CUDAGraphModel:
+ def __init__(self, model, warmup_iterations: int = 3) -> None:
+ self.model = model
+ self.device = model.device
+ self.warmup_iterations = warmup_iterations
+ self._captures: dict[tuple, _CapturedForward] = {}
+
+ def __call__(self, images: torch.Tensor, sizes: torch.Tensor):
+ if images.shape[0] != 1:
+ with torch.no_grad():
+ return self.model(images, sizes)
+ signature = _signature(images, sizes)
+ capture = self._captures.get(signature)
+ if capture is None:
+ capture = _CapturedForward(
+ self.model,
+ images,
+ sizes,
+ self.warmup_iterations,
+ )
+ self._captures[signature] = capture
+ return capture(images, sizes)
+
+ def warmup(self, image_size: int) -> None:
+ images = torch.zeros(
+ (1, 3, image_size, image_size),
+ dtype=torch.float32,
+ device=self.device,
+ )
+ sizes = torch.full(
+ (1, 2),
+ image_size,
+ dtype=torch.int64,
+ device=self.device,
+ )
+ self(images, sizes)
+ torch.cuda.synchronize(self.device)
+
+ @property
+ def ready(self) -> bool:
+ return bool(self._captures)
diff --git a/services/layout_analyze/dfine_la/model/__init__.py b/services/layout_analyze/dfine_la/model/__init__.py
new file mode 100644
index 0000000..0d81892
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/__init__.py
@@ -0,0 +1,5 @@
+"""Minimal D-FINE model implementation used by the inference service."""
+
+from .model import load_model
+
+__all__ = ["load_model"]
diff --git a/services/layout_analyze/dfine_la/model/backbone.py b/services/layout_analyze/dfine_la/model/backbone.py
new file mode 100644
index 0000000..ccc7a11
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/backbone.py
@@ -0,0 +1,618 @@
+"""
+reference
+- https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py
+
+Copyright (c) 2024 The D-FINE Authors. All Rights Reserved.
+"""
+
+import logging
+import os
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+class FrozenBatchNorm2d(nn.Module):
+ """copy and modified from https://github.com/facebookresearch/detr/blob/master/models/backbone.py
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt,
+ without which any other models than torchvision.models.resnet[18,34,50,101]
+ produce nans.
+ """
+
+ def __init__(self, num_features, eps=1e-5):
+ super(FrozenBatchNorm2d, self).__init__()
+ n = num_features
+ self.register_buffer("weight", torch.ones(n))
+ self.register_buffer("bias", torch.zeros(n))
+ self.register_buffer("running_mean", torch.zeros(n))
+ self.register_buffer("running_var", torch.ones(n))
+ self.eps = eps
+ self.num_features = n
+
+ def _load_from_state_dict(
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ ):
+ num_batches_tracked_key = prefix + "num_batches_tracked"
+ if num_batches_tracked_key in state_dict:
+ del state_dict[num_batches_tracked_key]
+
+ super(FrozenBatchNorm2d, self)._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
+
+ def forward(self, x):
+ # move reshapes to the beginning
+ # to make it fuser-friendly
+ w = self.weight.reshape(1, -1, 1, 1)
+ b = self.bias.reshape(1, -1, 1, 1)
+ rv = self.running_var.reshape(1, -1, 1, 1)
+ rm = self.running_mean.reshape(1, -1, 1, 1)
+ scale = w * (rv + self.eps).rsqrt()
+ bias = b - rm * scale
+ return x * scale + bias
+
+ def extra_repr(self):
+ return "{num_features}, eps={eps}".format(**self.__dict__)
+
+# Constants for initialization
+kaiming_normal_ = nn.init.kaiming_normal_
+zeros_ = nn.init.zeros_
+ones_ = nn.init.ones_
+
+__all__ = ["HGNetv2"]
+
+def safe_barrier():
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
+ torch.distributed.barrier()
+ else:
+ pass
+
+def safe_get_rank():
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
+ return torch.distributed.get_rank()
+ else:
+ return 0
+
+class LearnableAffineBlock(nn.Module):
+ def __init__(self, scale_value=1.0, bias_value=0.0):
+ super().__init__()
+ self.scale = nn.Parameter(torch.tensor([scale_value]), requires_grad=True)
+ self.bias = nn.Parameter(torch.tensor([bias_value]), requires_grad=True)
+
+ def forward(self, x):
+ return self.scale * x + self.bias
+
+
+class ConvBNAct(nn.Module):
+ def __init__(
+ self,
+ in_chs,
+ out_chs,
+ kernel_size,
+ stride=1,
+ groups=1,
+ padding="",
+ use_act=True,
+ use_lab=False,
+ ):
+ super().__init__()
+ self.use_act = use_act
+ self.use_lab = use_lab
+ if padding == "same":
+ self.conv = nn.Sequential(
+ nn.ZeroPad2d([0, 1, 0, 1]),
+ nn.Conv2d(in_chs, out_chs, kernel_size, stride, groups=groups, bias=False),
+ )
+ else:
+ self.conv = nn.Conv2d(
+ in_chs,
+ out_chs,
+ kernel_size,
+ stride,
+ padding=(kernel_size - 1) // 2,
+ groups=groups,
+ bias=False,
+ )
+ self.bn = nn.BatchNorm2d(out_chs)
+ if self.use_act:
+ self.act = nn.ReLU()
+ else:
+ self.act = nn.Identity()
+ if self.use_act and self.use_lab:
+ self.lab = LearnableAffineBlock()
+ else:
+ self.lab = nn.Identity()
+
+ def forward(self, x):
+ x = self.conv(x)
+ x = self.bn(x)
+ x = self.act(x)
+ x = self.lab(x)
+ return x
+
+
+class LightConvBNAct(nn.Module):
+ def __init__(
+ self,
+ in_chs,
+ out_chs,
+ kernel_size,
+ groups=1,
+ use_lab=False,
+ ):
+ super().__init__()
+ self.conv1 = ConvBNAct(
+ in_chs,
+ out_chs,
+ kernel_size=1,
+ use_act=False,
+ use_lab=use_lab,
+ )
+ self.conv2 = ConvBNAct(
+ out_chs,
+ out_chs,
+ kernel_size=kernel_size,
+ groups=out_chs,
+ use_act=True,
+ use_lab=use_lab,
+ )
+
+ def forward(self, x):
+ x = self.conv1(x)
+ x = self.conv2(x)
+ return x
+
+
+class StemBlock(nn.Module):
+ # for HGNetv2
+ def __init__(self, in_chs, mid_chs, out_chs, use_lab=False):
+ super().__init__()
+ self.stem1 = ConvBNAct(
+ in_chs,
+ mid_chs,
+ kernel_size=3,
+ stride=2,
+ use_lab=use_lab,
+ )
+ self.stem2a = ConvBNAct(
+ mid_chs,
+ mid_chs // 2,
+ kernel_size=2,
+ stride=1,
+ use_lab=use_lab,
+ )
+ self.stem2b = ConvBNAct(
+ mid_chs // 2,
+ mid_chs,
+ kernel_size=2,
+ stride=1,
+ use_lab=use_lab,
+ )
+ self.stem3 = ConvBNAct(
+ mid_chs * 2,
+ mid_chs,
+ kernel_size=3,
+ stride=2,
+ use_lab=use_lab,
+ )
+ self.stem4 = ConvBNAct(
+ mid_chs,
+ out_chs,
+ kernel_size=1,
+ stride=1,
+ use_lab=use_lab,
+ )
+ self.pool = nn.MaxPool2d(kernel_size=2, stride=1, ceil_mode=True)
+
+ def forward(self, x):
+ x = self.stem1(x)
+ x = F.pad(x, (0, 1, 0, 1))
+ x2 = self.stem2a(x)
+ x2 = F.pad(x2, (0, 1, 0, 1))
+ x2 = self.stem2b(x2)
+ x1 = self.pool(x)
+ x = torch.cat([x1, x2], dim=1)
+ x = self.stem3(x)
+ x = self.stem4(x)
+ return x
+
+
+class EseModule(nn.Module):
+ def __init__(self, chs):
+ super().__init__()
+ self.conv = nn.Conv2d(
+ chs,
+ chs,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ )
+ self.sigmoid = nn.Sigmoid()
+
+ def forward(self, x):
+ identity = x
+ x = x.mean((2, 3), keepdim=True)
+ x = self.conv(x)
+ x = self.sigmoid(x)
+ return torch.mul(identity, x)
+
+
+class HG_Block(nn.Module):
+ def __init__(
+ self,
+ in_chs,
+ mid_chs,
+ out_chs,
+ layer_num,
+ kernel_size=3,
+ residual=False,
+ light_block=False,
+ use_lab=False,
+ agg="ese",
+ drop_path=0.0,
+ ):
+ super().__init__()
+ self.residual = residual
+
+ self.layers = nn.ModuleList()
+ for i in range(layer_num):
+ if light_block:
+ self.layers.append(
+ LightConvBNAct(
+ in_chs if i == 0 else mid_chs,
+ mid_chs,
+ kernel_size=kernel_size,
+ use_lab=use_lab,
+ )
+ )
+ else:
+ self.layers.append(
+ ConvBNAct(
+ in_chs if i == 0 else mid_chs,
+ mid_chs,
+ kernel_size=kernel_size,
+ stride=1,
+ use_lab=use_lab,
+ )
+ )
+
+ # feature aggregation
+ total_chs = in_chs + layer_num * mid_chs
+ if agg == "se":
+ aggregation_squeeze_conv = ConvBNAct(
+ total_chs,
+ out_chs // 2,
+ kernel_size=1,
+ stride=1,
+ use_lab=use_lab,
+ )
+ aggregation_excitation_conv = ConvBNAct(
+ out_chs // 2,
+ out_chs,
+ kernel_size=1,
+ stride=1,
+ use_lab=use_lab,
+ )
+ self.aggregation = nn.Sequential(
+ aggregation_squeeze_conv,
+ aggregation_excitation_conv,
+ )
+ else:
+ aggregation_conv = ConvBNAct(
+ total_chs,
+ out_chs,
+ kernel_size=1,
+ stride=1,
+ use_lab=use_lab,
+ )
+ att = EseModule(out_chs)
+ self.aggregation = nn.Sequential(
+ aggregation_conv,
+ att,
+ )
+
+ self.drop_path = nn.Dropout(drop_path) if drop_path else nn.Identity()
+
+ def forward(self, x):
+ identity = x
+ output = [x]
+ for layer in self.layers:
+ x = layer(x)
+ output.append(x)
+ x = torch.cat(output, dim=1)
+ x = self.aggregation(x)
+ if self.residual:
+ x = self.drop_path(x) + identity
+ return x
+
+
+class HG_Stage(nn.Module):
+ def __init__(
+ self,
+ in_chs,
+ mid_chs,
+ out_chs,
+ block_num,
+ layer_num,
+ downsample=True,
+ light_block=False,
+ kernel_size=3,
+ use_lab=False,
+ agg="se",
+ drop_path=0.0,
+ ):
+ super().__init__()
+ self.downsample = downsample
+ if downsample:
+ self.downsample = ConvBNAct(
+ in_chs,
+ in_chs,
+ kernel_size=3,
+ stride=2,
+ groups=in_chs,
+ use_act=False,
+ use_lab=use_lab,
+ )
+ else:
+ self.downsample = nn.Identity()
+
+ blocks_list = []
+ for i in range(block_num):
+ blocks_list.append(
+ HG_Block(
+ in_chs if i == 0 else out_chs,
+ mid_chs,
+ out_chs,
+ layer_num,
+ residual=False if i == 0 else True,
+ kernel_size=kernel_size,
+ light_block=light_block,
+ use_lab=use_lab,
+ agg=agg,
+ drop_path=drop_path[i] if isinstance(drop_path, (list, tuple)) else drop_path,
+ )
+ )
+ self.blocks = nn.Sequential(*blocks_list)
+
+ def forward(self, x):
+ x = self.downsample(x)
+ x = self.blocks(x)
+ return x
+
+
+class HGNetv2(nn.Module):
+ """
+ HGNetV2
+ Args:
+ stem_channels: list. Number of channels for the stem block.
+ stage_type: str. The stage configuration of HGNet. such as the number of channels, stride, etc.
+ use_lab: boolean. Whether to use LearnableAffineBlock in network.
+ lr_mult_list: list. Control the learning rate of different stages.
+ Returns:
+ model: nn.Layer. Specific HGNetV2 model depends on args.
+ """
+
+ arch_configs = {
+ "B0": {
+ "stem_channels": [3, 16, 16],
+ "stage_config": {
+ # in_channels, mid_channels, out_channels, num_blocks, downsample, light_block, kernel_size, layer_num
+ "stage1": [16, 16, 64, 1, False, False, 3, 3],
+ "stage2": [64, 32, 256, 1, True, False, 3, 3],
+ "stage3": [256, 64, 512, 2, True, True, 5, 3],
+ "stage4": [512, 128, 1024, 1, True, True, 5, 3],
+ },
+ "url": "https://github.com/Peterande/storage/releases/download/dfinev1.0/PPHGNetV2_B0_stage1.pth",
+ },
+ "B1": {
+ "stem_channels": [3, 24, 32],
+ "stage_config": {
+ # in_channels, mid_channels, out_channels, num_blocks, downsample, light_block, kernel_size, layer_num
+ "stage1": [32, 32, 64, 1, False, False, 3, 3],
+ "stage2": [64, 48, 256, 1, True, False, 3, 3],
+ "stage3": [256, 96, 512, 2, True, True, 5, 3],
+ "stage4": [512, 192, 1024, 1, True, True, 5, 3],
+ },
+ "url": "https://github.com/Peterande/storage/releases/download/dfinev1.0/PPHGNetV2_B1_stage1.pth",
+ },
+ "B2": {
+ "stem_channels": [3, 24, 32],
+ "stage_config": {
+ # in_channels, mid_channels, out_channels, num_blocks, downsample, light_block, kernel_size, layer_num
+ "stage1": [32, 32, 96, 1, False, False, 3, 4],
+ "stage2": [96, 64, 384, 1, True, False, 3, 4],
+ "stage3": [384, 128, 768, 3, True, True, 5, 4],
+ "stage4": [768, 256, 1536, 1, True, True, 5, 4],
+ },
+ "url": "https://github.com/Peterande/storage/releases/download/dfinev1.0/PPHGNetV2_B2_stage1.pth",
+ },
+ "B3": {
+ "stem_channels": [3, 24, 32],
+ "stage_config": {
+ # in_channels, mid_channels, out_channels, num_blocks, downsample, light_block, kernel_size, layer_num
+ "stage1": [32, 32, 128, 1, False, False, 3, 5],
+ "stage2": [128, 64, 512, 1, True, False, 3, 5],
+ "stage3": [512, 128, 1024, 3, True, True, 5, 5],
+ "stage4": [1024, 256, 2048, 1, True, True, 5, 5],
+ },
+ "url": "https://github.com/Peterande/storage/releases/download/dfinev1.0/PPHGNetV2_B3_stage1.pth",
+ },
+ "B4": {
+ "stem_channels": [3, 32, 48],
+ "stage_config": {
+ # in_channels, mid_channels, out_channels, num_blocks, downsample, light_block, kernel_size, layer_num
+ "stage1": [48, 48, 128, 1, False, False, 3, 6],
+ "stage2": [128, 96, 512, 1, True, False, 3, 6],
+ "stage3": [512, 192, 1024, 3, True, True, 5, 6],
+ "stage4": [1024, 384, 2048, 1, True, True, 5, 6],
+ },
+ "url": "https://github.com/Peterande/storage/releases/download/dfinev1.0/PPHGNetV2_B4_stage1.pth",
+ },
+ "B5": {
+ "stem_channels": [3, 32, 64],
+ "stage_config": {
+ # in_channels, mid_channels, out_channels, num_blocks, downsample, light_block, kernel_size, layer_num
+ "stage1": [64, 64, 128, 1, False, False, 3, 6],
+ "stage2": [128, 128, 512, 2, True, False, 3, 6],
+ "stage3": [512, 256, 1024, 5, True, True, 5, 6],
+ "stage4": [1024, 512, 2048, 2, True, True, 5, 6],
+ },
+ "url": "https://github.com/Peterande/storage/releases/download/dfinev1.0/PPHGNetV2_B5_stage1.pth",
+ },
+ "B6": {
+ "stem_channels": [3, 48, 96],
+ "stage_config": {
+ # in_channels, mid_channels, out_channels, num_blocks, downsample, light_block, kernel_size, layer_num
+ "stage1": [96, 96, 192, 2, False, False, 3, 6],
+ "stage2": [192, 192, 512, 3, True, False, 3, 6],
+ "stage3": [512, 384, 1024, 6, True, True, 5, 6],
+ "stage4": [1024, 768, 2048, 3, True, True, 5, 6],
+ },
+ "url": "https://github.com/Peterande/storage/releases/download/dfinev1.0/PPHGNetV2_B6_stage1.pth",
+ },
+ }
+
+ def __init__(
+ self,
+ name,
+ use_lab=False,
+ return_idx=[1, 2, 3],
+ freeze_stem_only=True,
+ freeze_at=0,
+ freeze_norm=True,
+ pretrained=True,
+ local_model_dir="weight/hgnetv2/",
+ ):
+ super().__init__()
+ self.use_lab = use_lab
+ self.return_idx = return_idx
+
+ stem_channels = self.arch_configs[name]["stem_channels"]
+ stage_config = self.arch_configs[name]["stage_config"]
+ download_url = self.arch_configs[name]["url"]
+
+ self._out_strides = [4, 8, 16, 32]
+ self._out_channels = [stage_config[k][2] for k in stage_config]
+
+ # stem
+ self.stem = StemBlock(
+ in_chs=stem_channels[0],
+ mid_chs=stem_channels[1],
+ out_chs=stem_channels[2],
+ use_lab=use_lab,
+ )
+
+ # stages
+ self.stages = nn.ModuleList()
+ for i, k in enumerate(stage_config):
+ (
+ in_channels,
+ mid_channels,
+ out_channels,
+ block_num,
+ downsample,
+ light_block,
+ kernel_size,
+ layer_num,
+ ) = stage_config[k]
+ self.stages.append(
+ HG_Stage(
+ in_channels,
+ mid_channels,
+ out_channels,
+ block_num,
+ layer_num,
+ downsample,
+ light_block,
+ kernel_size,
+ use_lab,
+ )
+ )
+
+ if freeze_at >= 0:
+ self._freeze_parameters(self.stem)
+ if not freeze_stem_only:
+ for i in range(min(freeze_at + 1, len(self.stages))):
+ self._freeze_parameters(self.stages[i])
+
+ if freeze_norm:
+ self._freeze_norm(self)
+
+ if pretrained:
+ RED, GREEN, RESET = "\033[91m", "\033[92m", "\033[0m"
+ try:
+ # If the file doesn't exist locally, download from the URL
+ if safe_get_rank() == 0:
+ print(
+ GREEN
+ + "If the pretrained HGNetV2 can't be downloaded automatically. Please check your network connection."
+ + RESET
+ )
+ print(
+ GREEN
+ + "Please check your network connection. Or download the model manually from "
+ + RESET
+ + f"{download_url}"
+ + GREEN
+ + " to "
+ + RESET
+ + f"{local_model_dir}."
+ + RESET
+ )
+ state = torch.hub.load_state_dict_from_url(
+ download_url, map_location="cpu", model_dir=local_model_dir
+ )
+ print(f"Loaded stage1 {name} HGNetV2 from URL.")
+
+ # Wait for rank 0 to download the model
+ safe_barrier()
+
+ # All processes load the downloaded model
+ model_path = local_model_dir + "PPHGNetV2_" + name + "_stage1.pth"
+ state = torch.load(model_path, map_location="cpu")
+
+ self.load_state_dict(state)
+ print(f"Loaded stage1 {name} HGNetV2 from URL.")
+
+ except (Exception, KeyboardInterrupt) as e:
+ if safe_get_rank() == 0:
+ print(f"{str(e)}")
+ logging.error(
+ RED + "CRITICAL WARNING: Failed to load pretrained HGNetV2 model" + RESET
+ )
+ logging.error(
+ GREEN
+ + "Please check your network connection. Or download the model manually from "
+ + RESET
+ + f"{download_url}"
+ + GREEN
+ + " to "
+ + RESET
+ + f"{local_model_dir}."
+ + RESET
+ )
+ exit()
+
+ def _freeze_norm(self, m: nn.Module):
+ if isinstance(m, nn.BatchNorm2d):
+ m = FrozenBatchNorm2d(m.num_features)
+ else:
+ for name, child in m.named_children():
+ _child = self._freeze_norm(child)
+ if _child is not child:
+ setattr(m, name, _child)
+ return m
+
+ def _freeze_parameters(self, m: nn.Module):
+ for p in m.parameters():
+ p.requires_grad = False
+
+ def forward(self, x):
+ x = self.stem(x)
+ outs = []
+ for idx, stage in enumerate(self.stages):
+ x = stage(x)
+ if idx in self.return_idx:
+ outs.append(x)
+ return outs
diff --git a/services/layout_analyze/dfine_la/model/box_ops.py b/services/layout_analyze/dfine_la/model/box_ops.py
new file mode 100644
index 0000000..1e2acba
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/box_ops.py
@@ -0,0 +1,93 @@
+"""
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+https://github.com/facebookresearch/detr/blob/main/util/box_ops.py
+"""
+
+import torch
+from torch import Tensor
+from torchvision.ops.boxes import box_area
+
+
+def box_cxcywh_to_xyxy(x):
+ x_c, y_c, w, h = x.unbind(-1)
+ b = [
+ (x_c - 0.5 * w.clamp(min=0.0)),
+ (y_c - 0.5 * h.clamp(min=0.0)),
+ (x_c + 0.5 * w.clamp(min=0.0)),
+ (y_c + 0.5 * h.clamp(min=0.0)),
+ ]
+ return torch.stack(b, dim=-1)
+
+
+def box_xyxy_to_cxcywh(x: Tensor) -> Tensor:
+ x0, y0, x1, y1 = x.unbind(-1)
+ b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)]
+ return torch.stack(b, dim=-1)
+
+
+# modified from torchvision to also return the union
+def box_iou(boxes1: Tensor, boxes2: Tensor):
+ area1 = box_area(boxes1)
+ area2 = box_area(boxes2)
+
+ lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
+ rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
+
+ wh = (rb - lt).clamp(min=0) # [N,M,2]
+ inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
+
+ union = area1[:, None] + area2 - inter
+
+ iou = inter / union
+ return iou, union
+
+
+def generalized_box_iou(boxes1, boxes2):
+ """
+ Generalized IoU from https://giou.stanford.edu/
+
+ The boxes should be in [x0, y0, x1, y1] format
+
+ Returns a [N, M] pairwise matrix, where N = len(boxes1)
+ and M = len(boxes2)
+ """
+ # degenerate boxes gives inf / nan results
+ # so do an early check
+ assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
+ assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
+ iou, union = box_iou(boxes1, boxes2)
+
+ lt = torch.min(boxes1[:, None, :2], boxes2[:, :2])
+ rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
+
+ wh = (rb - lt).clamp(min=0) # [N,M,2]
+ area = wh[:, :, 0] * wh[:, :, 1]
+
+ return iou - (area - union) / area
+
+
+def masks_to_boxes(masks):
+ """Compute the bounding boxes around the provided masks
+
+ The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.
+
+ Returns a [N, 4] tensors, with the boxes in xyxy format
+ """
+ if masks.numel() == 0:
+ return torch.zeros((0, 4), device=masks.device)
+
+ h, w = masks.shape[-2:]
+
+ y = torch.arange(0, h, dtype=torch.float)
+ x = torch.arange(0, w, dtype=torch.float)
+ y, x = torch.meshgrid(y, x)
+
+ x_mask = masks * x.unsqueeze(0)
+ x_max = x_mask.flatten(1).max(-1)[0]
+ x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
+
+ y_mask = masks * y.unsqueeze(0)
+ y_max = y_mask.flatten(1).max(-1)[0]
+ y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
+
+ return torch.stack([x_min, y_min, x_max, y_max], 1)
diff --git a/services/layout_analyze/dfine_la/model/decoder.py b/services/layout_analyze/dfine_la/model/decoder.py
new file mode 100644
index 0000000..405049a
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/decoder.py
@@ -0,0 +1,971 @@
+"""
+D-FINE: Redefine Regression Task of DETRs as Fine-grained Distribution Refinement
+Copyright (c) 2024 The D-FINE Authors. All Rights Reserved.
+---------------------------------------------------------------------------------
+Modified from RT-DETR (https://github.com/lyuwenyu/RT-DETR)
+Copyright (c) 2023 lyuwenyu. All Rights Reserved.
+"""
+
+import copy
+import functools
+import math
+from collections import OrderedDict
+from typing import List
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.nn.init as init
+
+from .denoising import get_contrastive_denoising_training_group
+from .dfine_utils import distance2bbox, weighting_function
+from .utils import (
+ bias_init_with_prob,
+ deformable_attention_core_func_v2,
+ get_activation,
+ inverse_sigmoid,
+)
+
+__all__ = ["DFINETransformer"]
+
+
+class MLP(nn.Module):
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers, act="relu"):
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
+ )
+ self.act = get_activation(act)
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = self.act(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+class MSDeformableAttention(nn.Module):
+ def __init__(
+ self,
+ embed_dim=256,
+ num_heads=8,
+ num_levels=4,
+ num_points=4,
+ method="default",
+ offset_scale=0.5,
+ ):
+ """Multi-Scale Deformable Attention"""
+ super(MSDeformableAttention, self).__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.num_levels = num_levels
+ self.offset_scale = offset_scale
+
+ if isinstance(num_points, list):
+ assert len(num_points) == num_levels, ""
+ num_points_list = num_points
+ else:
+ num_points_list = [num_points for _ in range(num_levels)]
+
+ self.num_points_list = num_points_list
+
+ num_points_scale = [1 / n for n in num_points_list for _ in range(n)]
+ self.register_buffer(
+ "num_points_scale", torch.tensor(num_points_scale, dtype=torch.float32)
+ )
+
+ self.total_points = num_heads * sum(num_points_list)
+ self.method = method
+
+ self.head_dim = embed_dim // num_heads
+ assert (
+ self.head_dim * num_heads == self.embed_dim
+ ), "embed_dim must be divisible by num_heads"
+
+ self.sampling_offsets = nn.Linear(embed_dim, self.total_points * 2)
+ self.attention_weights = nn.Linear(embed_dim, self.total_points)
+
+ self.ms_deformable_attn_core = functools.partial(
+ deformable_attention_core_func_v2, method=self.method
+ )
+
+ self._reset_parameters()
+
+ if method == "discrete":
+ for p in self.sampling_offsets.parameters():
+ p.requires_grad = False
+
+ def _reset_parameters(self):
+ # sampling_offsets
+ init.constant_(self.sampling_offsets.weight, 0)
+ thetas = torch.arange(self.num_heads, dtype=torch.float32) * (
+ 2.0 * math.pi / self.num_heads
+ )
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = grid_init / grid_init.abs().max(-1, keepdim=True).values
+ grid_init = grid_init.reshape(self.num_heads, 1, 2).tile([1, sum(self.num_points_list), 1])
+ scaling = torch.concat([torch.arange(1, n + 1) for n in self.num_points_list]).reshape(
+ 1, -1, 1
+ )
+ grid_init *= scaling
+ self.sampling_offsets.bias.data[...] = grid_init.flatten()
+
+ # attention_weights
+ init.constant_(self.attention_weights.weight, 0)
+ init.constant_(self.attention_weights.bias, 0)
+
+ def forward(
+ self,
+ query: torch.Tensor,
+ reference_points: torch.Tensor,
+ value: torch.Tensor,
+ value_spatial_shapes: List[int],
+ ):
+ """
+ Args:
+ query (Tensor): [bs, query_length, C]
+ reference_points (Tensor): [bs, query_length, n_levels, 2], range in [0, 1], top-left (0,0),
+ bottom-right (1, 1), including padding area
+ value (Tensor): [bs, value_length, C]
+ value_spatial_shapes (List): [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]
+
+ Returns:
+ output (Tensor): [bs, Length_{query}, C]
+ """
+ bs, Len_q = query.shape[:2]
+
+ sampling_offsets: torch.Tensor = self.sampling_offsets(query)
+ sampling_offsets = sampling_offsets.reshape(
+ bs, Len_q, self.num_heads, sum(self.num_points_list), 2
+ )
+
+ attention_weights = self.attention_weights(query).reshape(
+ bs, Len_q, self.num_heads, sum(self.num_points_list)
+ )
+ attention_weights = F.softmax(attention_weights, dim=-1)
+
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.tensor(value_spatial_shapes)
+ offset_normalizer = offset_normalizer.flip([1]).reshape(1, 1, 1, self.num_levels, 1, 2)
+ sampling_locations = (
+ reference_points.reshape(bs, Len_q, 1, self.num_levels, 1, 2)
+ + sampling_offsets / offset_normalizer
+ )
+ elif reference_points.shape[-1] == 4:
+ # reference_points [8, 480, None, 1, 4]
+ # sampling_offsets [8, 480, 8, 12, 2]
+ num_points_scale = self.num_points_scale.to(dtype=query.dtype).unsqueeze(-1)
+ offset = (
+ sampling_offsets
+ * num_points_scale
+ * reference_points[:, :, None, :, 2:]
+ * self.offset_scale
+ )
+ sampling_locations = reference_points[:, :, None, :, :2] + offset
+ else:
+ raise ValueError(
+ "Last dim of reference_points must be 2 or 4, but get {} instead.".format(
+ reference_points.shape[-1]
+ )
+ )
+
+ output = self.ms_deformable_attn_core(
+ value, value_spatial_shapes, sampling_locations, attention_weights, self.num_points_list
+ )
+
+ return output
+
+
+class TransformerDecoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model=256,
+ n_head=8,
+ dim_feedforward=1024,
+ dropout=0.0,
+ activation="relu",
+ n_levels=4,
+ n_points=4,
+ cross_attn_method="default",
+ layer_scale=None,
+ ):
+ super(TransformerDecoderLayer, self).__init__()
+ if layer_scale is not None:
+ dim_feedforward = round(layer_scale * dim_feedforward)
+ d_model = round(layer_scale * d_model)
+
+ # self attention
+ self.self_attn = nn.MultiheadAttention(d_model, n_head, dropout=dropout, batch_first=True)
+ self.dropout1 = nn.Dropout(dropout)
+ self.norm1 = nn.LayerNorm(d_model)
+
+ # cross attention
+ self.cross_attn = MSDeformableAttention(
+ d_model, n_head, n_levels, n_points, method=cross_attn_method
+ )
+ self.dropout2 = nn.Dropout(dropout)
+
+ # gate
+ self.gateway = Gate(d_model)
+
+ # ffn
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
+ self.activation = get_activation(activation)
+ self.dropout3 = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
+ self.dropout4 = nn.Dropout(dropout)
+ self.norm3 = nn.LayerNorm(d_model)
+
+ self._reset_parameters()
+
+ def _reset_parameters(self):
+ init.xavier_uniform_(self.linear1.weight)
+ init.xavier_uniform_(self.linear2.weight)
+
+ def with_pos_embed(self, tensor, pos):
+ return tensor if pos is None else tensor + pos
+
+ def forward_ffn(self, tgt):
+ return self.linear2(self.dropout3(self.activation(self.linear1(tgt))))
+
+ def forward(
+ self, target, reference_points, value, spatial_shapes, attn_mask=None, query_pos_embed=None
+ ):
+ # self attention
+ q = k = self.with_pos_embed(target, query_pos_embed)
+
+ target2, _ = self.self_attn(q, k, value=target, attn_mask=attn_mask)
+ target = target + self.dropout1(target2)
+ target = self.norm1(target)
+
+ # cross attention
+ target2 = self.cross_attn(
+ self.with_pos_embed(target, query_pos_embed), reference_points, value, spatial_shapes
+ )
+
+ target = self.gateway(target, self.dropout2(target2))
+
+ # ffn
+ target2 = self.forward_ffn(target)
+ target = target + self.dropout4(target2)
+ target = self.norm3(target.clamp(min=-65504, max=65504))
+
+ return target
+
+
+class Gate(nn.Module):
+ def __init__(self, d_model):
+ super(Gate, self).__init__()
+ self.gate = nn.Linear(2 * d_model, 2 * d_model)
+ bias = bias_init_with_prob(0.5)
+ init.constant_(self.gate.bias, bias)
+ init.constant_(self.gate.weight, 0)
+ self.norm = nn.LayerNorm(d_model)
+
+ def forward(self, x1, x2):
+ gate_input = torch.cat([x1, x2], dim=-1)
+ gates = torch.sigmoid(self.gate(gate_input))
+ gate1, gate2 = gates.chunk(2, dim=-1)
+ return self.norm(gate1 * x1 + gate2 * x2)
+
+
+class Integral(nn.Module):
+ """
+ A static layer that calculates integral results from a distribution.
+
+ This layer computes the target location using the formula: `sum{Pr(n) * W(n)}`,
+ where Pr(n) is the softmax probability vector representing the discrete
+ distribution, and W(n) is the non-uniform Weighting Function.
+
+ Args:
+ reg_max (int): Max number of the discrete bins. Default is 32.
+ It can be adjusted based on the dataset or task requirements.
+ """
+
+ def __init__(self, reg_max=32):
+ super(Integral, self).__init__()
+ self.reg_max = reg_max
+
+ def forward(self, x, project):
+ shape = x.shape
+ x = F.softmax(x.reshape(-1, self.reg_max + 1), dim=1)
+ x = F.linear(x, project.to(x.device)).reshape(-1, 4)
+ return x.reshape(list(shape[:-1]) + [-1])
+
+
+class LQE(nn.Module):
+ def __init__(self, k, hidden_dim, num_layers, reg_max):
+ super(LQE, self).__init__()
+ self.k = k
+ self.reg_max = reg_max
+ self.reg_conf = MLP(4 * (k + 1), hidden_dim, 1, num_layers)
+ init.constant_(self.reg_conf.layers[-1].bias, 0)
+ init.constant_(self.reg_conf.layers[-1].weight, 0)
+
+ def forward(self, scores, pred_corners):
+ B, L, _ = pred_corners.size()
+ prob = F.softmax(pred_corners.reshape(B, L, 4, self.reg_max + 1), dim=-1)
+ prob_topk, _ = prob.topk(self.k, dim=-1)
+ stat = torch.cat([prob_topk, prob_topk.mean(dim=-1, keepdim=True)], dim=-1)
+ quality_score = self.reg_conf(stat.reshape(B, L, -1))
+ return scores + quality_score
+
+
+class TransformerDecoder(nn.Module):
+ """
+ Transformer Decoder implementing Fine-grained Distribution Refinement (FDR).
+
+ This decoder refines object detection predictions through iterative updates across multiple layers,
+ utilizing attention mechanisms, location quality estimators, and distribution refinement techniques
+ to improve bounding box accuracy and robustness.
+ """
+
+ def __init__(
+ self,
+ hidden_dim,
+ decoder_layer,
+ decoder_layer_wide,
+ num_layers,
+ num_head,
+ reg_max,
+ reg_scale,
+ up,
+ eval_idx=-1,
+ layer_scale=2,
+ ):
+ super(TransformerDecoder, self).__init__()
+ self.hidden_dim = hidden_dim
+ self.num_layers = num_layers
+ self.layer_scale = layer_scale
+ self.num_head = num_head
+ self.eval_idx = eval_idx if eval_idx >= 0 else num_layers + eval_idx
+ self.up, self.reg_scale, self.reg_max = up, reg_scale, reg_max
+ self.layers = nn.ModuleList(
+ [copy.deepcopy(decoder_layer) for _ in range(self.eval_idx + 1)]
+ + [copy.deepcopy(decoder_layer_wide) for _ in range(num_layers - self.eval_idx - 1)]
+ )
+ self.lqe_layers = nn.ModuleList(
+ [copy.deepcopy(LQE(4, 64, 2, reg_max)) for _ in range(num_layers)]
+ )
+
+ def value_op(self, memory, value_proj, value_scale, memory_mask, memory_spatial_shapes):
+ """
+ Preprocess values for MSDeformableAttention.
+ """
+ value = value_proj(memory) if value_proj is not None else memory
+ value = F.interpolate(memory, size=value_scale) if value_scale is not None else value
+ if memory_mask is not None:
+ value = value * memory_mask.to(value.dtype).unsqueeze(-1)
+ value = value.reshape(value.shape[0], value.shape[1], self.num_head, -1)
+ split_shape = [h * w for h, w in memory_spatial_shapes]
+ return value.permute(0, 2, 3, 1).split(split_shape, dim=-1)
+
+ def convert_to_deploy(self):
+ self.register_buffer(
+ "project",
+ weighting_function(self.reg_max, self.up, self.reg_scale, deploy=True),
+ persistent=False,
+ )
+ self.layers = self.layers[: self.eval_idx + 1]
+ self.lqe_layers = nn.ModuleList(
+ [nn.Identity()] * (self.eval_idx) + [self.lqe_layers[self.eval_idx]]
+ )
+
+ def forward(
+ self,
+ target,
+ ref_points_unact,
+ memory,
+ spatial_shapes,
+ bbox_head,
+ score_head,
+ query_pos_head,
+ pre_bbox_head,
+ integral,
+ up,
+ reg_scale,
+ attn_mask=None,
+ memory_mask=None,
+ dn_meta=None,
+ ):
+ output = target
+ output_detach = pred_corners_undetach = 0
+ value = self.value_op(memory, None, None, memory_mask, spatial_shapes)
+
+ dec_out_bboxes = []
+ dec_out_logits = []
+ dec_out_pred_corners = []
+ dec_out_refs = []
+ if not hasattr(self, "project"):
+ project = weighting_function(self.reg_max, up, reg_scale)
+ else:
+ project = self.project
+
+ ref_points_detach = F.sigmoid(ref_points_unact)
+
+ for i, layer in enumerate(self.layers):
+ ref_points_input = ref_points_detach.unsqueeze(2)
+ query_pos_embed = query_pos_head(ref_points_detach).clamp(min=-10, max=10)
+
+ # TODO Adjust scale if needed for detachable wider layers
+ if i >= self.eval_idx + 1 and self.layer_scale > 1:
+ query_pos_embed = F.interpolate(query_pos_embed, scale_factor=self.layer_scale)
+ value = self.value_op(
+ memory, None, query_pos_embed.shape[-1], memory_mask, spatial_shapes
+ )
+ output = F.interpolate(output, size=query_pos_embed.shape[-1])
+ output_detach = output.detach()
+
+ output = layer(
+ output, ref_points_input, value, spatial_shapes, attn_mask, query_pos_embed
+ )
+
+ if i == 0:
+ # Initial bounding box predictions with inverse sigmoid refinement
+ pre_bboxes = F.sigmoid(pre_bbox_head(output) + inverse_sigmoid(ref_points_detach))
+ pre_scores = score_head[0](output)
+ ref_points_initial = pre_bboxes.detach()
+
+ # Refine bounding box corners using FDR, integrating previous layer's corrections
+ pred_corners = bbox_head[i](output + output_detach) + pred_corners_undetach
+ inter_ref_bbox = distance2bbox(
+ ref_points_initial, integral(pred_corners, project), reg_scale
+ )
+
+ if self.training or i == self.eval_idx:
+ scores = score_head[i](output)
+ # Lqe does not affect the performance here.
+ scores = self.lqe_layers[i](scores, pred_corners)
+ dec_out_logits.append(scores)
+ dec_out_bboxes.append(inter_ref_bbox)
+ dec_out_pred_corners.append(pred_corners)
+ dec_out_refs.append(ref_points_initial)
+
+ if not self.training:
+ break
+
+ pred_corners_undetach = pred_corners
+ ref_points_detach = inter_ref_bbox.detach()
+ output_detach = output.detach()
+
+ return (
+ torch.stack(dec_out_bboxes),
+ torch.stack(dec_out_logits),
+ torch.stack(dec_out_pred_corners),
+ torch.stack(dec_out_refs),
+ pre_bboxes,
+ pre_scores,
+ )
+
+
+class DFINETransformer(nn.Module):
+ __share__ = ["num_classes", "eval_spatial_size"]
+
+ def __init__(
+ self,
+ num_classes=80,
+ hidden_dim=256,
+ num_queries=300,
+ feat_channels=[512, 1024, 2048],
+ feat_strides=[8, 16, 32],
+ num_levels=3,
+ num_points=4,
+ nhead=8,
+ num_layers=6,
+ dim_feedforward=1024,
+ dropout=0.0,
+ activation="relu",
+ num_denoising=100,
+ label_noise_ratio=0.5,
+ box_noise_scale=1.0,
+ learn_query_content=False,
+ eval_spatial_size=None,
+ eval_idx=-1,
+ eps=1e-2,
+ aux_loss=True,
+ cross_attn_method="default",
+ query_select_method="default",
+ reg_max=32,
+ reg_scale=4.0,
+ layer_scale=1,
+ ):
+ super().__init__()
+ assert len(feat_channels) <= num_levels
+ assert len(feat_strides) == len(feat_channels)
+
+ for _ in range(num_levels - len(feat_strides)):
+ feat_strides.append(feat_strides[-1] * 2)
+
+ self.hidden_dim = hidden_dim
+ scaled_dim = round(layer_scale * hidden_dim)
+ self.nhead = nhead
+ self.feat_strides = feat_strides
+ self.num_levels = num_levels
+ self.num_classes = num_classes
+ self.num_queries = num_queries
+ self.eps = eps
+ self.num_layers = num_layers
+ self.eval_spatial_size = eval_spatial_size
+ self.aux_loss = aux_loss
+ self.reg_max = reg_max
+
+ assert query_select_method in ("default", "one2many", "agnostic"), ""
+ assert cross_attn_method in ("default", "discrete"), ""
+ self.cross_attn_method = cross_attn_method
+ self.query_select_method = query_select_method
+
+ # backbone feature projection
+ self._build_input_proj_layer(feat_channels)
+
+ # Transformer module
+ self.up = nn.Parameter(torch.tensor([0.5]), requires_grad=False)
+ self.reg_scale = nn.Parameter(torch.tensor([reg_scale]), requires_grad=False)
+ decoder_layer = TransformerDecoderLayer(
+ hidden_dim,
+ nhead,
+ dim_feedforward,
+ dropout,
+ activation,
+ num_levels,
+ num_points,
+ cross_attn_method=cross_attn_method,
+ )
+ decoder_layer_wide = TransformerDecoderLayer(
+ hidden_dim,
+ nhead,
+ dim_feedforward,
+ dropout,
+ activation,
+ num_levels,
+ num_points,
+ cross_attn_method=cross_attn_method,
+ layer_scale=layer_scale,
+ )
+ self.decoder = TransformerDecoder(
+ hidden_dim,
+ decoder_layer,
+ decoder_layer_wide,
+ num_layers,
+ nhead,
+ reg_max,
+ self.reg_scale,
+ self.up,
+ eval_idx,
+ layer_scale,
+ )
+ # denoising
+ self.num_denoising = num_denoising
+ self.label_noise_ratio = label_noise_ratio
+ self.box_noise_scale = box_noise_scale
+ if num_denoising > 0:
+ self.denoising_class_embed = nn.Embedding(
+ num_classes + 1, hidden_dim, padding_idx=num_classes
+ )
+ init.normal_(self.denoising_class_embed.weight[:-1])
+
+ # decoder embedding
+ self.learn_query_content = learn_query_content
+ if learn_query_content:
+ self.tgt_embed = nn.Embedding(num_queries, hidden_dim)
+ self.query_pos_head = MLP(4, 2 * hidden_dim, hidden_dim, 2)
+
+ # if num_select_queries != self.num_queries:
+ # layer = TransformerEncoderLayer(hidden_dim, nhead, dim_feedforward, activation='gelu')
+ # self.encoder = TransformerEncoder(layer, 1)
+
+ self.enc_output = nn.Sequential(
+ OrderedDict(
+ [
+ ("proj", nn.Linear(hidden_dim, hidden_dim)),
+ (
+ "norm",
+ nn.LayerNorm(
+ hidden_dim,
+ ),
+ ),
+ ]
+ )
+ )
+
+ if query_select_method == "agnostic":
+ self.enc_score_head = nn.Linear(hidden_dim, 1)
+ else:
+ self.enc_score_head = nn.Linear(hidden_dim, num_classes)
+
+ self.enc_bbox_head = MLP(hidden_dim, hidden_dim, 4, 3)
+
+ # decoder head
+ self.eval_idx = eval_idx if eval_idx >= 0 else num_layers + eval_idx
+ self.dec_score_head = nn.ModuleList(
+ [nn.Linear(hidden_dim, num_classes) for _ in range(self.eval_idx + 1)]
+ + [nn.Linear(scaled_dim, num_classes) for _ in range(num_layers - self.eval_idx - 1)]
+ )
+ self.pre_bbox_head = MLP(hidden_dim, hidden_dim, 4, 3)
+ self.dec_bbox_head = nn.ModuleList(
+ [
+ MLP(hidden_dim, hidden_dim, 4 * (self.reg_max + 1), 3)
+ for _ in range(self.eval_idx + 1)
+ ]
+ + [
+ MLP(scaled_dim, scaled_dim, 4 * (self.reg_max + 1), 3)
+ for _ in range(num_layers - self.eval_idx - 1)
+ ]
+ )
+ self.integral = Integral(self.reg_max)
+
+ # init encoder output anchors and valid_mask
+ if self.eval_spatial_size:
+ anchors, valid_mask = self._generate_anchors()
+ self.register_buffer("anchors", anchors)
+ self.register_buffer("valid_mask", valid_mask)
+ # init encoder output anchors and valid_mask
+ if self.eval_spatial_size:
+ self.anchors, self.valid_mask = self._generate_anchors()
+
+ self._reset_parameters(feat_channels)
+
+ def convert_to_deploy(self):
+ self.dec_score_head = nn.ModuleList(
+ [nn.Identity()] * (self.eval_idx) + [self.dec_score_head[self.eval_idx]]
+ )
+ self.dec_bbox_head = nn.ModuleList(
+ [
+ self.dec_bbox_head[i] if i <= self.eval_idx else nn.Identity()
+ for i in range(len(self.dec_bbox_head))
+ ]
+ )
+
+ def _reset_parameters(self, feat_channels):
+ bias = bias_init_with_prob(0.01)
+ init.constant_(self.enc_score_head.bias, bias)
+ init.constant_(self.enc_bbox_head.layers[-1].weight, 0)
+ init.constant_(self.enc_bbox_head.layers[-1].bias, 0)
+
+ init.constant_(self.pre_bbox_head.layers[-1].weight, 0)
+ init.constant_(self.pre_bbox_head.layers[-1].bias, 0)
+
+ for cls_, reg_ in zip(self.dec_score_head, self.dec_bbox_head):
+ init.constant_(cls_.bias, bias)
+ if hasattr(reg_, "layers"):
+ init.constant_(reg_.layers[-1].weight, 0)
+ init.constant_(reg_.layers[-1].bias, 0)
+
+ init.xavier_uniform_(self.enc_output[0].weight)
+ if self.learn_query_content:
+ init.xavier_uniform_(self.tgt_embed.weight)
+ init.xavier_uniform_(self.query_pos_head.layers[0].weight)
+ init.xavier_uniform_(self.query_pos_head.layers[1].weight)
+ for m, in_channels in zip(self.input_proj, feat_channels):
+ if in_channels != self.hidden_dim:
+ init.xavier_uniform_(m[0].weight)
+
+ def _build_input_proj_layer(self, feat_channels):
+ self.input_proj = nn.ModuleList()
+ for in_channels in feat_channels:
+ if in_channels == self.hidden_dim:
+ self.input_proj.append(nn.Identity())
+ else:
+ self.input_proj.append(
+ nn.Sequential(
+ OrderedDict(
+ [
+ ("conv", nn.Conv2d(in_channels, self.hidden_dim, 1, bias=False)),
+ (
+ "norm",
+ nn.BatchNorm2d(
+ self.hidden_dim,
+ ),
+ ),
+ ]
+ )
+ )
+ )
+
+ in_channels = feat_channels[-1]
+
+ for _ in range(self.num_levels - len(feat_channels)):
+ if in_channels == self.hidden_dim:
+ self.input_proj.append(nn.Identity())
+ else:
+ self.input_proj.append(
+ nn.Sequential(
+ OrderedDict(
+ [
+ (
+ "conv",
+ nn.Conv2d(
+ in_channels, self.hidden_dim, 3, 2, padding=1, bias=False
+ ),
+ ),
+ ("norm", nn.BatchNorm2d(self.hidden_dim)),
+ ]
+ )
+ )
+ )
+ in_channels = self.hidden_dim
+
+ def _get_encoder_input(self, feats: List[torch.Tensor]):
+ # get projection features
+ proj_feats = [self.input_proj[i](feat) for i, feat in enumerate(feats)]
+ if self.num_levels > len(proj_feats):
+ len_srcs = len(proj_feats)
+ for i in range(len_srcs, self.num_levels):
+ if i == len_srcs:
+ proj_feats.append(self.input_proj[i](feats[-1]))
+ else:
+ proj_feats.append(self.input_proj[i](proj_feats[-1]))
+
+ # get encoder inputs
+ feat_flatten = []
+ spatial_shapes = []
+ for i, feat in enumerate(proj_feats):
+ _, _, h, w = feat.shape
+ # [b, c, h, w] -> [b, h*w, c]
+ feat_flatten.append(feat.flatten(2).permute(0, 2, 1))
+ # [num_levels, 2]
+ spatial_shapes.append([h, w])
+
+ # [b, l, c]
+ feat_flatten = torch.concat(feat_flatten, 1)
+ return feat_flatten, spatial_shapes
+
+ def _generate_anchors(
+ self, spatial_shapes=None, grid_size=0.05, dtype=torch.float32, device="cpu"
+ ):
+ if spatial_shapes is None:
+ spatial_shapes = []
+ eval_h, eval_w = self.eval_spatial_size
+ for s in self.feat_strides:
+ spatial_shapes.append([int(eval_h / s), int(eval_w / s)])
+
+ anchors = []
+ for lvl, (h, w) in enumerate(spatial_shapes):
+ grid_y, grid_x = torch.meshgrid(torch.arange(h), torch.arange(w), indexing="ij")
+ grid_xy = torch.stack([grid_x, grid_y], dim=-1)
+ grid_xy = (grid_xy.unsqueeze(0) + 0.5) / torch.tensor([w, h], dtype=dtype)
+ wh = torch.ones_like(grid_xy) * grid_size * (2.0**lvl)
+ lvl_anchors = torch.concat([grid_xy, wh], dim=-1).reshape(-1, h * w, 4)
+ anchors.append(lvl_anchors)
+
+ anchors = torch.concat(anchors, dim=1).to(device)
+ valid_mask = ((anchors > self.eps) * (anchors < 1 - self.eps)).all(-1, keepdim=True)
+ anchors = torch.log(anchors / (1 - anchors))
+ anchors = torch.where(valid_mask, anchors, torch.inf)
+
+ return anchors, valid_mask
+
+ def _get_decoder_input(
+ self, memory: torch.Tensor, spatial_shapes, denoising_logits=None, denoising_bbox_unact=None
+ ):
+ # prepare input for decoder
+ if self.training or self.eval_spatial_size is None:
+ anchors, valid_mask = self._generate_anchors(spatial_shapes, device=memory.device)
+ else:
+ anchors = self.anchors
+ valid_mask = self.valid_mask
+ if memory.shape[0] > 1:
+ anchors = anchors.repeat(memory.shape[0], 1, 1)
+
+ # memory = torch.where(valid_mask, memory, 0)
+ # TODO fix type error for onnx export
+ memory = valid_mask.to(memory.dtype) * memory
+
+ output_memory: torch.Tensor = self.enc_output(memory)
+ enc_outputs_logits: torch.Tensor = self.enc_score_head(output_memory)
+
+ enc_topk_bboxes_list, enc_topk_logits_list = [], []
+ enc_topk_memory, enc_topk_logits, enc_topk_anchors = self._select_topk(
+ output_memory, enc_outputs_logits, anchors, self.num_queries
+ )
+
+ enc_topk_bbox_unact: torch.Tensor = self.enc_bbox_head(enc_topk_memory) + enc_topk_anchors
+
+ if self.training:
+ enc_topk_bboxes = F.sigmoid(enc_topk_bbox_unact)
+ enc_topk_bboxes_list.append(enc_topk_bboxes)
+ enc_topk_logits_list.append(enc_topk_logits)
+
+ # if self.num_select_queries != self.num_queries:
+ # raise NotImplementedError('')
+
+ if self.learn_query_content:
+ content = self.tgt_embed.weight.unsqueeze(0).tile([memory.shape[0], 1, 1])
+ else:
+ content = enc_topk_memory.detach()
+
+ enc_topk_bbox_unact = enc_topk_bbox_unact.detach()
+
+ if denoising_bbox_unact is not None:
+ enc_topk_bbox_unact = torch.concat([denoising_bbox_unact, enc_topk_bbox_unact], dim=1)
+ content = torch.concat([denoising_logits, content], dim=1)
+
+ return content, enc_topk_bbox_unact, enc_topk_bboxes_list, enc_topk_logits_list
+
+ def _select_topk(
+ self,
+ memory: torch.Tensor,
+ outputs_logits: torch.Tensor,
+ outputs_anchors_unact: torch.Tensor,
+ topk: int,
+ ):
+ if self.query_select_method == "default":
+ # ------ For ONNX Export ------
+ # topk_input = outputs_logits.max(-1).values
+ # topk_input = F.softmax(topk_input, dim=-1)
+ # offset = torch.arange(topk_input.size()[-1]).to(torch.int32)
+ # topk_input = (topk_input * 1000).to(torch.int32) * 10000 + offset
+ # _, topk_ind = torch.topk(topk_input, topk, dim=-1)
+
+ # topk_ind = torch.argsort(outputs_logits.max(-1).values, dim=-1, descending=True)[..., :topk]
+
+ # ------ Original ------
+ _, topk_ind = torch.topk(outputs_logits.max(-1).values, topk, dim=-1)
+
+ elif self.query_select_method == "one2many":
+ _, topk_ind = torch.topk(outputs_logits.flatten(1), topk, dim=-1)
+ topk_ind = topk_ind // self.num_classes
+
+ elif self.query_select_method == "agnostic":
+ _, topk_ind = torch.topk(outputs_logits.squeeze(-1), topk, dim=-1)
+
+ topk_ind: torch.Tensor
+
+ topk_anchors = outputs_anchors_unact.gather(
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, outputs_anchors_unact.shape[-1])
+ )
+
+ topk_logits = (
+ outputs_logits.gather(
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, outputs_logits.shape[-1])
+ )
+ if self.training
+ else None
+ )
+
+ topk_memory = memory.gather(
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, memory.shape[-1])
+ )
+
+ return topk_memory, topk_logits, topk_anchors
+
+ def forward(self, feats, targets=None):
+ # input projection and embedding
+ memory, spatial_shapes = self._get_encoder_input(feats)
+
+ # prepare denoising training
+ if self.training and self.num_denoising > 0:
+ denoising_logits, denoising_bbox_unact, attn_mask, dn_meta = (
+ get_contrastive_denoising_training_group(
+ targets,
+ self.num_classes,
+ self.num_queries,
+ self.denoising_class_embed,
+ num_denoising=self.num_denoising,
+ label_noise_ratio=self.label_noise_ratio,
+ box_noise_scale=1.0,
+ )
+ )
+ else:
+ denoising_logits, denoising_bbox_unact, attn_mask, dn_meta = None, None, None, None
+
+ init_ref_contents, init_ref_points_unact, enc_topk_bboxes_list, enc_topk_logits_list = (
+ self._get_decoder_input(memory, spatial_shapes, denoising_logits, denoising_bbox_unact)
+ )
+
+ # decoder
+ out_bboxes, out_logits, out_corners, out_refs, pre_bboxes, pre_logits = self.decoder(
+ init_ref_contents,
+ init_ref_points_unact,
+ memory,
+ spatial_shapes,
+ self.dec_bbox_head,
+ self.dec_score_head,
+ self.query_pos_head,
+ self.pre_bbox_head,
+ self.integral,
+ self.up,
+ self.reg_scale,
+ attn_mask=attn_mask,
+ dn_meta=dn_meta,
+ )
+
+ if self.training and dn_meta is not None:
+ dn_pre_logits, pre_logits = torch.split(pre_logits, dn_meta["dn_num_split"], dim=1)
+ dn_pre_bboxes, pre_bboxes = torch.split(pre_bboxes, dn_meta["dn_num_split"], dim=1)
+ dn_out_bboxes, out_bboxes = torch.split(out_bboxes, dn_meta["dn_num_split"], dim=2)
+ dn_out_logits, out_logits = torch.split(out_logits, dn_meta["dn_num_split"], dim=2)
+
+ dn_out_corners, out_corners = torch.split(out_corners, dn_meta["dn_num_split"], dim=2)
+ dn_out_refs, out_refs = torch.split(out_refs, dn_meta["dn_num_split"], dim=2)
+
+ if self.training:
+ out = {
+ "pred_logits": out_logits[-1],
+ "pred_boxes": out_bboxes[-1],
+ "pred_corners": out_corners[-1],
+ "ref_points": out_refs[-1],
+ "up": self.up,
+ "reg_scale": self.reg_scale,
+ }
+ else:
+ out = {"pred_logits": out_logits[-1], "pred_boxes": out_bboxes[-1]}
+
+ if self.training and self.aux_loss:
+ out["aux_outputs"] = self._set_aux_loss2(
+ out_logits[:-1],
+ out_bboxes[:-1],
+ out_corners[:-1],
+ out_refs[:-1],
+ out_corners[-1],
+ out_logits[-1],
+ )
+ out["enc_aux_outputs"] = self._set_aux_loss(enc_topk_logits_list, enc_topk_bboxes_list)
+ out["pre_outputs"] = {"pred_logits": pre_logits, "pred_boxes": pre_bboxes}
+ out["enc_meta"] = {"class_agnostic": self.query_select_method == "agnostic"}
+
+ if dn_meta is not None:
+ out["dn_outputs"] = self._set_aux_loss2(
+ dn_out_logits,
+ dn_out_bboxes,
+ dn_out_corners,
+ dn_out_refs,
+ dn_out_corners[-1],
+ dn_out_logits[-1],
+ )
+ out["dn_pre_outputs"] = {"pred_logits": dn_pre_logits, "pred_boxes": dn_pre_bboxes}
+ out["dn_meta"] = dn_meta
+
+ return out
+
+ @torch.jit.unused
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ # this is a workaround to make torchscript happy, as torchscript
+ # doesn't support dictionary with non-homogeneous values, such
+ # as a dict having both a Tensor and a list.
+ return [{"pred_logits": a, "pred_boxes": b} for a, b in zip(outputs_class, outputs_coord)]
+
+ @torch.jit.unused
+ def _set_aux_loss2(
+ self,
+ outputs_class,
+ outputs_coord,
+ outputs_corners,
+ outputs_ref,
+ teacher_corners=None,
+ teacher_logits=None,
+ ):
+ # this is a workaround to make torchscript happy, as torchscript
+ # doesn't support dictionary with non-homogeneous values, such
+ # as a dict having both a Tensor and a list.
+ return [
+ {
+ "pred_logits": a,
+ "pred_boxes": b,
+ "pred_corners": c,
+ "ref_points": d,
+ "teacher_corners": teacher_corners,
+ "teacher_logits": teacher_logits,
+ }
+ for a, b, c, d in zip(outputs_class, outputs_coord, outputs_corners, outputs_ref)
+ ]
diff --git a/services/layout_analyze/dfine_la/model/denoising.py b/services/layout_analyze/dfine_la/model/denoising.py
new file mode 100644
index 0000000..4d2409a
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/denoising.py
@@ -0,0 +1,121 @@
+"""Copyright(c) 2023 lyuwenyu. All Rights Reserved.
+Modifications Copyright (c) 2024 The D-FINE Authors. All Rights Reserved.
+"""
+
+import torch
+
+from .box_ops import box_cxcywh_to_xyxy, box_xyxy_to_cxcywh
+from .utils import inverse_sigmoid
+
+
+def get_contrastive_denoising_training_group(
+ targets,
+ num_classes,
+ num_queries,
+ class_embed,
+ num_denoising=100,
+ label_noise_ratio=0.5,
+ box_noise_scale=1.0,
+):
+ """cnd"""
+ if num_denoising <= 0:
+ return None, None, None, None
+
+ num_gts = [len(t["labels"]) for t in targets]
+ device = targets[0]["labels"].device
+
+ max_gt_num = max(num_gts)
+ if max_gt_num == 0:
+ dn_meta = {"dn_positive_idx": None, "dn_num_group": 0, "dn_num_split": [0, num_queries]}
+ return None, None, None, dn_meta
+
+ num_group = num_denoising // max_gt_num
+ num_group = 1 if num_group == 0 else num_group
+ # pad gt to max_num of a batch
+ bs = len(num_gts)
+
+ input_query_class = torch.full([bs, max_gt_num], num_classes, dtype=torch.int32, device=device)
+ input_query_bbox = torch.zeros([bs, max_gt_num, 4], device=device)
+ pad_gt_mask = torch.zeros([bs, max_gt_num], dtype=torch.bool, device=device)
+
+ for i in range(bs):
+ num_gt = num_gts[i]
+ if num_gt > 0:
+ input_query_class[i, :num_gt] = targets[i]["labels"]
+ input_query_bbox[i, :num_gt] = targets[i]["boxes"]
+ pad_gt_mask[i, :num_gt] = 1
+ # each group has positive and negative queries.
+ input_query_class = input_query_class.tile([1, 2 * num_group])
+ input_query_bbox = input_query_bbox.tile([1, 2 * num_group, 1])
+ pad_gt_mask = pad_gt_mask.tile([1, 2 * num_group])
+ # positive and negative mask
+ negative_gt_mask = torch.zeros([bs, max_gt_num * 2, 1], device=device)
+ negative_gt_mask[:, max_gt_num:] = 1
+ negative_gt_mask = negative_gt_mask.tile([1, num_group, 1])
+ positive_gt_mask = 1 - negative_gt_mask
+ # contrastive denoising training positive index
+ positive_gt_mask = positive_gt_mask.squeeze(-1) * pad_gt_mask
+ dn_positive_idx = torch.nonzero(positive_gt_mask)[:, 1]
+ dn_positive_idx = torch.split(dn_positive_idx, [n * num_group for n in num_gts])
+ # total denoising queries
+ num_denoising = int(max_gt_num * 2 * num_group)
+
+ if label_noise_ratio > 0:
+ mask = torch.rand_like(input_query_class, dtype=torch.float) < (label_noise_ratio * 0.5)
+ # randomly put a new one here
+ new_label = torch.randint_like(mask, 0, num_classes, dtype=input_query_class.dtype)
+ input_query_class = torch.where(mask & pad_gt_mask, new_label, input_query_class)
+
+ if box_noise_scale > 0:
+ known_bbox = box_cxcywh_to_xyxy(input_query_bbox)
+ diff = torch.tile(input_query_bbox[..., 2:] * 0.5, [1, 1, 2]) * box_noise_scale
+ rand_sign = torch.randint_like(input_query_bbox, 0, 2) * 2.0 - 1.0
+ rand_part = torch.rand_like(input_query_bbox)
+ rand_part = (rand_part + 1.0) * negative_gt_mask + rand_part * (1 - negative_gt_mask)
+ # shrink_mask = torch.zeros_like(rand_sign)
+ # shrink_mask[:, :, :2] = (rand_sign[:, :, :2] == 1) # rand_sign == 1 → (x1, y1) ↘ → smaller bbox
+ # shrink_mask[:, :, 2:] = (rand_sign[:, :, 2:] == -1) # rand_sign == -1 → (x2, y2) ↖ → smaller bbox
+ # mask = rand_part > (upper_bound / (upper_bound+1))
+ # # this is to make sure the dn bbox can be reversed to the original bbox by dfine head.
+ # rand_sign = torch.where((shrink_mask * (1 - negative_gt_mask) * mask).bool(), \
+ # rand_sign * upper_bound / (upper_bound+1) / rand_part, rand_sign)
+ known_bbox += rand_sign * rand_part * diff
+ known_bbox = torch.clip(known_bbox, min=0.0, max=1.0)
+ input_query_bbox = box_xyxy_to_cxcywh(known_bbox)
+ input_query_bbox[input_query_bbox < 0] *= -1
+ input_query_bbox_unact = inverse_sigmoid(input_query_bbox)
+
+ input_query_logits = class_embed(input_query_class)
+
+ tgt_size = num_denoising + num_queries
+ attn_mask = torch.full([tgt_size, tgt_size], False, dtype=torch.bool, device=device)
+ # match query cannot see the reconstruction
+ attn_mask[num_denoising:, :num_denoising] = True
+
+ # reconstruct cannot see each other
+ for i in range(num_group):
+ if i == 0:
+ attn_mask[
+ max_gt_num * 2 * i : max_gt_num * 2 * (i + 1),
+ max_gt_num * 2 * (i + 1) : num_denoising,
+ ] = True
+ if i == num_group - 1:
+ attn_mask[max_gt_num * 2 * i : max_gt_num * 2 * (i + 1), : max_gt_num * i * 2] = True
+ else:
+ attn_mask[
+ max_gt_num * 2 * i : max_gt_num * 2 * (i + 1),
+ max_gt_num * 2 * (i + 1) : num_denoising,
+ ] = True
+ attn_mask[max_gt_num * 2 * i : max_gt_num * 2 * (i + 1), : max_gt_num * 2 * i] = True
+
+ dn_meta = {
+ "dn_positive_idx": dn_positive_idx,
+ "dn_num_group": num_group,
+ "dn_num_split": [num_denoising, num_queries],
+ }
+
+ # print(input_query_class.shape) # torch.Size([4, 196, 256])
+ # print(input_query_bbox.shape) # torch.Size([4, 196, 4])
+ # print(attn_mask.shape) # torch.Size([496, 496])
+
+ return input_query_logits, input_query_bbox_unact, attn_mask, dn_meta
diff --git a/services/layout_analyze/dfine_la/model/dfine_utils.py b/services/layout_analyze/dfine_la/model/dfine_utils.py
new file mode 100644
index 0000000..512d161
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/dfine_utils.py
@@ -0,0 +1,169 @@
+"""
+Copyright (c) 2024 The D-FINE Authors. All Rights Reserved.
+"""
+
+import torch
+
+from .box_ops import box_xyxy_to_cxcywh
+
+
+def weighting_function(reg_max, up, reg_scale, deploy=False):
+ """
+ Generates the non-uniform Weighting Function W(n) for bounding box regression.
+
+ Args:
+ reg_max (int): Max number of the discrete bins.
+ up (Tensor): Controls upper bounds of the sequence,
+ where maximum offset is ±up * H / W.
+ reg_scale (float): Controls the curvature of the Weighting Function.
+ Larger values result in flatter weights near the central axis W(reg_max/2)=0
+ and steeper weights at both ends.
+ deploy (bool): If True, uses deployment mode settings.
+
+ Returns:
+ Tensor: Sequence of Weighting Function.
+ """
+ if deploy:
+ upper_bound1 = (abs(up[0]) * abs(reg_scale)).item()
+ upper_bound2 = (abs(up[0]) * abs(reg_scale) * 2).item()
+ step = (upper_bound1 + 1) ** (2 / (reg_max - 2))
+ left_values = [-((step) ** i) + 1 for i in range(reg_max // 2 - 1, 0, -1)]
+ right_values = [(step) ** i - 1 for i in range(1, reg_max // 2)]
+ values = (
+ [-upper_bound2]
+ + left_values
+ + [torch.zeros_like(up[0][None])]
+ + right_values
+ + [upper_bound2]
+ )
+ return torch.tensor(values, dtype=up.dtype, device=up.device)
+ else:
+ upper_bound1 = abs(up[0]) * abs(reg_scale)
+ upper_bound2 = abs(up[0]) * abs(reg_scale) * 2
+ step = (upper_bound1 + 1) ** (2 / (reg_max - 2))
+ left_values = [-((step) ** i) + 1 for i in range(reg_max // 2 - 1, 0, -1)]
+ right_values = [(step) ** i - 1 for i in range(1, reg_max // 2)]
+ values = (
+ [-upper_bound2]
+ + left_values
+ + [torch.zeros_like(up[0][None])]
+ + right_values
+ + [upper_bound2]
+ )
+ return torch.cat(values, 0)
+
+
+def translate_gt(gt, reg_max, reg_scale, up):
+ """
+ Decodes bounding box ground truth (GT) values into distribution-based GT representations.
+
+ This function maps continuous GT values into discrete distribution bins, which can be used
+ for regression tasks in object detection models. It calculates the indices of the closest
+ bins to each GT value and assigns interpolation weights to these bins based on their proximity
+ to the GT value.
+
+ Args:
+ gt (Tensor): Ground truth bounding box values, shape (N, ).
+ reg_max (int): Maximum number of discrete bins for the distribution.
+ reg_scale (float): Controls the curvature of the Weighting Function.
+ up (Tensor): Controls the upper bounds of the Weighting Function.
+
+ Returns:
+ Tuple[Tensor, Tensor, Tensor]:
+ - indices (Tensor): Index of the left bin closest to each GT value, shape (N, ).
+ - weight_right (Tensor): Weight assigned to the right bin, shape (N, ).
+ - weight_left (Tensor): Weight assigned to the left bin, shape (N, ).
+ """
+ gt = gt.reshape(-1)
+ function_values = weighting_function(reg_max, up, reg_scale)
+
+ # Find the closest left-side indices for each value
+ diffs = function_values.unsqueeze(0) - gt.unsqueeze(1)
+ mask = diffs <= 0
+ closest_left_indices = torch.sum(mask, dim=1) - 1
+
+ # Calculate the weights for the interpolation
+ indices = closest_left_indices.float()
+
+ weight_right = torch.zeros_like(indices)
+ weight_left = torch.zeros_like(indices)
+
+ valid_idx_mask = (indices >= 0) & (indices < reg_max)
+ valid_indices = indices[valid_idx_mask].long()
+
+ # Obtain distances
+ left_values = function_values[valid_indices]
+ right_values = function_values[valid_indices + 1]
+
+ left_diffs = torch.abs(gt[valid_idx_mask] - left_values)
+ right_diffs = torch.abs(right_values - gt[valid_idx_mask])
+
+ # Valid weights
+ weight_right[valid_idx_mask] = left_diffs / (left_diffs + right_diffs)
+ weight_left[valid_idx_mask] = 1.0 - weight_right[valid_idx_mask]
+
+ # Invalid weights (out of range)
+ invalid_idx_mask_neg = indices < 0
+ weight_right[invalid_idx_mask_neg] = 0.0
+ weight_left[invalid_idx_mask_neg] = 1.0
+ indices[invalid_idx_mask_neg] = 0.0
+
+ invalid_idx_mask_pos = indices >= reg_max
+ weight_right[invalid_idx_mask_pos] = 1.0
+ weight_left[invalid_idx_mask_pos] = 0.0
+ indices[invalid_idx_mask_pos] = reg_max - 0.1
+
+ return indices, weight_right, weight_left
+
+
+def distance2bbox(points, distance, reg_scale):
+ """
+ Decodes edge-distances into bounding box coordinates.
+
+ Args:
+ points (Tensor): (B, N, 4) or (N, 4) format, representing [x, y, w, h],
+ where (x, y) is the center and (w, h) are width and height.
+ distance (Tensor): (B, N, 4) or (N, 4), representing distances from the
+ point to the left, top, right, and bottom boundaries.
+
+ reg_scale (float): Controls the curvature of the Weighting Function.
+
+ Returns:
+ Tensor: Bounding boxes in (N, 4) or (B, N, 4) format [cx, cy, w, h].
+ """
+ reg_scale = abs(reg_scale)
+ x1 = points[..., 0] - (0.5 * reg_scale + distance[..., 0]) * (points[..., 2] / reg_scale)
+ y1 = points[..., 1] - (0.5 * reg_scale + distance[..., 1]) * (points[..., 3] / reg_scale)
+ x2 = points[..., 0] + (0.5 * reg_scale + distance[..., 2]) * (points[..., 2] / reg_scale)
+ y2 = points[..., 1] + (0.5 * reg_scale + distance[..., 3]) * (points[..., 3] / reg_scale)
+
+ bboxes = torch.stack([x1, y1, x2, y2], -1)
+
+ return box_xyxy_to_cxcywh(bboxes)
+
+
+def bbox2distance(points, bbox, reg_max, reg_scale, up, eps=0.1):
+ """
+ Converts bounding box coordinates to distances from a reference point.
+
+ Args:
+ points (Tensor): (n, 4) [x, y, w, h], where (x, y) is the center.
+ bbox (Tensor): (n, 4) bounding boxes in "xyxy" format.
+ reg_max (float): Maximum bin value.
+ reg_scale (float): Controling curvarture of W(n).
+ up (Tensor): Controling upper bounds of W(n).
+ eps (float): Small value to ensure target < reg_max.
+
+ Returns:
+ Tensor: Decoded distances.
+ """
+ reg_scale = abs(reg_scale)
+ left = (points[:, 0] - bbox[:, 0]) / (points[..., 2] / reg_scale + 1e-16) - 0.5 * reg_scale
+ top = (points[:, 1] - bbox[:, 1]) / (points[..., 3] / reg_scale + 1e-16) - 0.5 * reg_scale
+ right = (bbox[:, 2] - points[:, 0]) / (points[..., 2] / reg_scale + 1e-16) - 0.5 * reg_scale
+ bottom = (bbox[:, 3] - points[:, 1]) / (points[..., 3] / reg_scale + 1e-16) - 0.5 * reg_scale
+ four_lens = torch.stack([left, top, right, bottom], -1)
+ four_lens, weight_right, weight_left = translate_gt(four_lens, reg_max, reg_scale, up)
+ if reg_max is not None:
+ four_lens = four_lens.clamp(min=0, max=reg_max - eps)
+ return four_lens.reshape(-1).detach(), weight_right.detach(), weight_left.detach()
diff --git a/services/layout_analyze/dfine_la/model/encoder.py b/services/layout_analyze/dfine_la/model/encoder.py
new file mode 100644
index 0000000..4785605
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/encoder.py
@@ -0,0 +1,484 @@
+import copy
+from collections import OrderedDict
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from .utils import get_activation
+
+__all__ = ["HybridEncoder"]
+
+
+class ConvNormLayer_fuse(nn.Module):
+ def __init__(self, ch_in, ch_out, kernel_size, stride, g=1, padding=None, bias=False, act=None):
+ super().__init__()
+ padding = (kernel_size - 1) // 2 if padding is None else padding
+ self.conv = nn.Conv2d(
+ ch_in, ch_out, kernel_size, stride, groups=g, padding=padding, bias=bias
+ )
+ self.norm = nn.BatchNorm2d(ch_out)
+ self.act = nn.Identity() if act is None else get_activation(act)
+ self.ch_in, self.ch_out, self.kernel_size, self.stride, self.g, self.padding, self.bias = (
+ ch_in,
+ ch_out,
+ kernel_size,
+ stride,
+ g,
+ padding,
+ bias,
+ )
+
+ def forward(self, x):
+ if hasattr(self, "conv_bn_fused"):
+ y = self.conv_bn_fused(x)
+ else:
+ y = self.norm(self.conv(x))
+ return self.act(y)
+
+ def convert_to_deploy(self):
+ if not hasattr(self, "conv_bn_fused"):
+ self.conv_bn_fused = nn.Conv2d(
+ self.ch_in,
+ self.ch_out,
+ self.kernel_size,
+ self.stride,
+ groups=self.g,
+ padding=self.padding,
+ bias=True,
+ )
+
+ kernel, bias = self.get_equivalent_kernel_bias()
+ self.conv_bn_fused.weight.data = kernel
+ self.conv_bn_fused.bias.data = bias
+ self.__delattr__("conv")
+ self.__delattr__("norm")
+
+ def get_equivalent_kernel_bias(self):
+ kernel3x3, bias3x3 = self._fuse_bn_tensor()
+
+ return kernel3x3, bias3x3
+
+ def _fuse_bn_tensor(self):
+ kernel = self.conv.weight
+ running_mean = self.norm.running_mean
+ running_var = self.norm.running_var
+ gamma = self.norm.weight
+ beta = self.norm.bias
+ eps = self.norm.eps
+ std = (running_var + eps).sqrt()
+ t = (gamma / std).reshape(-1, 1, 1, 1)
+ return kernel * t, beta - running_mean * gamma / std
+
+
+class ConvNormLayer(nn.Module):
+ def __init__(self, ch_in, ch_out, kernel_size, stride, g=1, padding=None, bias=False, act=None):
+ super().__init__()
+ padding = (kernel_size - 1) // 2 if padding is None else padding
+ self.conv = nn.Conv2d(
+ ch_in, ch_out, kernel_size, stride, groups=g, padding=padding, bias=bias
+ )
+ self.norm = nn.BatchNorm2d(ch_out)
+ self.act = nn.Identity() if act is None else get_activation(act)
+
+ def forward(self, x):
+ return self.act(self.norm(self.conv(x)))
+
+
+class SCDown(nn.Module):
+ def __init__(self, c1, c2, k, s):
+ super().__init__()
+ self.cv1 = ConvNormLayer_fuse(c1, c2, 1, 1)
+ self.cv2 = ConvNormLayer_fuse(c2, c2, k, s, c2)
+
+ def forward(self, x):
+ return self.cv2(self.cv1(x))
+
+
+class VGGBlock(nn.Module):
+ def __init__(self, ch_in, ch_out, act="relu"):
+ super().__init__()
+ self.ch_in = ch_in
+ self.ch_out = ch_out
+ self.conv1 = ConvNormLayer(ch_in, ch_out, 3, 1, padding=1, act=None)
+ self.conv2 = ConvNormLayer(ch_in, ch_out, 1, 1, padding=0, act=None)
+ self.act = nn.Identity() if act is None else act
+
+ def forward(self, x):
+ if hasattr(self, "conv"):
+ y = self.conv(x)
+ else:
+ y = self.conv1(x) + self.conv2(x)
+
+ return self.act(y)
+
+ def convert_to_deploy(self):
+ if not hasattr(self, "conv"):
+ self.conv = nn.Conv2d(self.ch_in, self.ch_out, 3, 1, padding=1)
+
+ kernel, bias = self.get_equivalent_kernel_bias()
+ self.conv.weight.data = kernel
+ self.conv.bias.data = bias
+ self.__delattr__("conv1")
+ self.__delattr__("conv2")
+
+ def get_equivalent_kernel_bias(self):
+ kernel3x3, bias3x3 = self._fuse_bn_tensor(self.conv1)
+ kernel1x1, bias1x1 = self._fuse_bn_tensor(self.conv2)
+
+ return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1), bias3x3 + bias1x1
+
+ def _pad_1x1_to_3x3_tensor(self, kernel1x1):
+ if kernel1x1 is None:
+ return 0
+ else:
+ return F.pad(kernel1x1, [1, 1, 1, 1])
+
+ def _fuse_bn_tensor(self, branch: ConvNormLayer):
+ if branch is None:
+ return 0, 0
+ kernel = branch.conv.weight
+ running_mean = branch.norm.running_mean
+ running_var = branch.norm.running_var
+ gamma = branch.norm.weight
+ beta = branch.norm.bias
+ eps = branch.norm.eps
+ std = (running_var + eps).sqrt()
+ t = (gamma / std).reshape(-1, 1, 1, 1)
+ return kernel * t, beta - running_mean * gamma / std
+
+
+class ELAN(nn.Module):
+ # csp-elan
+ def __init__(self, c1, c2, c3, c4, n=2, bias=False, act="silu", bottletype=VGGBlock):
+ super().__init__()
+ self.c = c3
+ self.cv1 = ConvNormLayer_fuse(c1, c3, 1, 1, bias=bias, act=act)
+ self.cv2 = nn.Sequential(
+ bottletype(c3 // 2, c4, act=get_activation(act)),
+ ConvNormLayer_fuse(c4, c4, 3, 1, bias=bias, act=act),
+ )
+ self.cv3 = nn.Sequential(
+ bottletype(c4, c4, act=get_activation(act)),
+ ConvNormLayer_fuse(c4, c4, 3, 1, bias=bias, act=act),
+ )
+ self.cv4 = ConvNormLayer_fuse(c3 + (2 * c4), c2, 1, 1, bias=bias, act=act)
+
+ def forward(self, x):
+ # y = [self.cv1(x)]
+ y = list(self.cv1(x).chunk(2, 1))
+ y.append(self.cv2(y[-1]))
+ y.append(self.cv3(y[-1]))
+ return self.cv4(torch.cat(y, 1))
+
+
+class RepNCSPELAN4(nn.Module):
+ # csp-elan
+ def __init__(self, c1, c2, c3, c4, n=3, bias=False, act="silu"):
+ super().__init__()
+ self.c = c3 // 2
+ self.cv1 = ConvNormLayer_fuse(c1, c3, 1, 1, bias=bias, act=act)
+ self.cv2 = nn.Sequential(
+ CSPLayer(c3 // 2, c4, n, 1, bias=bias, act=act, bottletype=VGGBlock),
+ ConvNormLayer_fuse(c4, c4, 3, 1, bias=bias, act=act),
+ )
+ self.cv3 = nn.Sequential(
+ CSPLayer(c4, c4, n, 1, bias=bias, act=act, bottletype=VGGBlock),
+ ConvNormLayer_fuse(c4, c4, 3, 1, bias=bias, act=act),
+ )
+ self.cv4 = ConvNormLayer_fuse(c3 + (2 * c4), c2, 1, 1, bias=bias, act=act)
+
+ def forward_chunk(self, x):
+ y = list(self.cv1(x).chunk(2, 1))
+ y.append(self.cv2(y[-1]))
+ y.append(self.cv3(y[-1]))
+ return self.cv4(torch.cat(y, 1))
+
+ def forward(self, x):
+ y = list(self.cv1(x).split((self.c, self.c), 1))
+ y.append(self.cv2(y[-1]))
+ y.append(self.cv3(y[-1]))
+ return self.cv4(torch.cat(y, 1))
+
+
+class CSPLayer(nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ num_blocks=3,
+ expansion=1.0,
+ bias=False,
+ act="silu",
+ bottletype=VGGBlock,
+ ):
+ super(CSPLayer, self).__init__()
+ hidden_channels = int(out_channels * expansion)
+ self.conv1 = ConvNormLayer_fuse(in_channels, hidden_channels, 1, 1, bias=bias, act=act)
+ self.conv2 = ConvNormLayer_fuse(in_channels, hidden_channels, 1, 1, bias=bias, act=act)
+ self.bottlenecks = nn.Sequential(
+ *[
+ bottletype(hidden_channels, hidden_channels, act=get_activation(act))
+ for _ in range(num_blocks)
+ ]
+ )
+ if hidden_channels != out_channels:
+ self.conv3 = ConvNormLayer_fuse(hidden_channels, out_channels, 1, 1, bias=bias, act=act)
+ else:
+ self.conv3 = nn.Identity()
+
+ def forward(self, x):
+ x_1 = self.conv1(x)
+ x_1 = self.bottlenecks(x_1)
+ x_2 = self.conv2(x)
+ return self.conv3(x_1 + x_2)
+
+
+# transformer
+class TransformerEncoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model,
+ nhead,
+ dim_feedforward=2048,
+ dropout=0.1,
+ activation="relu",
+ normalize_before=False,
+ ):
+ super().__init__()
+ self.normalize_before = normalize_before
+
+ self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout, batch_first=True)
+
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
+ self.dropout = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
+
+ self.norm1 = nn.LayerNorm(d_model)
+ self.norm2 = nn.LayerNorm(d_model)
+ self.dropout1 = nn.Dropout(dropout)
+ self.dropout2 = nn.Dropout(dropout)
+ self.activation = get_activation(activation)
+
+ @staticmethod
+ def with_pos_embed(tensor, pos_embed):
+ return tensor if pos_embed is None else tensor + pos_embed
+
+ def forward(self, src, src_mask=None, pos_embed=None) -> torch.Tensor:
+ residual = src
+ if self.normalize_before:
+ src = self.norm1(src)
+ q = k = self.with_pos_embed(src, pos_embed)
+ src, _ = self.self_attn(q, k, value=src, attn_mask=src_mask)
+
+ src = residual + self.dropout1(src)
+ if not self.normalize_before:
+ src = self.norm1(src)
+
+ residual = src
+ if self.normalize_before:
+ src = self.norm2(src)
+ src = self.linear2(self.dropout(self.activation(self.linear1(src))))
+ src = residual + self.dropout2(src)
+ if not self.normalize_before:
+ src = self.norm2(src)
+ return src
+
+
+class TransformerEncoder(nn.Module):
+ def __init__(self, encoder_layer, num_layers, norm=None):
+ super(TransformerEncoder, self).__init__()
+ self.layers = nn.ModuleList([copy.deepcopy(encoder_layer) for _ in range(num_layers)])
+ self.num_layers = num_layers
+ self.norm = norm
+
+ def forward(self, src, src_mask=None, pos_embed=None) -> torch.Tensor:
+ output = src
+ for layer in self.layers:
+ output = layer(output, src_mask=src_mask, pos_embed=pos_embed)
+
+ if self.norm is not None:
+ output = self.norm(output)
+
+ return output
+
+
+class HybridEncoder(nn.Module):
+ __share__ = [
+ "eval_spatial_size",
+ ]
+
+ def __init__(
+ self,
+ in_channels=[512, 1024, 2048],
+ feat_strides=[8, 16, 32],
+ hidden_dim=256,
+ nhead=8,
+ dim_feedforward=1024,
+ dropout=0.0,
+ enc_act="gelu",
+ use_encoder_idx=[2],
+ num_encoder_layers=1,
+ pe_temperature=10000,
+ expansion=1.0,
+ depth_mult=1.0,
+ act="silu",
+ eval_spatial_size=None,
+ ):
+ super().__init__()
+ self.in_channels = in_channels
+ self.feat_strides = feat_strides
+ self.hidden_dim = hidden_dim
+ self.use_encoder_idx = use_encoder_idx
+ self.num_encoder_layers = num_encoder_layers
+ self.pe_temperature = pe_temperature
+ self.eval_spatial_size = eval_spatial_size
+ self.out_channels = [hidden_dim for _ in range(len(in_channels))]
+ self.out_strides = feat_strides
+
+ # channel projection
+ self.input_proj = nn.ModuleList()
+ for in_channel in in_channels:
+ proj = nn.Sequential(
+ OrderedDict(
+ [
+ ("conv", nn.Conv2d(in_channel, hidden_dim, kernel_size=1, bias=False)),
+ ("norm", nn.BatchNorm2d(hidden_dim)),
+ ]
+ )
+ )
+
+ self.input_proj.append(proj)
+
+ # encoder transformer
+ encoder_layer = TransformerEncoderLayer(
+ hidden_dim,
+ nhead=nhead,
+ dim_feedforward=dim_feedforward,
+ dropout=dropout,
+ activation=enc_act,
+ )
+
+ self.encoder = nn.ModuleList(
+ [
+ TransformerEncoder(copy.deepcopy(encoder_layer), num_encoder_layers)
+ for _ in range(len(use_encoder_idx))
+ ]
+ )
+
+ # top-down fpn
+ self.lateral_convs = nn.ModuleList()
+ self.fpn_blocks = nn.ModuleList()
+ for _ in range(len(in_channels) - 1, 0, -1):
+ self.lateral_convs.append(ConvNormLayer_fuse(hidden_dim, hidden_dim, 1, 1))
+ self.fpn_blocks.append(
+ RepNCSPELAN4(
+ hidden_dim * 2,
+ hidden_dim,
+ hidden_dim * 2,
+ round(expansion * hidden_dim // 2),
+ round(3 * depth_mult),
+ )
+ # CSPLayer(hidden_dim * 2, hidden_dim, round(3 * depth_mult), act=act, expansion=expansion, bottletype=VGGBlock)
+ )
+
+ # bottom-up pan
+ self.downsample_convs = nn.ModuleList()
+ self.pan_blocks = nn.ModuleList()
+ for _ in range(len(in_channels) - 1):
+ self.downsample_convs.append(
+ nn.Sequential(
+ SCDown(hidden_dim, hidden_dim, 3, 2),
+ )
+ )
+ self.pan_blocks.append(
+ RepNCSPELAN4(
+ hidden_dim * 2,
+ hidden_dim,
+ hidden_dim * 2,
+ round(expansion * hidden_dim // 2),
+ round(3 * depth_mult),
+ )
+ # CSPLayer(hidden_dim * 2, hidden_dim, round(3 * depth_mult), act=act, expansion=expansion, bottletype=VGGBlock)
+ )
+
+ self._reset_parameters()
+
+ def _reset_parameters(self):
+ if self.eval_spatial_size:
+ for idx in self.use_encoder_idx:
+ stride = self.feat_strides[idx]
+ pos_embed = self.build_2d_sincos_position_embedding(
+ self.eval_spatial_size[1] // stride,
+ self.eval_spatial_size[0] // stride,
+ self.hidden_dim,
+ self.pe_temperature,
+ )
+ self.register_buffer(
+ f"pos_embed{idx}",
+ pos_embed,
+ persistent=False,
+ )
+
+ @staticmethod
+ def build_2d_sincos_position_embedding(w, h, embed_dim=256, temperature=10000.0):
+ """ """
+ grid_w = torch.arange(int(w), dtype=torch.float32)
+ grid_h = torch.arange(int(h), dtype=torch.float32)
+ grid_w, grid_h = torch.meshgrid(grid_w, grid_h, indexing="ij")
+ assert (
+ embed_dim % 4 == 0
+ ), "Embed dimension must be divisible by 4 for 2D sin-cos position embedding"
+ pos_dim = embed_dim // 4
+ omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim
+ omega = 1.0 / (temperature**omega)
+
+ out_w = grid_w.flatten()[..., None] @ omega[None]
+ out_h = grid_h.flatten()[..., None] @ omega[None]
+
+ return torch.concat([out_w.sin(), out_w.cos(), out_h.sin(), out_h.cos()], dim=1)[None, :, :]
+
+ def forward(self, feats):
+ assert len(feats) == len(self.in_channels)
+ proj_feats = [self.input_proj[i](feat) for i, feat in enumerate(feats)]
+
+ # encoder
+ if self.num_encoder_layers > 0:
+ for i, enc_ind in enumerate(self.use_encoder_idx):
+ h, w = proj_feats[enc_ind].shape[2:]
+ # flatten [B, C, H, W] to [B, HxW, C]
+ src_flatten = proj_feats[enc_ind].flatten(2).permute(0, 2, 1)
+ if self.training or self.eval_spatial_size is None:
+ pos_embed = self.build_2d_sincos_position_embedding(
+ w, h, self.hidden_dim, self.pe_temperature
+ ).to(src_flatten.device)
+ else:
+ pos_embed = getattr(self, f"pos_embed{enc_ind}", None).to(src_flatten.device)
+
+ memory: torch.Tensor = self.encoder[i](src_flatten, pos_embed=pos_embed)
+ proj_feats[enc_ind] = (
+ memory.permute(0, 2, 1).reshape(-1, self.hidden_dim, h, w).contiguous()
+ )
+
+ # broadcasting and fusion
+ inner_outs = [proj_feats[-1]]
+ for idx in range(len(self.in_channels) - 1, 0, -1):
+ feat_heigh = inner_outs[0]
+ feat_low = proj_feats[idx - 1]
+ feat_heigh = self.lateral_convs[len(self.in_channels) - 1 - idx](feat_heigh)
+ inner_outs[0] = feat_heigh
+ upsample_feat = F.interpolate(feat_heigh, scale_factor=2.0, mode="nearest")
+ inner_out = self.fpn_blocks[len(self.in_channels) - 1 - idx](
+ torch.concat([upsample_feat, feat_low], dim=1)
+ )
+ inner_outs.insert(0, inner_out)
+
+ outs = [inner_outs[0]]
+ for idx in range(len(self.in_channels) - 1):
+ feat_low = outs[-1]
+ feat_height = inner_outs[idx + 1]
+ downsample_feat = self.downsample_convs[idx](feat_low)
+ out = self.pan_blocks[idx](torch.concat([downsample_feat, feat_height], dim=1))
+ outs.append(out)
+
+ return outs
diff --git a/services/layout_analyze/dfine_la/model/model.py b/services/layout_analyze/dfine_la/model/model.py
new file mode 100644
index 0000000..38e350c
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/model.py
@@ -0,0 +1,125 @@
+"""Fixed D-FINE Stage-2 B2 architecture used by the public LA service."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import torch
+import torch.nn as nn
+
+from .backbone import HGNetv2
+from .decoder import DFINETransformer
+from .encoder import HybridEncoder
+from .postprocessor import DFINEPostProcessor
+
+
+class DFINE(nn.Module):
+ """D-FINE Stage-2 B2 model for 960px layout analysis."""
+
+ def __init__(self, num_classes: int = 12, eval_spatial_size=(960, 960)):
+ super().__init__()
+ self.backbone = HGNetv2(
+ name="B2",
+ use_lab=True,
+ return_idx=[1, 2, 3],
+ freeze_at=3,
+ freeze_stem_only=False,
+ freeze_norm=True,
+ pretrained=False,
+ )
+ self.encoder = HybridEncoder(
+ in_channels=[384, 768, 1536],
+ feat_strides=[8, 16, 32],
+ hidden_dim=256,
+ use_encoder_idx=[2],
+ num_encoder_layers=1,
+ nhead=8,
+ dim_feedforward=1024,
+ dropout=0.0,
+ enc_act="gelu",
+ expansion=1.0,
+ depth_mult=0.67,
+ act="silu",
+ eval_spatial_size=eval_spatial_size,
+ )
+ self.decoder = DFINETransformer(
+ num_classes=num_classes,
+ eval_spatial_size=eval_spatial_size,
+ feat_channels=[256, 256, 256],
+ feat_strides=[8, 16, 32],
+ hidden_dim=256,
+ num_levels=3,
+ num_layers=4,
+ eval_idx=-1,
+ num_queries=300,
+ num_denoising=100,
+ label_noise_ratio=0.5,
+ box_noise_scale=1.0,
+ reg_max=32,
+ reg_scale=4,
+ layer_scale=1,
+ num_points=[3, 6, 3],
+ cross_attn_method="default",
+ query_select_method="default",
+ )
+
+ def forward(self, images, targets=None):
+ features = self.backbone(images)
+ features = self.encoder(features)
+ return self.decoder(features, targets)
+
+ def deploy(self):
+ self.eval()
+ for module in self.modules():
+ if hasattr(module, "convert_to_deploy"):
+ module.convert_to_deploy()
+ return self
+
+
+class DfineWithPostProcessor(nn.Module):
+ """Run model and postprocessor under the official FP16 AMP boundary."""
+
+ def __init__(self, model, postprocessor, device: torch.device) -> None:
+ super().__init__()
+ self.model = model.deploy()
+ self.postprocessor = postprocessor.deploy()
+ self.device = device
+
+ def forward(self, images, original_sizes):
+ with torch.autocast(
+ device_type=images.device.type,
+ dtype=torch.float16,
+ enabled=images.is_cuda,
+ ):
+ outputs = self.model(images)
+ return self.postprocessor(outputs, original_sizes)
+
+
+def load_model(
+ checkpoint_path: str | Path,
+ device: torch.device,
+ num_classes: int = 12,
+ image_size: int = 960,
+) -> DfineWithPostProcessor:
+ """Load a standard, unencrypted Stage-2 B2 checkpoint."""
+ model = DFINE(
+ num_classes=num_classes,
+ eval_spatial_size=(image_size, image_size),
+ )
+ checkpoint = torch.load(
+ str(checkpoint_path),
+ map_location="cpu",
+ weights_only=True,
+ )
+ state = checkpoint["ema"]["module"] if "ema" in checkpoint else checkpoint["model"]
+ model.load_state_dict(state)
+
+ postprocessor = DFINEPostProcessor(
+ num_classes=num_classes,
+ num_top_queries=300,
+ letterbox=True,
+ clip_boxes=True,
+ target_size=image_size,
+ )
+ wrapped = DfineWithPostProcessor(model, postprocessor, device)
+ return wrapped.eval().to(device)
diff --git a/services/layout_analyze/dfine_la/model/postprocessor.py b/services/layout_analyze/dfine_la/model/postprocessor.py
new file mode 100644
index 0000000..af46d1f
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/postprocessor.py
@@ -0,0 +1,152 @@
+"""
+Copied from RT-DETR (https://github.com/lyuwenyu/RT-DETR)
+Copyright(c) 2023 lyuwenyu. All Rights Reserved.
+"""
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torchvision
+
+
+__all__ = ["DFINEPostProcessor"]
+
+
+def mod(a, b):
+ out = a - a // b * b
+ return out
+
+
+def postprocess_boxes(bbox_pred, orig_target_sizes, target_size=960, letterbox=False):
+ if orig_target_sizes.dim() == 1:
+ orig_target_sizes = orig_target_sizes.unsqueeze(0)
+ orig_target_sizes = orig_target_sizes.to(bbox_pred.dtype)
+
+ if not letterbox:
+ scale_x = (orig_target_sizes[:, 0] / target_size).view(-1, 1)
+ scale_y = (orig_target_sizes[:, 1] / target_size).view(-1, 1)
+ bbox_pred[..., 0] = bbox_pred[..., 0] * scale_x
+ bbox_pred[..., 2] = bbox_pred[..., 2] * scale_x
+ bbox_pred[..., 1] = bbox_pred[..., 1] * scale_y
+ bbox_pred[..., 3] = bbox_pred[..., 3] * scale_y
+ return bbox_pred
+
+ orig_w = orig_target_sizes[:, 0]
+ orig_h = orig_target_sizes[:, 1]
+ max_dim = torch.maximum(orig_w, orig_h)
+ scale = target_size / max_dim
+ new_w = (orig_w * scale).floor()
+ new_h = (orig_h * scale).floor()
+ pad_left = ((target_size - new_w) // 2).view(-1, 1)
+ pad_top = ((target_size - new_h) // 2).view(-1, 1)
+ scale = scale.view(-1, 1)
+
+ bbox_pred[..., 0] = (bbox_pred[..., 0] - pad_left) / scale
+ bbox_pred[..., 2] = (bbox_pred[..., 2] - pad_left) / scale
+ bbox_pred[..., 1] = (bbox_pred[..., 1] - pad_top) / scale
+ bbox_pred[..., 3] = (bbox_pred[..., 3] - pad_top) / scale
+ return bbox_pred
+
+
+class DFINEPostProcessor(nn.Module):
+ __share__ = [
+ "num_classes",
+ "use_focal_loss",
+ "num_top_queries",
+ "remap_mscoco_category",
+ "letterbox",
+ ]
+
+ def __init__(
+ self,
+ num_classes=80,
+ use_focal_loss=True,
+ num_top_queries=300,
+ remap_mscoco_category=False,
+ letterbox=False,
+ clip_boxes=False,
+ target_size=960,
+ ) -> None:
+ super().__init__()
+ self.use_focal_loss = use_focal_loss
+ self.num_top_queries = num_top_queries
+ self.num_classes = int(num_classes)
+ self.remap_mscoco_category = remap_mscoco_category
+ self.letterbox = letterbox
+ self.clip_boxes = clip_boxes
+ self.target_size = int(target_size)
+ self.deploy_mode = False
+
+ def extra_repr(self) -> str:
+ return (
+ f"use_focal_loss={self.use_focal_loss}, num_classes={self.num_classes}, "
+ f"num_top_queries={self.num_top_queries}, letterbox={self.letterbox}, "
+ f"clip_boxes={self.clip_boxes}, target_size={self.target_size}"
+ )
+
+ # def forward(self, outputs, orig_target_sizes):
+ def forward(self, outputs, orig_target_sizes: torch.Tensor):
+ logits, boxes = outputs["pred_logits"], outputs["pred_boxes"]
+ bbox_pred = torchvision.ops.box_convert(boxes, in_fmt="cxcywh", out_fmt="xyxy")
+ # Both axes use the same square canvas size. Avoid constructing a CUDA
+ # tensor during forward: host-to-device tensor creation invalidates a
+ # CUDA Graph stream capture on newer CUDA runtimes.
+ bbox_pred = bbox_pred * self.target_size
+
+ if self.use_focal_loss:
+ # ------ For ONNX Export ------
+ # scores = F.sigmoid(logits).flatten(1)
+ # topk_input = F.softmax(logits.flatten(1), dim=-1)
+ # offset = torch.arange(topk_input.size()[-1]).to(torch.int32)
+ # topk_input = (topk_input * 1000).to(torch.int32) * 10000 + offset
+ # _, index = torch.topk(topk_input, self.num_top_queries, dim=-1)
+ # scores = scores.gather(dim=-1, index=index)
+
+ # ------ Original ------
+ scores = F.sigmoid(logits)
+ scores, index = torch.topk(scores.flatten(1), self.num_top_queries, dim=-1)
+
+ # TODO for older tensorrt
+ # labels = index % self.num_classes
+ labels = mod(index, self.num_classes)
+ index = index // self.num_classes
+ boxes = bbox_pred.gather(
+ dim=1, index=index.unsqueeze(-1).repeat(1, 1, bbox_pred.shape[-1])
+ )
+
+ else:
+ scores = F.softmax(logits)[:, :, :-1]
+ scores, labels = scores.max(dim=-1)
+ if scores.shape[1] > self.num_top_queries:
+ scores, index = torch.topk(scores, self.num_top_queries, dim=-1)
+ labels = torch.gather(labels, dim=1, index=index)
+ boxes = torch.gather(
+ boxes, dim=1, index=index.unsqueeze(-1).tile(1, 1, boxes.shape[-1])
+ )
+
+ if self.clip_boxes:
+ boxes = boxes.clamp(min=0, max=self.target_size - 1)
+ boxes = postprocess_boxes(
+ boxes,
+ orig_target_sizes,
+ target_size=self.target_size,
+ letterbox=self.letterbox,
+ )
+
+ # TODO for onnx export
+ if self.deploy_mode:
+ return labels, boxes, scores
+
+ results = []
+ for lab, box, sco in zip(labels, boxes, scores):
+ result = dict(labels=lab, boxes=box, scores=sco)
+ results.append(result)
+
+ return results
+
+ def deploy(
+ self,
+ ):
+ self.eval()
+ self.deploy_mode = True
+ return self
diff --git a/services/layout_analyze/dfine_la/model/utils.py b/services/layout_analyze/dfine_la/model/utils.py
new file mode 100644
index 0000000..dffdcb5
--- /dev/null
+++ b/services/layout_analyze/dfine_la/model/utils.py
@@ -0,0 +1,182 @@
+"""
+D-FINE: Redefine Regression Task of DETRs as Fine-grained Distribution Refinement
+Copyright (c) 2024 The D-FINE Authors. All Rights Reserved.
+---------------------------------------------------------------------------------
+Modified from RT-DETR (https://github.com/lyuwenyu/RT-DETR)
+Copyright (c) 2023 lyuwenyu. All Rights Reserved.
+"""
+
+import math
+from typing import List
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+def inverse_sigmoid(x: torch.Tensor, eps: float = 1e-5) -> torch.Tensor:
+ x = x.clip(min=0.0, max=1.0)
+ return torch.log(x.clip(min=eps) / (1 - x).clip(min=eps))
+
+
+def bias_init_with_prob(prior_prob=0.01):
+ """initialize conv/fc bias value according to a given probability value."""
+ bias_init = float(-math.log((1 - prior_prob) / prior_prob))
+ return bias_init
+
+
+def deformable_attention_core_func(
+ value, value_spatial_shapes, sampling_locations, attention_weights
+):
+ """
+ Args:
+ value (Tensor): [bs, value_length, n_head, c]
+ value_spatial_shapes (Tensor|List): [n_levels, 2]
+ value_level_start_index (Tensor|List): [n_levels]
+ sampling_locations (Tensor): [bs, query_length, n_head, n_levels, n_points, 2]
+ attention_weights (Tensor): [bs, query_length, n_head, n_levels, n_points]
+
+ Returns:
+ output (Tensor): [bs, Length_{query}, C]
+ """
+ bs, _, n_head, c = value.shape
+ _, Len_q, _, n_levels, n_points, _ = sampling_locations.shape
+
+ split_shape = [h * w for h, w in value_spatial_shapes]
+ value_list = value.split(split_shape, dim=1)
+ sampling_grids = 2 * sampling_locations - 1
+ sampling_value_list = []
+ for level, (h, w) in enumerate(value_spatial_shapes):
+ # N_, H_*W_, M_, D_ -> N_, H_*W_, M_*D_ -> N_, M_*D_, H_*W_ -> N_*M_, D_, H_, W_
+ value_l_ = value_list[level].flatten(2).permute(0, 2, 1).reshape(bs * n_head, c, h, w)
+ # N_, Lq_, M_, P_, 2 -> N_, M_, Lq_, P_, 2 -> N_*M_, Lq_, P_, 2
+ sampling_grid_l_ = sampling_grids[:, :, :, level].permute(0, 2, 1, 3, 4).flatten(0, 1)
+ # N_*M_, D_, Lq_, P_
+ sampling_value_l_ = F.grid_sample(
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
+ )
+ sampling_value_list.append(sampling_value_l_)
+ # (N_, Lq_, M_, L_, P_) -> (N_, M_, Lq_, L_, P_) -> (N_*M_, 1, Lq_, L_*P_)
+ attention_weights = attention_weights.permute(0, 2, 1, 3, 4).reshape(
+ bs * n_head, 1, Len_q, n_levels * n_points
+ )
+ output = (
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
+ .sum(-1)
+ .reshape(bs, n_head * c, Len_q)
+ )
+
+ return output.permute(0, 2, 1)
+
+
+def deformable_attention_core_func_v2(
+ value: torch.Tensor,
+ value_spatial_shapes,
+ sampling_locations: torch.Tensor,
+ attention_weights: torch.Tensor,
+ num_points_list: List[int],
+ method="default",
+):
+ """
+ Args:
+ value (Tensor): [bs, value_length, n_head, c]
+ value_spatial_shapes (Tensor|List): [n_levels, 2]
+ value_level_start_index (Tensor|List): [n_levels]
+ sampling_locations (Tensor): [bs, query_length, n_head, n_levels * n_points, 2]
+ attention_weights (Tensor): [bs, query_length, n_head, n_levels * n_points]
+
+ Returns:
+ output (Tensor): [bs, Length_{query}, C]
+ """
+ bs, n_head, c, _ = value[0].shape
+ _, Len_q, _, _, _ = sampling_locations.shape
+
+ # sampling_offsets [8, 480, 8, 12, 2]
+ if method == "default":
+ sampling_grids = 2 * sampling_locations - 1
+
+ elif method == "discrete":
+ sampling_grids = sampling_locations
+
+ sampling_grids = sampling_grids.permute(0, 2, 1, 3, 4).flatten(0, 1)
+ sampling_locations_list = sampling_grids.split(num_points_list, dim=-2)
+
+ sampling_value_list = []
+ for level, (h, w) in enumerate(value_spatial_shapes):
+ value_l = value[level].reshape(bs * n_head, c, h, w)
+ sampling_grid_l: torch.Tensor = sampling_locations_list[level]
+
+ if method == "default":
+ sampling_value_l = F.grid_sample(
+ value_l, sampling_grid_l, mode="bilinear", padding_mode="zeros", align_corners=False
+ )
+
+ elif method == "discrete":
+ # n * m, seq, n, 2
+ sampling_coord = (
+ sampling_grid_l * torch.tensor([[w, h]], device=value_l.device) + 0.5
+ ).to(torch.int64)
+
+ # FIX ME? for rectangle input
+ sampling_coord = sampling_coord.clamp(0, h - 1)
+ sampling_coord = sampling_coord.reshape(bs * n_head, Len_q * num_points_list[level], 2)
+
+ s_idx = (
+ torch.arange(sampling_coord.shape[0], device=value_l.device)
+ .unsqueeze(-1)
+ .repeat(1, sampling_coord.shape[1])
+ )
+ sampling_value_l: torch.Tensor = value_l[
+ s_idx, :, sampling_coord[..., 1], sampling_coord[..., 0]
+ ] # n l c
+
+ sampling_value_l = sampling_value_l.permute(0, 2, 1).reshape(
+ bs * n_head, c, Len_q, num_points_list[level]
+ )
+
+ sampling_value_list.append(sampling_value_l)
+
+ attn_weights = attention_weights.permute(0, 2, 1, 3).reshape(
+ bs * n_head, 1, Len_q, sum(num_points_list)
+ )
+ weighted_sample_locs = torch.concat(sampling_value_list, dim=-1) * attn_weights
+ output = weighted_sample_locs.sum(-1).reshape(bs, n_head * c, Len_q)
+
+ return output.permute(0, 2, 1)
+
+
+def get_activation(act: str, inpace: bool = True):
+ """get activation"""
+ if act is None:
+ return nn.Identity()
+
+ elif isinstance(act, nn.Module):
+ return act
+
+ act = act.lower()
+
+ if act == "silu" or act == "swish":
+ m = nn.SiLU()
+
+ elif act == "relu":
+ m = nn.ReLU()
+
+ elif act == "leaky_relu":
+ m = nn.LeakyReLU()
+
+ elif act == "silu":
+ m = nn.SiLU()
+
+ elif act == "gelu":
+ m = nn.GELU()
+
+ elif act == "hardsigmoid":
+ m = nn.Hardsigmoid()
+
+ else:
+ raise RuntimeError("")
+
+ if hasattr(m, "inplace"):
+ m.inplace = inpace
+
+ return m
diff --git a/services/layout_analyze/dfine_la/preprocess.py b/services/layout_analyze/dfine_la/preprocess.py
new file mode 100644
index 0000000..2f895e0
--- /dev/null
+++ b/services/layout_analyze/dfine_la/preprocess.py
@@ -0,0 +1,60 @@
+"""OpenCV preprocessing equivalent to the official Stage-2 evaluator."""
+
+from __future__ import annotations
+
+import cv2
+import numpy as np
+import torch
+
+
+def decode_images(payloads: list[bytes]) -> list[np.ndarray]:
+ images = []
+ for payload in payloads:
+ image = cv2.imdecode(np.frombuffer(payload, dtype=np.uint8), cv2.IMREAD_COLOR)
+ if image is None:
+ raise ValueError("OpenCV failed to decode an uploaded image")
+ images.append(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
+ return images
+
+
+def resize_and_pad(
+ image: np.ndarray,
+ target_size: int = 960,
+ fill_value: int = 114,
+) -> np.ndarray:
+ original_height, original_width = image.shape[:2]
+ ratio = target_size / max(original_width, original_height)
+ new_width = int(original_width * ratio)
+ new_height = int(original_height * ratio)
+ pad_left = (target_size - new_width) // 2
+ pad_top = (target_size - new_height) // 2
+ resized = cv2.resize(
+ image,
+ (new_width, new_height),
+ interpolation=cv2.INTER_LANCZOS4,
+ )
+ canvas = np.full(
+ (target_size, target_size, resized.shape[2]),
+ fill_value,
+ dtype=image.dtype,
+ )
+ canvas[pad_top : pad_top + new_height, pad_left : pad_left + new_width] = resized
+ return canvas
+
+
+def uint8_hwc_to_tensor(image: np.ndarray) -> torch.Tensor:
+ if image.dtype != np.uint8 or image.ndim != 3:
+ raise ValueError("expected an HWC uint8 image")
+ chw = np.ascontiguousarray(image.transpose((2, 0, 1)))
+ return torch.from_numpy(chw).to(dtype=torch.get_default_dtype()).div(255)
+
+
+def preprocess_images(images: list[np.ndarray], image_size: int = 960):
+ tensors = []
+ original_sizes = []
+ for image in images:
+ height, width = image.shape[:2]
+ tensors.append(uint8_hwc_to_tensor(resize_and_pad(image, image_size)))
+ original_sizes.append([width, height])
+ batch = tensors[0].unsqueeze(0) if len(tensors) == 1 else torch.stack(tensors)
+ return batch, torch.tensor(original_sizes)
diff --git a/services/layout_analyze/dfine_la/runtime.py b/services/layout_analyze/dfine_la/runtime.py
new file mode 100644
index 0000000..c78e57b
--- /dev/null
+++ b/services/layout_analyze/dfine_la/runtime.py
@@ -0,0 +1,110 @@
+"""Single-device model runtime with optional parallel preprocessing."""
+
+from __future__ import annotations
+
+import queue
+import time
+
+import torch
+
+from .config import Settings
+from .cuda_graph import CUDAGraphModel
+from .model import load_model
+from .preprocess import decode_images, preprocess_images
+
+
+class ModelRuntime:
+ def __init__(self, settings: Settings) -> None:
+ settings = settings.validate_checkpoint()
+ if settings.device == "cuda" and not torch.cuda.is_available():
+ raise RuntimeError("an NVIDIA GPU with CUDA support is required")
+
+ self.settings = settings
+ device_name = (
+ "cuda:0"
+ if settings.device == "cuda"
+ or (settings.device == "auto" and torch.cuda.is_available())
+ else "cpu"
+ )
+ self.device = torch.device(device_name)
+ model = load_model(
+ settings.model_path,
+ self.device,
+ num_classes=settings.num_classes,
+ image_size=settings.image_size,
+ )
+ self.cuda_graph_enabled = settings.cuda_graph_enabled and self.device.type == "cuda"
+ if self.cuda_graph_enabled:
+ model = CUDAGraphModel(model)
+ model.warmup(settings.image_size)
+ self._engines: queue.Queue = queue.Queue(maxsize=1)
+ self._engines.put(model)
+ self.cuda_graph_ready = bool(getattr(model, "ready", False))
+ if self.cuda_graph_enabled and not self.cuda_graph_ready:
+ raise RuntimeError("CUDA Graph warmup did not reach readiness")
+
+ def prepare(self, payloads: list[bytes]):
+ decode_started = time.perf_counter()
+ images = decode_images(payloads)
+ decode_ms = (time.perf_counter() - decode_started) * 1000
+
+ preprocess_started = time.perf_counter()
+ ready = preprocess_images(images, self.settings.image_size)
+ preprocess_ms = (time.perf_counter() - preprocess_started) * 1000
+ return ready, decode_ms, preprocess_ms
+
+ def infer(self, ready):
+ queue_started = time.perf_counter()
+ model = self._engines.get(block=True)
+ queue_ms = (time.perf_counter() - queue_started) * 1000
+ try:
+ images = ready[0].to(self.device)
+ sizes = ready[1].to(self.device)
+ inference_started = time.perf_counter()
+ with torch.no_grad():
+ labels, boxes, scores = model(images, sizes)
+ outputs = tuple(
+ value.cpu().detach().numpy() for value in (labels, boxes, scores)
+ )
+ # The CPU copy synchronizes CUDA. Include it so Server-Timing
+ # reports completed inference instead of asynchronous launch time.
+ inference_ms = (time.perf_counter() - inference_started) * 1000
+ return outputs, {"queue": queue_ms, "inference": inference_ms}
+ finally:
+ self._engines.put(model)
+
+ def health(self) -> dict:
+ return {
+ "status": "healthy",
+ "model_version": self.settings.model_version,
+ "num_classes": self.settings.num_classes,
+ "img_size": self.settings.image_size,
+ "preprocess_type": "resize_pad",
+ "architecture": self.settings.architecture,
+ "color_order": self.settings.color_order,
+ "resize_backend": self.settings.resize_backend,
+ "postprocess_mode": self.settings.postprocess,
+ "device": str(self.device),
+ "inference_precision": (
+ "fp16_autocast" if self.device.type == "cuda" else "fp32"
+ ),
+ "cuda_graph_enabled": self.cuda_graph_enabled,
+ "cuda_graph_ready": self.cuda_graph_ready,
+ "cuda_graph_batch_sizes": [1],
+ }
+
+ def info(self) -> dict:
+ model_config = self.settings.public_dict()
+ model_config.update(
+ device=str(self.device),
+ inference_precision=(
+ "fp16_autocast" if self.device.type == "cuda" else "fp32"
+ ),
+ cuda_graph_enabled=self.cuda_graph_enabled,
+ )
+ return {
+ "model_config": model_config,
+ "device_count": 1,
+ "devices": [str(self.device)],
+ "endpoint": "/inference",
+ }
diff --git a/services/layout_analyze/examples/infer.py b/services/layout_analyze/examples/infer.py
new file mode 100644
index 0000000..67c6eba
--- /dev/null
+++ b/services/layout_analyze/examples/infer.py
@@ -0,0 +1,47 @@
+#!/usr/bin/env python3
+"""Send one or more images to the D-FINE LA HTTP API."""
+
+import argparse
+from contextlib import ExitStack
+import json
+from pathlib import Path
+
+import requests
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("images", nargs="+", type=Path)
+ parser.add_argument("--url", default="http://127.0.0.1:8000/inference")
+ parser.add_argument("--confidence", type=float)
+ parser.add_argument(
+ "--class-confidences",
+ help=(
+ "JSON object keyed by numeric class ID; for example "
+ "'{\"4\":0.7,\"8\":0.3}' sets Page-footer and Table overrides. "
+ "Unspecified classes inherit --confidence."
+ ),
+ )
+ args = parser.parse_args()
+
+ data = {}
+ if args.confidence is not None:
+ data["confidence"] = str(args.confidence)
+ if args.class_confidences is not None:
+ data["class_confidences"] = args.class_confidences
+
+ with ExitStack() as stack:
+ files = [
+ (
+ "images",
+ (path.name, stack.enter_context(path.open("rb")), "application/octet-stream"),
+ )
+ for path in args.images
+ ]
+ response = requests.post(args.url, files=files, data=data, timeout=120)
+ response.raise_for_status()
+ print(json.dumps(response.json(), ensure_ascii=False))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/services/layout_analyze/models/README.md b/services/layout_analyze/models/README.md
new file mode 100644
index 0000000..cdfd6c5
--- /dev/null
+++ b/services/layout_analyze/models/README.md
@@ -0,0 +1,14 @@
+# Model directory
+
+Use `layout_analysis/last.pth` and `layout_analysis/metadata.json` from the
+unified `oxr-model` repository. Both files are required for startup.
+
+The checkpoint is intentionally not included in this source distribution.
+Set `OXR_MODEL_DIR` to the absolute model repository root before starting
+Compose. It mounts the repository read-only; no checkpoint copy is needed.
+Run `git lfs pull` in the model checkout first. The container does not download
+weights automatically.
+
+The service reads the model version, supported configuration and checkpoint
+size/SHA-256 from `metadata.json` and verifies them before loading weights.
+An explicit `MODEL_METADATA_PATH` can override the metadata path.
diff --git a/services/layout_analyze/requirements-dev.txt b/services/layout_analyze/requirements-dev.txt
new file mode 100644
index 0000000..6a84d0c
--- /dev/null
+++ b/services/layout_analyze/requirements-dev.txt
@@ -0,0 +1,3 @@
+-r requirements.txt
+httpx==0.28.1
+pytest==8.4.1
diff --git a/services/layout_analyze/requirements.txt b/services/layout_analyze/requirements.txt
new file mode 100644
index 0000000..69df7e0
--- /dev/null
+++ b/services/layout_analyze/requirements.txt
@@ -0,0 +1,6 @@
+fastapi==0.116.1
+numpy==1.26.4
+opencv-python-headless==4.11.0.86
+python-multipart==0.0.20
+requests==2.32.4
+uvicorn[standard]==0.35.0
diff --git a/services/layout_analyze/tests/test_api.py b/services/layout_analyze/tests/test_api.py
new file mode 100644
index 0000000..897d861
--- /dev/null
+++ b/services/layout_analyze/tests/test_api.py
@@ -0,0 +1,148 @@
+import numpy as np
+from fastapi.testclient import TestClient
+
+from dfine_la.api import create_app
+
+
+class FakeRuntime:
+ def __init__(self, settings):
+ self.settings = settings
+
+ def prepare(self, payloads):
+ return payloads, 1.0, 2.0
+
+ def infer(self, ready):
+ count = len(ready)
+ outputs = (
+ np.tile(np.array([[0, 1, 1, 2]], dtype=np.int64), (count, 1)),
+ np.tile(
+ np.array(
+ [[
+ [0.0, 0.0, 1.0, 1.0],
+ [1.0, 1.0, 2.0, 2.0],
+ [2.0, 2.0, 3.0, 3.0],
+ [3.0, 3.0, 4.0, 4.0],
+ ]],
+ dtype=np.float32,
+ ),
+ (count, 1, 1),
+ ),
+ np.tile(
+ np.array([[0.4, 0.6, 0.8, 0.9]], dtype=np.float32),
+ (count, 1),
+ ),
+ )
+ return outputs, {"queue": 0.0, "inference": 3.0}
+
+ def health(self):
+ return {"status": "healthy", "cuda_graph_ready": True}
+
+ def info(self):
+ return {"endpoint": "/inference"}
+
+
+def test_api_contract_and_no_versioned_route():
+ app = create_app(runtime_factory=FakeRuntime)
+ with TestClient(app) as client:
+ response = client.post(
+ "/inference",
+ files=[("images", ("image.png", b"image", "image/png"))],
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "status": "success",
+ "params": {},
+ "data": {
+ "labels": [[0, 1, 1, 2]],
+ "boxes": [[
+ [0.0, 0.0, 1.0, 1.0],
+ [1.0, 1.0, 2.0, 2.0],
+ [2.0, 2.0, 3.0, 3.0],
+ [3.0, 3.0, 4.0, 4.0],
+ ]],
+ "scores": [[
+ 0.4000000059604645,
+ 0.6000000238418579,
+ 0.800000011920929,
+ 0.8999999761581421,
+ ]],
+ },
+ }
+ assert "request_read" in response.headers["server-timing"]
+ assert client.get("/health").json()["status"] == "healthy"
+ assert client.get("/model/info").json()["endpoint"] == "/inference"
+ assert client.post("/legacy-inference").status_code == 404
+ assert client.get("/docs").status_code == 404
+ assert client.get("/redoc").status_code == 404
+ assert client.get("/openapi.json").status_code == 404
+
+
+def test_missing_images_returns_422():
+ app = create_app(runtime_factory=FakeRuntime)
+ with TestClient(app) as client:
+ assert client.post("/inference").status_code == 422
+
+
+def test_global_confidence_filters_all_classes_and_keeps_fields_aligned():
+ app = create_app(runtime_factory=FakeRuntime)
+ with TestClient(app) as client:
+ response = client.post(
+ "/inference",
+ files=[("images", ("image.png", b"image", "image/png"))],
+ data={"confidence": "0.7"},
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["params"] == {"confidence": 0.7, "class_confidences": {}}
+ assert body["data"]["labels"] == [[1, 2]]
+ assert body["data"]["boxes"] == [[
+ [2.0, 2.0, 3.0, 3.0],
+ [3.0, 3.0, 4.0, 4.0],
+ ]]
+ assert len(body["data"]["scores"][0]) == 2
+
+
+def test_class_confidences_override_global_confidence():
+ app = create_app(runtime_factory=FakeRuntime)
+ with TestClient(app) as client:
+ response = client.post(
+ "/inference",
+ files=[("images", ("image.png", b"image", "image/png"))],
+ data={
+ "confidence": "0.7",
+ "class_confidences": '{"1": 0.5, "2": 0.95}',
+ },
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["params"] == {
+ "confidence": 0.7,
+ "class_confidences": {"1": 0.5, "2": 0.95},
+ }
+ assert body["data"]["labels"] == [[1, 1]]
+ assert body["data"]["boxes"] == [[
+ [1.0, 1.0, 2.0, 2.0],
+ [2.0, 2.0, 3.0, 3.0],
+ ]]
+ assert len(body["data"]["scores"][0]) == 2
+
+
+def test_invalid_confidence_parameters_return_422_before_inference():
+ app = create_app(runtime_factory=FakeRuntime)
+ invalid_data = [
+ {"confidence": "-0.1"},
+ {"confidence": "nan"},
+ {"class_confidences": "[]"},
+ {"class_confidences": '{"12": 0.5}'},
+ {"class_confidences": '{"1": 1.1}'},
+ ]
+ with TestClient(app) as client:
+ for data in invalid_data:
+ response = client.post(
+ "/inference",
+ files=[("images", ("image.png", b"image", "image/png"))],
+ data=data,
+ )
+ assert response.status_code == 422, data
diff --git a/services/layout_analyze/tests/test_config.py b/services/layout_analyze/tests/test_config.py
new file mode 100644
index 0000000..82cba99
--- /dev/null
+++ b/services/layout_analyze/tests/test_config.py
@@ -0,0 +1,141 @@
+from pathlib import Path
+import copy
+import hashlib
+import json
+
+import pytest
+
+import dfine_la.config as config
+from dfine_la.config import Settings
+
+
+def model_bundle(tmp_path):
+ checkpoint = tmp_path / "last.pth"
+ checkpoint.write_bytes(b"checkpoint")
+ metadata = copy.deepcopy(config.SUPPORTED_METADATA)
+ metadata.update(
+ model_version="1.0.0", checkpoint="last.pth",
+ checkpoint_size_bytes=checkpoint.stat().st_size,
+ checkpoint_sha256=hashlib.sha256(checkpoint.read_bytes()).hexdigest(),
+ )
+ path = tmp_path / "metadata.json"
+ path.write_text(json.dumps(metadata))
+ return checkpoint, path, metadata
+
+
+def test_checkpoint_validation_accepts_expected_file(model_bundle):
+ checkpoint, path, _ = model_bundle
+ settings = Settings(model_path=checkpoint, device="cpu").validate_checkpoint()
+ assert settings.model_version == "1.0.0"
+ assert settings.metadata_path == path
+ assert settings.id2label["9"] == "Code Block"
+ assert settings.device == "cpu"
+ assert "metadata_path" not in settings.public_dict()
+ assert "model_path" not in settings.public_dict()
+
+
+def test_checkpoint_validation_rejects_missing_file(tmp_path: Path):
+ with pytest.raises(RuntimeError, match="checkpoint not found"):
+ Settings(model_path=tmp_path / "missing.pth").validate_checkpoint()
+
+
+def test_device_from_env(monkeypatch):
+ monkeypatch.setenv("DFINE_DEVICE", "cpu")
+ assert Settings.from_env().device == "cpu"
+
+
+def test_invalid_device_from_env(monkeypatch):
+ monkeypatch.setenv("DFINE_DEVICE", "metal")
+ with pytest.raises(RuntimeError, match="DFINE_DEVICE must be one of"):
+ Settings.from_env()
+
+
+def test_release_checkpoint_defaults(monkeypatch):
+ monkeypatch.delenv("MODEL_PATH", raising=False)
+ settings = Settings.from_env()
+ assert settings.model_path == Path("/models/layout_analysis/last.pth")
+ assert settings.model_version == "unknown" # Resolved from metadata at startup.
+
+
+def test_model_path_override(monkeypatch):
+ monkeypatch.setenv("MODEL_PATH", "/custom/last.pth")
+ assert Settings.from_env().model_path == Path("/custom/last.pth")
+
+
+def test_checkpoint_validation_rejects_wrong_hash(model_bundle):
+ checkpoint, _, _ = model_bundle
+ checkpoint.write_bytes(b"checkpoinx") # Same size; fails the integrity check.
+ with pytest.raises(RuntimeError, match="SHA-256 mismatch"):
+ Settings(model_path=checkpoint).validate_checkpoint()
+
+
+def test_checkpoint_validation_rejects_wrong_size(model_bundle):
+ checkpoint, _, _ = model_bundle
+ checkpoint.write_bytes(b"short")
+ with pytest.raises(RuntimeError, match="size mismatch"):
+ Settings(model_path=checkpoint).validate_checkpoint()
+
+
[email protected]("field,value", [
+ ("schema_version", 2), ("schema_version", True),
+ ("model_type", "other"), ("architecture", "stage2_b4"),
+ ("image_size", 800), ("num_classes", 13), ("color_order", "bgr"),
+ ("resize_backend", "bilinear"), ("postprocess", "other"),
+ ("provides_reading_order", True), ("id2label", {"0": "Text"}),
+ ("model_version", ""), ("model_version", "training_release"),
+ ("model_version", "1.0"), ("checkpoint", "../last.pth"),
+ ("checkpoint_size_bytes", True), ("checkpoint_size_bytes", -1),
+ ("checkpoint_sha256", "invalid"),
+])
+def test_rejects_invalid_or_unsupported_metadata(model_bundle, field, value):
+ checkpoint, path, metadata = model_bundle
+ metadata[field] = value
+ path.write_text(json.dumps(metadata))
+ with pytest.raises(RuntimeError, match="metadata"):
+ Settings(model_path=checkpoint).validate_checkpoint()
+
+
[email protected]("content", ["not JSON", "[]"])
+def test_rejects_malformed_metadata(model_bundle, content):
+ checkpoint, path, _ = model_bundle
+ path.write_text(content)
+ with pytest.raises(RuntimeError, match="metadata"):
+ Settings(model_path=checkpoint).validate_checkpoint()
+
+
+def test_metadata_is_required(model_bundle):
+ checkpoint, path, _ = model_bundle
+ path.unlink()
+ with pytest.raises(RuntimeError, match="metadata"):
+ Settings(model_path=checkpoint).validate_checkpoint()
+
+
+def test_metadata_path_override(model_bundle, monkeypatch):
+ checkpoint, path, _ = model_bundle
+ override = path.with_name("custom.json")
+ path.rename(override)
+ monkeypatch.setenv("MODEL_PATH", str(checkpoint))
+ monkeypatch.setenv("MODEL_METADATA_PATH", str(override))
+ assert Settings.from_env().validate_checkpoint().metadata_path == override
+
+
+def test_missing_required_metadata_field(model_bundle):
+ checkpoint, path, metadata = model_bundle
+ metadata.pop("image_size")
+ path.write_text(json.dumps(metadata))
+ with pytest.raises(RuntimeError, match="image_size"):
+ Settings(model_path=checkpoint).validate_checkpoint()
+
+
+def test_metadata_does_not_override_runtime_settings(model_bundle):
+ checkpoint, path, metadata = model_bundle
+ metadata.update(device="cuda", inference_precision="fp16_autocast",
+ cuda_graph_enabled=True)
+ path.write_text(json.dumps(metadata))
+ settings = Settings(model_path=checkpoint, device="cpu",
+ inference_precision="fp32", cuda_graph_enabled=False)
+ loaded = settings.validate_checkpoint()
+ assert loaded.device == "cpu"
+ assert loaded.inference_precision == "fp32"
+ assert loaded.cuda_graph_enabled is False
diff --git a/services/layout_analyze/tests/test_preprocess.py b/services/layout_analyze/tests/test_preprocess.py
new file mode 100644
index 0000000..41618a8
--- /dev/null
+++ b/services/layout_analyze/tests/test_preprocess.py
@@ -0,0 +1,19 @@
+import numpy as np
+import torch
+
+from dfine_la.preprocess import preprocess_images, resize_and_pad
+
+
+def test_resize_and_pad_keeps_canvas_shape_and_fill_value():
+ image = np.zeros((100, 200, 3), dtype=np.uint8)
+ canvas = resize_and_pad(image, target_size=960)
+ assert canvas.shape == (960, 960, 3)
+ assert np.all(canvas[:200] == 114)
+
+
+def test_batch1_preprocessing_matches_runtime_signature():
+ image = np.zeros((100, 200, 3), dtype=np.uint8)
+ batch, sizes = preprocess_images([image])
+ assert batch.shape == (1, 3, 960, 960)
+ assert batch.dtype == torch.float32
+ assert sizes.tolist() == [[200, 100]]
diff --git a/services/layout_analyze/tests/test_runtime.py b/services/layout_analyze/tests/test_runtime.py
new file mode 100644
index 0000000..c960d0b
--- /dev/null
+++ b/services/layout_analyze/tests/test_runtime.py
@@ -0,0 +1,55 @@
+from pathlib import Path
+
+import torch
+
+from dfine_la.config import Settings
+import dfine_la.runtime as runtime_module
+
+
+class FakeModel:
+ def __call__(self, images, sizes):
+ batch_size = images.shape[0]
+ return (
+ torch.zeros((batch_size, 1), dtype=torch.int64, device=images.device),
+ torch.zeros((batch_size, 1, 4), device=images.device),
+ torch.ones((batch_size, 1), device=images.device),
+ )
+
+
+def test_cpu_runtime_uses_fp32_eager_inference(monkeypatch):
+ monkeypatch.setattr(Settings, "validate_checkpoint", lambda self: self)
+ monkeypatch.setattr(runtime_module, "load_model", lambda *args, **kwargs: FakeModel())
+ settings = Settings(
+ model_path=Path("unused.pth"),
+ device="cpu",
+ cuda_graph_enabled=True,
+ )
+
+ runtime = runtime_module.ModelRuntime(settings)
+ outputs, _ = runtime.infer(
+ (torch.zeros((1, 3, 8, 8)), torch.tensor([[8, 8]]))
+ )
+
+ assert runtime.device == torch.device("cpu")
+ assert runtime.cuda_graph_enabled is False
+ assert runtime.health()["inference_precision"] == "fp32"
+ assert "model_path" not in runtime.health()
+ assert "model_path" not in runtime.info()["model_config"]
+ assert "metadata_path" not in runtime.info()["model_config"]
+ assert runtime.info()["devices"] == ["cpu"]
+ assert runtime.info()["model_config"]["device"] == "cpu"
+ assert runtime.info()["model_config"]["cuda_graph_enabled"] is False
+ assert outputs[0].shape == (1, 1)
+
+
+def test_cuda_mode_still_requires_cuda(monkeypatch):
+ monkeypatch.setattr(Settings, "validate_checkpoint", lambda self: self)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
+ settings = Settings(model_path=Path("unused.pth"), device="cuda")
+
+ try:
+ runtime_module.ModelRuntime(settings)
+ except RuntimeError as exc:
+ assert "NVIDIA GPU" in str(exc)
+ else:
+ raise AssertionError("CUDA mode must fail when CUDA is unavailable")
diff --git a/services/layout_analyze/third_party/D-FINE/LICENSE b/services/layout_analyze/third_party/D-FINE/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/services/layout_analyze/third_party/D-FINE/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/services/oxr/start_vllm.sh b/services/oxr/start_vllm.sh
new file mode 100644
index 0000000..3299a60
--- /dev/null
+++ b/services/oxr/start_vllm.sh
@@ -0,0 +1,17 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Use a complete local oxr-model checkout, including Git LFS files.
+model_dir="${MODEL_PATH:-${MODEL_NAME:-./oxr-model}}"
+if [[ ! -f "$model_dir/plugins/vllm/pyproject.toml" || ! -f "$model_dir/chat_template.jinja" ]]; then
+ echo "Expected an oxr-model repository root with plugins/vllm and chat_template.jinja: $model_dir" >&2
+ exit 1
+fi
+python3 -m pip install "$model_dir/plugins/vllm"
+export VLLM_PLUGINS=oxr
+exec vllm serve "$model_dir" \
+ --trust-remote-code --served-model-name oxr \
+ --chat-template "$model_dir/chat_template.jinja" \
+ --dtype bfloat16 --max-model-len 16384 \
+ --attention-config '{"backend":"TRITON_ATTN"}' \
+ --host 0.0.0.0 --port 8080 "$@"
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/unit/test_allinone_entrypoint.py b/tests/unit/test_allinone_entrypoint.py
new file mode 100644
index 0000000..824c194
--- /dev/null
+++ b/tests/unit/test_allinone_entrypoint.py
@@ -0,0 +1,388 @@
+import asyncio
+import importlib.util
+import json
+import os
+from pathlib import Path
+import signal
+import sys
+from types import SimpleNamespace
+
+import httpx
+import pytest
+
+
+SCRIPT_PATH = Path(__file__).parents[2] / "docker" / "allinone_entrypoint.py"
+SPEC = importlib.util.spec_from_file_location("allinone_entrypoint", SCRIPT_PATH)
+assert SPEC is not None and SPEC.loader is not None
+MODULE = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = MODULE
+SPEC.loader.exec_module(MODULE)
+AllInOneConfig = MODULE.AllInOneConfig
+
+
+def _config(**overrides):
+ env = {"MODEL_PATH": "/models/oxr"}
+ env.update(overrides)
+ return AllInOneConfig.from_env(env)
+
+
+def test_commands_use_loopback_model_services_and_public_api():
+ config = _config()
+
+ assert config.dfine_command() == [
+ "/opt/dfine-venv/bin/python",
+ "-m",
+ "uvicorn",
+ "dfine_la.api:app",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ "8081",
+ "--workers",
+ "1",
+ ]
+ assert config.vllm_command()[:5] == [
+ "/opt/vllm-venv/bin/python",
+ "-m",
+ "vllm.entrypoints.cli.main",
+ "serve",
+ "/models/oxr",
+ ]
+ assert "127.0.0.1" in config.vllm_command()
+ assert config.api_command() == [
+ "/opt/oxr-venv/bin/oxr",
+ "serve",
+ "--host",
+ "0.0.0.0",
+ "--port",
+ "8000",
+ "--workers",
+ "1",
+ "--layout-analyze-model-url",
+ "http://127.0.0.1:8081",
+ "--oxr-model-url",
+ "http://127.0.0.1:8080/v1",
+ "--oxr-model-name",
+ "oxr",
+ ]
+
+
+def test_dfine_and_api_environments_are_scoped():
+ config = _config(DFINE_MODEL_PATH="/weights/layout.pth", DFINE_PORT="9001")
+
+ dfine_env = config.dfine_env({"PYTHONPATH": "/existing"})
+ assert dfine_env["MODEL_PATH"] == "/weights/layout.pth"
+ assert dfine_env["MODEL_METADATA_PATH"] == "/weights/metadata.json"
+ assert dfine_env["PORT"] == "9001"
+ assert dfine_env["PYTHONPATH"] == "/app/services/layout_analyze:/existing"
+
+ api_env = config.api_env({})
+ assert api_env["OXR__LAYOUT_ANALYZE_MODEL__URL"] == "http://127.0.0.1:9001"
+ assert api_env["OXR__OXR_MODEL__URL"] == "http://127.0.0.1:8080/v1"
+ assert api_env["OXR__OXR_MODEL__MODEL_NAME"] == "oxr"
+ assert config.vllm_env({"VLLM_PLUGINS": "other"})["VLLM_PLUGINS"] == "oxr"
+
+
+def test_unified_repository_paths_and_frozen_inference_options():
+ config = _config()
+ assert config.dfine_model_path == "/models/oxr/layout_analysis/last.pth"
+ assert config.dfine_env({})["MODEL_METADATA_PATH"] == "/models/oxr/layout_analysis/metadata.json"
+ command = config.vllm_command()
+ assert command[command.index("--chat-template") + 1] == "/models/oxr/chat_template.jinja"
+ assert command[command.index("--dtype") + 1] == "bfloat16"
+ assert json.loads(command[command.index("--attention-config") + 1]) == {"backend": "TRITON_ATTN"}
+ assert command[command.index("--max-num-seqs") + 1] == "16"
+
+
+def model_repository(tmp_path):
+ for name in (
+ "config.json", "model.safetensors", "tokenizer.json", "chat_template.jinja",
+ "plugins/vllm/pyproject.toml", "layout_analysis/last.pth",
+ "layout_analysis/metadata.json",
+ ):
+ path = tmp_path / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("test fixture", encoding="utf-8")
+ return tmp_path
+
+
+def test_preflight_accepts_complete_repository(model_repository):
+ config = _config(MODEL_PATH=str(model_repository))
+ assert MODULE._validate_model_repository(config) == model_repository / "plugins/vllm"
+
+
[email protected]("name", ["model.safetensors", "tokenizer.json", "layout_analysis/last.pth"])
+def test_preflight_rejects_unresolved_lfs(model_repository, name):
+ (model_repository / name).write_text("version https://git-lfs.github.com/spec/v1\n")
+ with pytest.raises(ValueError, match="Unresolved Git LFS"):
+ MODULE._validate_model_repository(_config(MODEL_PATH=str(model_repository)))
+
+
+def test_preflight_rejects_missing_metadata(model_repository):
+ (model_repository / "layout_analysis/metadata.json").unlink()
+ with pytest.raises(ValueError, match="Missing model repository file"):
+ MODULE._validate_model_repository(_config(MODEL_PATH=str(model_repository)))
+
+
+def test_plugin_installs_from_temporary_copy_without_dependency_changes(model_repository, monkeypatch):
+ async def check():
+ commands = []
+ staged_path = None
+ original = (model_repository / "plugins/vllm/pyproject.toml").read_bytes()
+
+ async def start(name, command, env=None):
+ nonlocal staged_path
+ commands.append(command)
+ assert env["VLLM_PLUGINS"] == "oxr"
+ if name == "OXR plugin installation":
+ staged_path = Path(command[-1])
+ assert staged_path != model_repository / "plugins/vllm"
+ assert (staged_path / "pyproject.toml").read_bytes() == original
+ assert "--no-deps" in command and "--no-build-isolation" in command
+ async def wait():
+ return 0
+ return MODULE.ManagedProcess(name, SimpleNamespace(returncode=0, wait=wait))
+
+ async def shutdown(*args):
+ pass
+
+ monkeypatch.setattr(MODULE, "_start_process", start)
+ monkeypatch.setattr(MODULE, "_shutdown_processes", shutdown)
+ processes = []
+ await MODULE._prepare_plugin(
+ _config(MODEL_PATH=str(model_repository)), processes, asyncio.Event(),
+ )
+ assert "0.25.1" in commands[0][-1] and "2.11.0+cu130" in commands[0][-1]
+ assert "5.13.1" in commands[0][-1]
+ assert processes == []
+ assert not staged_path.exists()
+ assert (model_repository / "plugins/vllm/pyproject.toml").read_bytes() == original
+
+ asyncio.run(check())
+
+
+def test_vllm_extra_args_are_parsed_without_shell_evaluation():
+ config = _config(VLLM_EXTRA_ARGS="--enforce-eager --max-num-batched-tokens 8192")
+
+ assert config.vllm_command()[-3:] == ["--enforce-eager", "--max-num-batched-tokens", "8192"]
+
+
+ "overrides, message",
+ [
+ ({"MODEL_PATH": ""}, "MODEL_PATH must be set"),
+ ({"VLLM_GPU_MEMORY_UTILIZATION": "1"}, "must be greater than 0 and less than 1"),
+ ({"DFINE_PORT": "8080"}, "must be distinct"),
+ ({"DFINE_PORT": "65536"}, "must be at most 65535"),
+ ({"DFINE_MODEL_PATH": ""}, "DFINE_MODEL_PATH must be set"),
+ ({"VLLM_EXTRA_ARGS": "--port 9000"}, "cannot override managed options"),
+ ({"VLLM_EXTRA_ARGS": "--port=9000"}, "cannot override managed options"),
+ ({"VLLM_EXTRA_ARGS": "--attention-config {}"}, "cannot override managed options"),
+ ({"VLLM_EXTRA_ARGS": "-ac {}"}, "cannot override managed options"),
+ ({"VLLM_EXTRA_ARGS": "--attention-config.backend=FLASH_ATTN"}, "cannot override managed options"),
+ ({"VLLM_EXTRA_ARGS": "--attention-backend FLASH_ATTN"}, "cannot override managed options"),
+ ({"ALLINONE_STARTUP_TIMEOUT": "0"}, "must be greater than zero"),
+ ],
+)
+def test_invalid_configuration_fails_closed(overrides, message):
+ with pytest.raises(ValueError, match=message):
+ _config(**overrides)
+
+
[email protected]("name, payload", [
+ ("D-FINE", {"status": "loading"}),
+ ("D-FINE", []),
+ ("vLLM", {"data": [{"id": "other"}]}),
+ ("vLLM", {"data": "oxr"}),
+ ("vLLM", ["oxr"]),
+])
+def test_http_200_is_not_sufficient_readiness(name, payload):
+ response = httpx.Response(200, json=payload, request=httpx.Request("GET", "http://test"))
+ with pytest.raises(ValueError):
+ MODULE._validate_response(name, response)
+
+
+def test_expected_model_identity_is_configurable():
+ response = httpx.Response(
+ 200, json={"data": [{"id": "custom"}]},
+ request=httpx.Request("GET", "http://test"),
+ )
+ MODULE._validate_response("vLLM", response, "custom")
+ with pytest.raises(ValueError):
+ MODULE._validate_response("vLLM", response, "oxr")
+
+
+def test_startup_rechecks_process_after_http_response():
+ async def check():
+ process = SimpleNamespace(returncode=None)
+ managed = MODULE.ManagedProcess("vLLM", process)
+
+ def handler(request):
+ process.returncode = 7
+ return httpx.Response(200, json={"data": [{"id": "oxr"}]})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ with pytest.raises(RuntimeError, match="exited during startup"):
+ await MODULE._wait_for_http(
+ client, "vLLM", "http://test/models", [managed], asyncio.Event(), 1,
+ )
+
+ asyncio.run(check())
+
+
+def test_shutdown_cleans_group_even_when_leader_already_exited(monkeypatch):
+ async def check():
+ calls = []
+
+ def killpg(pid, signum):
+ calls.append((pid, signum))
+
+ async def wait():
+ return 7
+
+ monkeypatch.setattr(MODULE.os, "killpg", killpg)
+ process = SimpleNamespace(pid=123456, returncode=7, wait=wait)
+ await MODULE._shutdown_processes([MODULE.ManagedProcess("vLLM", process)], 0)
+ assert calls == [(123456, signal.SIGTERM), (123456, signal.SIGKILL)]
+
+ asyncio.run(check())
+
+
[email protected](sys.platform != "linux", reason="Linux container process groups")
+def test_real_process_ignoring_sigterm_is_reaped():
+ async def check():
+ process = await asyncio.create_subprocess_exec(
+ sys.executable, "-u", "-c",
+ "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); "
+ "print('ready', flush=True); time.sleep(60)",
+ stdout=asyncio.subprocess.PIPE, start_new_session=True,
+ )
+ try:
+ assert await asyncio.wait_for(process.stdout.readline(), 5) == b"ready\n"
+ await MODULE._shutdown_processes([MODULE.ManagedProcess("stub", process)], 0.05)
+ assert process.returncode == -signal.SIGKILL
+ finally:
+ if process.returncode is None:
+ os.killpg(process.pid, signal.SIGKILL)
+ await process.wait()
+
+ asyncio.run(check())
+
+
[email protected]("failure", [
+ "startup",
+ pytest.param("exit-zero", marks=pytest.mark.skipif(
+ sys.platform != "linux", reason="Dead-leader group probes require Linux")),
+ pytest.param("exit-seven", marks=pytest.mark.skipif(
+ sys.platform != "linux", reason="Dead-leader group probes require Linux")),
+ "stop",
+])
[email protected](sys.platform != "linux", reason="Linux container process groups")
+def test_supervisor_stops_all_real_owned_processes(monkeypatch, failure):
+ async def check():
+ owned = []
+ stop_event = None
+
+ def install_handlers(event):
+ nonlocal stop_event
+ stop_event = event
+
+ async def start(name, command, env=None):
+ code = 7 if failure == "exit-seven" else 0
+ script = (
+ "import signal,sys,time; "
+ f"signal.signal(signal.SIGUSR1, lambda *_: sys.exit({code})); "
+ "print('ready', flush=True); time.sleep(60)"
+ )
+ process = await asyncio.create_subprocess_exec(
+ sys.executable, "-u", "-c", script,
+ stdout=asyncio.subprocess.PIPE, start_new_session=True,
+ )
+ managed = MODULE.ManagedProcess(name, process)
+ owned.append(managed)
+ assert await asyncio.wait_for(process.stdout.readline(), 5) == b"ready\n"
+ return managed
+
+ async def ready(client, name, url, processes, stop_requested, timeout, *args):
+ if failure == "startup" and name == "vLLM":
+ raise TimeoutError("stub startup failure")
+ if name == "OXR API":
+ if failure == "stop":
+ stop_event.set()
+ else:
+ os.kill(owned[1].process.pid, signal.SIGUSR1)
+
+ monkeypatch.setattr(MODULE, "_install_signal_handlers", install_handlers)
+ monkeypatch.setattr(MODULE, "_start_process", start)
+ monkeypatch.setattr(MODULE, "_wait_for_http", ready)
+ async def prepare(*args):
+ pass
+ monkeypatch.setattr(MODULE, "_prepare_plugin", prepare)
+ try:
+ result = await asyncio.wait_for(MODULE._run(_config()), 10)
+ assert result == {"startup": 1, "exit-zero": 1, "exit-seven": 7, "stop": 0}[failure]
+ assert len(owned) == (2 if failure == "startup" else 3)
+ assert all(item.process.returncode is not None for item in owned)
+ for item in owned:
+ with pytest.raises(ProcessLookupError):
+ os.killpg(item.process.pid, 0)
+ finally:
+ for item in owned:
+ try:
+ os.killpg(item.process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ await asyncio.gather(*(item.process.wait() for item in owned))
+ await asyncio.gather(*(item.process.stdout.read() for item in owned))
+
+ asyncio.run(check())
+
+
[email protected]("exit_code, expected", [(0, 1), (7, 7)])
+def test_unexpected_exit_propagates_code_and_cleans_siblings(monkeypatch, exit_code, expected):
+ async def check():
+ owned = []
+
+ class Process:
+ def __init__(self, pid):
+ self.pid = pid
+ self.returncode = None
+ self.done = asyncio.Event()
+
+ def exit(self, code):
+ self.returncode = code
+ self.done.set()
+
+ async def wait(self):
+ await self.done.wait()
+ return self.returncode
+
+ async def start(name, command, env=None):
+ managed = MODULE.ManagedProcess(name, Process(1000 + len(owned)))
+ owned.append(managed)
+ return managed
+
+ async def ready(client, name, *args):
+ if name == "OXR API":
+ owned[1].process.exit(exit_code)
+
+ def killpg(pid, signum):
+ process = next(item.process for item in owned if item.process.pid == pid)
+ if process.returncode is not None:
+ raise ProcessLookupError
+ if signum != 0:
+ process.exit(-signum)
+
+ monkeypatch.setattr(MODULE, "_install_signal_handlers", lambda _: None)
+ monkeypatch.setattr(MODULE, "_start_process", start)
+ monkeypatch.setattr(MODULE, "_wait_for_http", ready)
+ async def prepare(*args):
+ pass
+ monkeypatch.setattr(MODULE, "_prepare_plugin", prepare)
+ monkeypatch.setattr(MODULE.os, "killpg", killpg)
+ assert await MODULE._run(_config()) == expected
+ assert len(owned) == 3
+ assert all(item.process.returncode is not None for item in owned)
+
+ asyncio.run(check())
diff --git a/tests/unit/test_assembler.py b/tests/unit/test_assembler.py
new file mode 100644
index 0000000..f8b9ca0
--- /dev/null
+++ b/tests/unit/test_assembler.py
@@ -0,0 +1,16 @@
+import pytest
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.assembly_postprocess import blocks_to_markdown
+
+def test_blocks_to_markdown():
+ blocks = [
+ Block(idx=0, type=BlockType.TITLE, bbox=[0,0,10,10], content="Title", format=ContentFormat.TEXT),
+ Block(idx=1, type=BlockType.TEXT, bbox=[0,10,10,20], content="Hello world", format=ContentFormat.TEXT),
+ Block(idx=2, type=BlockType.CODE_BLOCK, bbox=[0,20,10,30], content="```\nprint('ok')\n```", format=ContentFormat.MARKDOWN),
+ Block(idx=3, type=BlockType.CHEMICAL_STRUCTURE, bbox=[0,30,10,40], content="$\\smiles{CCO}$", format=ContentFormat.MARKDOWN),
+ ]
+ md = blocks_to_markdown(blocks)
+ assert "# Title" in md
+ assert "Hello world" in md
+ assert "print('ok')" in md
+ assert "$\\smiles{CCO}$" in md
diff --git a/tests/unit/test_cross_category_dedupe.py b/tests/unit/test_cross_category_dedupe.py
new file mode 100644
index 0000000..c90c1ac
--- /dev/null
+++ b/tests/unit/test_cross_category_dedupe.py
@@ -0,0 +1,90 @@
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.cross_category_dedupe import (
+ dedupe_systematic_cross_category_blocks,
+ normalize_cross_category_content,
+)
+
+
+def _block(
+ idx: int,
+ block_type: BlockType,
+ bbox: list[float],
+ content: str,
+ score: float,
+) -> Block:
+ return Block(
+ idx=idx,
+ type=block_type,
+ bbox=bbox,
+ content=content,
+ format=ContentFormat.LATEX if block_type == BlockType.FORMULA else ContentFormat.TEXT,
+ layout_score=score,
+ )
+
+
+def _systematic_page(extra_text_blocks: int = 6) -> list[Block]:
+ blocks = [
+ _block(0, BlockType.TEXT, [0, 0, 10, 10], "$x$", 0.9),
+ _block(1, BlockType.FORMULA, [0, 0, 10, 10], "x", 0.2),
+ _block(2, BlockType.TEXT, [0, 20, 10, 30], r"\[y\]", 0.3),
+ _block(3, BlockType.FORMULA, [0, 20, 10, 30], "y", 0.8),
+ ]
+ blocks.extend(
+ _block(
+ 4 + index,
+ BlockType.TEXT,
+ [20, index, 30, index + 1],
+ f"unique {index}",
+ 0.9,
+ )
+ for index in range(extra_text_blocks)
+ )
+ return blocks
+
+
+def test_normalizes_one_outer_math_wrapper_and_whitespace():
+ assert normalize_cross_category_content(" $$\n x + y \n$$ ") == "x+y"
+ assert normalize_cross_category_content(r"\[ x + y \]") == "x+y"
+ assert normalize_cross_category_content("$$$x$$$") == "$x$"
+
+
+def test_dedupes_multiple_dense_groups_by_score():
+ result = dedupe_systematic_cross_category_blocks(_systematic_page())
+
+ assert [block.idx for block in result] == [0, 3, 4, 5, 6, 7, 8, 9]
+
+
+def test_equal_score_preserves_earlier_reading_order_position():
+ blocks = _systematic_page()
+ blocks[0].layout_score = blocks[1].layout_score = 0.9
+
+ result = dedupe_systematic_cross_category_blocks(blocks)
+
+ assert blocks[0] in result
+ assert blocks[1] not in result
+
+
+def test_isolated_or_sparse_duplicates_are_unchanged():
+ isolated = _systematic_page()[:2]
+ sparse = _systematic_page(extra_text_blocks=17)
+
+ assert dedupe_systematic_cross_category_blocks(isolated) is isolated
+ assert dedupe_systematic_cross_category_blocks(sparse) is sparse
+
+
+def test_requires_cross_category_exact_bbox_and_content():
+ blocks = _systematic_page()
+ blocks[1].bbox = [0, 0, 11, 10]
+ blocks[3].content = "z"
+
+ assert dedupe_systematic_cross_category_blocks(blocks) is blocks
+
+
+def test_missing_layout_scores_tie_at_zero():
+ blocks = _systematic_page()
+ for block in blocks[:4]:
+ block.layout_score = None
+
+ result = dedupe_systematic_cross_category_blocks(blocks)
+
+ assert [block.idx for block in result[:2]] == [0, 2]
diff --git a/tests/unit/test_demo_api.py b/tests/unit/test_demo_api.py
new file mode 100644
index 0000000..6cdb219
--- /dev/null
+++ b/tests/unit/test_demo_api.py
@@ -0,0 +1,363 @@
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+import json
+import os
+import threading
+import time
+
+import cv2
+import numpy as np
+import pytest
+from fastapi.testclient import TestClient
+
+from oxr.config.settings import settings
+from oxr.pipeline import orchestrator
+from oxr.pipeline.errors import PipelineError
+from oxr.server import demo_api
+from oxr.server.app import app
+from oxr.server.demo_store import DemoStore
+
+
+def demo_store(monkeypatch, tmp_path):
+ store = DemoStore(tmp_path / "jobs")
+ monkeypatch.setattr(demo_api, "DemoStore", lambda: store)
+ monkeypatch.setattr(settings.layout_analyze_model, "url", "http://layout:8081")
+ monkeypatch.setattr(settings.oxr_model, "url", "http://oxr:8080/v1")
+ return store
+
+
+def image_bytes():
+ success, encoded = cv2.imencode(".png", np.full((18, 24, 3), 255, dtype=np.uint8))
+ assert success
+ return encoded.tobytes()
+
+
+def wait_status(client, job_id, expected):
+ for _ in range(200):
+ response = client.get(f"/v1/demo/jobs/{job_id}")
+ assert response.status_code == 200
+ data = response.json()["data"]
+ if data["status"] == expected:
+ return data
+ time.sleep(0.01)
+ pytest.fail(f"Expected {expected}; received {data}")
+
+
+def test_demo_upload_publishes_page_before_result_and_decodes_only_once(monkeypatch, demo_store):
+ release = threading.Event()
+ decode_calls = []
+ original_decode = orchestrator._decode_document_images
+
+ def decode(data, name):
+ decode_calls.append(name)
+ return original_decode(data, name)
+
+ async def process(images, name, formats, **kwargs):
+ assert len(images) == 1 and images[0].shape == (18, 24, 3)
+ assert formats == ["markdown", "json"]
+ assert kwargs["demo"] is True
+ assert kwargs["started_at"] > 0
+ while not release.is_set():
+ await asyncio.sleep(0.01)
+ (kwargs["asset_dir"] / "block-test.png").write_bytes(image_bytes())
+ return {
+ "file_name": name,
+ "outputs": {"markdown": "# Example", "json": {"pages": []}},
+ "metadata": {"page_num": 1},
+ "demo_pages": [{"page_num": 0, "markdown": "# Example", "blocks": []}],
+ }
+
+ monkeypatch.setattr(orchestrator, "_decode_document_images", decode)
+ monkeypatch.setattr(orchestrator, "process_decoded_document", process)
+ with TestClient(app) as client:
+ response = client.post("/v1/demo/jobs", files={"file": ("example.png", image_bytes(), "image/png")})
+ assert response.status_code == 200
+ job_id = response.json()["data"]["id"]
+ state = wait_status(client, job_id, "processing")
+ assert state["pages"][0]["page_size"] == {"w": 24, "h": 18}
+ assert "assets" not in state and "expires_at" not in state and "outputs" not in state
+ page = client.get(state["pages"][0]["image_url"])
+ assert page.status_code == 200 and page.headers["content-type"] == "image/png"
+ assert client.get(f"/v1/demo/jobs/{job_id}/result").status_code == 409
+ release.set()
+ state = wait_status(client, job_id, "success")
+ result = client.get(state["result_url"]).json()["data"]
+ assert result["outputs"]["markdown"] == "# Example"
+ assert result["demo_pages"][0]["page_num"] == 0
+ assert client.get(f"/v1/demo/jobs/{job_id}/assets/block-test.png").status_code == 200
+ assert decode_calls == ["example.png"]
+
+
+def test_demo_pdf_pages_use_decoder_dimensions(monkeypatch, demo_store):
+ called = []
+
+ def decode(data, name):
+ called.append((data, name))
+ return [np.zeros((20, 30, 3), dtype=np.uint8), np.zeros((40, 15, 3), dtype=np.uint8)]
+
+ async def process(images, name, formats, **kwargs):
+ return {"file_name": name, "outputs": {}, "metadata": {}, "demo_pages": []}
+
+ monkeypatch.setattr(orchestrator, "_decode_document_images", decode)
+ monkeypatch.setattr(orchestrator, "process_decoded_document", process)
+ with TestClient(app) as client:
+ response = client.post("/v1/demo/jobs", files={"file": ("two.pdf", b"pdf")})
+ state = wait_status(client, response.json()["data"]["id"], "success")
+ assert called == [(b"pdf", "two.pdf")]
+ assert [page["page_size"] for page in state["pages"]] == [{"w": 30, "h": 20}, {"w": 15, "h": 40}]
+ assert [page["page_num"] for page in state["pages"]] == [0, 1]
+
+
[email protected]("submitted, expected", [
+ ({}, {"temperature": 0.0, "top_p": 1.0, "repetition_penalty": 1.0}),
+ ({"temperature": "0.4", "top_p": "0.8", "repetition_penalty": "1.3"},
+ {"temperature": 0.4, "top_p": 0.8, "repetition_penalty": 1.3}),
+ ({"temperature": "0", "top_p": "0", "repetition_penalty": "0.1"},
+ {"temperature": 0.0, "top_p": 0.0, "repetition_penalty": 0.1}),
+ ({"temperature": "2", "top_p": "1", "repetition_penalty": "2"},
+ {"temperature": 2.0, "top_p": 1.0, "repetition_penalty": 2.0}),
+ ({"top_p": "0.5"}, {"temperature": 0.0, "top_p": 0.5, "repetition_penalty": 1.0}),
+])
+def test_demo_model_options_reach_pipeline(monkeypatch, demo_store, submitted, expected):
+ received = []
+
+ async def process(images, name, formats, **kwargs):
+ received.append(kwargs["model_options"])
+ return {"file_name": name, "outputs": {}, "metadata": {}, "demo_pages": []}
+
+ monkeypatch.setattr(orchestrator, "process_decoded_document", process)
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/demo/jobs", data=submitted,
+ files={"file": ("example.png", image_bytes(), "image/png")},
+ )
+ assert response.status_code == 200
+ wait_status(client, response.json()["data"]["id"], "success")
+ assert received == [expected]
+
+
[email protected]("name, value", [
+ (name, value)
+ for name in ("temperature", "top_p", "repetition_penalty")
+ for value in ("", " ", "hot", "NaN", "Infinity", "-Infinity")
+] + [
+ ("temperature", "-0.1"), ("temperature", "2.1"),
+ ("top_p", "-0.1"), ("top_p", "1.1"),
+ ("repetition_penalty", "0"), ("repetition_penalty", "0.09"),
+ ("repetition_penalty", "2.1"),
+])
+def test_demo_rejects_invalid_model_options_before_creating_job(monkeypatch, demo_store, name, value):
+ def unexpected_create(*_args):
+ pytest.fail("Invalid model parameters must not create a job")
+
+ monkeypatch.setattr(demo_store, "create", unexpected_create)
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/demo/jobs", data={name: value},
+ files={"file": ("example.png", image_bytes(), "image/png")},
+ )
+ assert response.status_code == 422
+ body = response.json()
+ assert body["code"] == 422
+ assert name in body["message"] and "between" in body["message"]
+ assert body["data"] is None
+ assert not app.state.demo_tasks
+ assert not list(demo_store.root.glob("*/manifest.json"))
+
+
+def test_upload_errors_and_decode_failure(monkeypatch, demo_store):
+ with TestClient(app) as client:
+ assert client.post("/v1/demo/jobs", files={"file": ("bad.txt", b"data")}).status_code == 415
+ assert client.post("/v1/demo/jobs", files={"file": ("empty.png", b"")}).status_code == 422
+ monkeypatch.setattr(demo_api, "MAX_UPLOAD_BYTES", 2)
+ assert client.post("/v1/demo/jobs", files={"file": ("big.png", b"123")}).status_code == 413
+ monkeypatch.setattr(demo_api, "MAX_UPLOAD_BYTES", 100)
+ response = client.post("/v1/demo/jobs", files={"file": ("bad.png", b"not an image")})
+ state = wait_status(client, response.json()["data"]["id"], "failed")
+ assert "Unable to decode" in state["error"]
+ assert state["result_url"] is None
+ assert client.get("/v1/demo/jobs/unknown").status_code == 404
+
+
+def test_assets_are_job_scoped_allowlisted_and_expire(demo_store):
+ first = demo_store.create("same.png")["id"]
+ second = demo_store.create("same.png")["id"]
+ directory = demo_store.job_dir(first) / "images"
+ (directory / "page-0000.png").write_bytes(image_bytes())
+ (directory / "secret.png").write_bytes(b"not registered")
+ demo_store.update(first, assets=["page-0000.png"])
+ with TestClient(app) as client:
+ assert client.get(f"/v1/demo/jobs/{first}/assets/page-0000.png").status_code == 200
+ assert client.get(f"/v1/demo/jobs/{second}/assets/page-0000.png").status_code == 404
+ assert client.get(f"/v1/demo/jobs/{first}/assets/secret.png").status_code == 404
+ assert client.get(f"/v1/demo/jobs/{first}/assets/manifest.json").status_code == 404
+ manifest_path = demo_store.job_dir(first) / "manifest.json"
+ manifest = json.loads(manifest_path.read_text())
+ manifest["expires_at"] = 0
+ manifest_path.write_text(json.dumps(manifest))
+ os.utime(demo_store.job_dir(first) / "lease", (0, 0))
+ assert client.get(f"/v1/demo/jobs/{first}").status_code == 404
+ assert client.get(f"/v1/demo/jobs/{first}/assets/page-0000.png").status_code == 404
+ demo_store.cleanup()
+ assert not demo_store.job_dir(first).exists()
+
+
+def test_demo_serves_bundled_ui_and_keeps_parse_routes(demo_store):
+ with TestClient(app) as client:
+ for url in ("/demo", "/demo/"):
+ response = client.get(url)
+ assert response.status_code == 200
+ assert "<title>OXR Online Demo</title>" in response.text
+ response = client.get("/demo/assets/style/index.css")
+ assert response.status_code == 200
+ assert response.headers["content-type"].startswith("text/css")
+ paths = client.get("/openapi.json").json()["paths"]
+ assert {"/v1/parse/sync", "/v1/parse/async", "/v1/parse/async_check"} <= paths.keys()
+ assert paths["/v1/demo/jobs"]["post"]["tags"] == ["OXR Online Demo"]
+
+
+def test_asset_symlink_cannot_escape_job_directory(demo_store, tmp_path):
+ job_id = demo_store.create("a.png")["id"]
+ secret = tmp_path / "outside.png"
+ secret.write_bytes(b"private")
+ link = demo_store.job_dir(job_id) / "images" / "linked.png"
+ try:
+ link.symlink_to(secret)
+ except OSError:
+ pytest.skip("Symlinks are unavailable on this platform.")
+ demo_store.update(job_id, assets=["linked.png"])
+ with pytest.raises(KeyError):
+ demo_store.asset(job_id, "linked.png")
+ demo_store.publish_result(job_id, {"metadata": {}})
+ assert "linked.png" not in demo_store.get(job_id)["assets"]
+
+
+def test_storage_exhaustion_marks_failed_and_removes_page_payload(monkeypatch, demo_store):
+ original_check = demo_store.ensure_capacity
+ checks = []
+
+ def check(*args):
+ checks.append(True)
+ if len(checks) > 1:
+ raise OSError("Temporary storage is full.")
+ return original_check(*args)
+
+ monkeypatch.setattr(demo_store, "ensure_capacity", check)
+ with TestClient(app) as client:
+ response = client.post("/v1/demo/jobs", files={"file": ("a.png", image_bytes())})
+ job_id = response.json()["data"]["id"]
+ state = wait_status(client, job_id, "failed")
+ assert state["error"] == "Temporary storage is unavailable or full. Try again later."
+ assert state["pages"] == []
+ assert not (demo_store.job_dir(job_id) / "images").exists()
+
+
[email protected]("stage", ["decode", "recognition", "publish"])
[email protected]("error_type", [RuntimeError, PipelineError, OSError])
+def test_demo_failures_hide_backend_details(monkeypatch, demo_store, caplog, stage, error_type):
+ details = ("/synthetic-private/checkpoint.pth", "http://backend.example.invalid", "DUMMY_CREDENTIAL")
+
+ def fail(*args, **kwargs):
+ raise error_type(" ".join(details))
+
+ async def process(*args, **kwargs):
+ if stage == "recognition":
+ fail()
+ return {"metadata": {}, "outputs": {"markdown": "ok"}, "demo_pages": []}
+
+ monkeypatch.setattr(orchestrator, "process_decoded_document", process)
+ if stage == "decode":
+ monkeypatch.setattr(orchestrator, "_decode_document_images", fail)
+ elif stage == "publish":
+ monkeypatch.setattr(demo_store, "publish_result", fail)
+ with TestClient(app) as client:
+ submit = client.post("/v1/demo/jobs", files={"file": ("demo.png", image_bytes(), "image/png")})
+ assert submit.status_code == 200
+ job_id = submit.json()["data"]["id"]
+ state = wait_status(client, job_id, "failed")
+ expected = (
+ "Temporary storage is unavailable or full. Try again later."
+ if error_type is OSError else "Unable to process this document. Please try again later."
+ )
+ assert state["error"] == expected
+ assert client.get(f"/v1/demo/jobs/{job_id}/result").status_code == 409
+ persisted = (demo_store.job_dir(job_id) / "manifest.json").read_text()
+ assert all(detail not in json.dumps(state) and detail not in persisted for detail in details)
+ if error_type is OSError:
+ assert state["pages"] == []
+ assert not (demo_store.job_dir(job_id) / "images").exists()
+
+ assert "Demo processing failed" in caplog.text
+ assert all(detail not in caplog.text for detail in details)
+
+
+def test_demo_invalid_image_keeps_safe_decode_message(demo_store):
+ with TestClient(app) as client:
+ submit = client.post("/v1/demo/jobs", files={"file": ("broken.png", b"not-an-image")})
+ state = wait_status(client, submit.json()["data"]["id"], "failed")
+ assert state["error"] == "Unable to decode document into valid page images."
+
+
+def test_demo_result_conflict_hides_exception_details(monkeypatch, demo_store):
+ def fail(*args, **kwargs):
+ raise ValueError("/synthetic-private/result.json DUMMY_CREDENTIAL")
+
+ job_id = demo_store.create("demo.png")["id"]
+ monkeypatch.setattr(demo_store, "result", fail)
+ with TestClient(app) as client:
+ response = client.get(f"/v1/demo/jobs/{job_id}/result")
+ assert response.status_code == 409
+ assert response.json() == {"code": 409, "message": "The document is not ready yet.", "data": None}
+
+
+def test_shared_store_heartbeat_preserves_published_manifest(tmp_path):
+ owner = DemoStore(tmp_path)
+ reader = DemoStore(tmp_path)
+ job_id = owner.create("a.png")["id"]
+ owner.update(job_id, status="processing", pages=[{"page_num": 0}])
+ reader.keep_alive(job_id)
+ owner.publish_result(job_id, {"metadata": {}, "outputs": {"markdown": "ok"}})
+ reader.keep_alive(job_id)
+ assert reader.get(job_id)["status"] == "success"
+ assert reader.get(job_id)["pages"] == [{"page_num": 0}]
+ assert reader.result(job_id)["outputs"]["markdown"] == "ok"
+
+
+def test_shared_store_capacity_admission_and_http_unavailable(monkeypatch, demo_store, tmp_path):
+ stores = [DemoStore(tmp_path / "limited", max_jobs=1) for _ in range(2)]
+
+ def create(store):
+ try:
+ return store.create("a.png")
+ except OSError:
+ return None
+
+ with ThreadPoolExecutor(2) as executor:
+ results = list(executor.map(create, stores))
+ assert sum(result is not None for result in results) == 1
+
+ monkeypatch.setattr(demo_store, "max_jobs", 0)
+ with TestClient(app) as client:
+ assert client.post("/v1/demo/jobs", files={"file": ("a.png", image_bytes())}).status_code == 503
+
+
+def test_shutdown_waits_for_decoder_then_marks_job_failed(monkeypatch, demo_store):
+ entered = threading.Event()
+
+ def decode(data, name):
+ entered.set()
+ time.sleep(0.15)
+ return [np.zeros((4, 4, 3), dtype=np.uint8)]
+
+ async def process(*args, **kwargs):
+ await asyncio.sleep(10)
+
+ monkeypatch.setattr(orchestrator, "_decode_document_images", decode)
+ monkeypatch.setattr(orchestrator, "process_decoded_document", process)
+ with TestClient(app) as client:
+ response = client.post("/v1/demo/jobs", files={"file": ("a.png", b"a")})
+ job_id = response.json()["data"]["id"]
+ assert entered.wait(1)
+ assert demo_store.get(job_id)["status"] == "failed"
+ assert "server stopped" in demo_store.get(job_id)["error"]
diff --git a/tests/unit/test_demo_pipeline.py b/tests/unit/test_demo_pipeline.py
new file mode 100644
index 0000000..f51dbc9
--- /dev/null
+++ b/tests/unit/test_demo_pipeline.py
@@ -0,0 +1,236 @@
+import asyncio
+from copy import deepcopy
+from unittest.mock import patch
+
+import numpy as np
+import pytest
+
+from oxr.pipeline import orchestrator
+from oxr.pipeline.assembler import assemble_markdown
+from oxr.pipeline.image_assets import ImageAssets, image_assets
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.assembly_postprocess import blocks_to_markdown_with_ranges
+from oxr.pipeline.postprocess.formula_postprocess import space_markdown_math
+from oxr.pipeline.postprocess.picture_postprocess import postprocess_picture
+from oxr.pipeline.postprocess.table_images import image_data_url
+
+
+def block(idx, kind, content, role=""):
+ return Block(idx, kind, [0, 0, 20, 20], content, ContentFormat.MARKDOWN,
+ generated_role=role)
+
+
+def test_source_ranges_preserve_assembly_and_empty_blocks():
+ blocks = [
+ block(0, BlockType.TITLE, "Heading"),
+ block(2, BlockType.FORMULA, r"a\\(b)"),
+ block(3, BlockType.TEXT, "(1)", "formula_numbering"),
+ block(5, BlockType.TABLE, "<table>\n<tr><td>A</td></tr>\n</table>"),
+ block(6, BlockType.PICTURE, "![](/image.png)"),
+ block(9, BlockType.CODE_BLOCK, "```python\nx = 1\n```"),
+ block(11, BlockType.FOOTNOTE, "Note"),
+ block(12, BlockType.TEXT, " "),
+ ]
+ markdown, ranges = blocks_to_markdown_with_ranges(list(reversed(blocks)))
+ assert space_markdown_math(markdown) == assemble_markdown([blocks])
+ lines = markdown.splitlines(keepends=True)
+ assert "".join(lines[slice(*ranges[0])]) == "# Heading\n"
+ assert "".join(lines[slice(*ranges[2])]) == "$$\na\\\\(b)\n$$\n"
+ assert ranges[3][0] == ranges[2][1] # Tight formula-number separator.
+ assert "".join(lines[slice(*ranges[5])]).startswith("<table>")
+ assert "".join(lines[slice(*ranges[11])]) == "[^11]: Note\n"
+ assert 12 not in ranges
+
+
+def test_request_scoped_images_are_isolated_and_include_table_images(tmp_path):
+ async def save(name):
+ token = image_assets.set(ImageAssets(tmp_path / name, f"/assets/{name}/"))
+ try:
+ image = np.zeros((20, 20, 3), dtype=np.uint8)
+ picture = await asyncio.to_thread(
+ postprocess_picture, block(0, BlockType.PICTURE, ""), image, "same.png", 0,
+ )
+ table_url = await asyncio.to_thread(image_data_url, image)
+ return picture.content, table_url
+ finally:
+ image_assets.reset(token)
+
+ async def run():
+ return await asyncio.gather(save("one"), save("two"))
+
+ results = asyncio.run(run())
+ for name, (picture, table_url) in zip(("one", "two"), results):
+ assert f"/assets/{name}/" in picture
+ assert table_url.startswith(f"/assets/{name}/")
+ assert len(list((tmp_path / name).glob("*.png"))) == 2
+ assert image_assets.get() is None
+
+
+def test_decoded_demo_pipeline_keeps_page_ranges_without_decoding(monkeypatch, tmp_path):
+ images = [np.zeros((30, 40, 3), dtype=np.uint8)]
+
+ async def layout(_images, _options):
+ return [[block(0, BlockType.TITLE, "Title"), block(1, BlockType.TEXT, "")]]
+
+ async def recognize(blocks, *_args):
+ return blocks
+
+ def unexpected_decode(*_args):
+ raise AssertionError("Already decoded demo pages must never be decoded again")
+
+ monkeypatch.setattr(orchestrator, "_decode_document_images", unexpected_decode)
+ monkeypatch.setattr(orchestrator, "analyze_layouts", layout)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(orchestrator.settings.layout_analyze_model, "provides_reading_order", True)
+ result = asyncio.run(orchestrator.process_decoded_document(
+ images, "test.pdf", ["markdown", "json"], demo=True,
+ asset_dir=tmp_path, asset_url_prefix="/assets/",
+ ))
+ page = result["demo_pages"][0]
+ assert page["page_size"] == {"w": 40, "h": 30}
+ assert page["markdown"] == result["outputs"]["markdown"]
+ assert page["blocks"][0]["start_line"] == 0
+ assert page["blocks"][0]["end_line"] == 1
+ assert page["blocks"][1]["start_line"] is None
+ assert image_assets.get() is None
+
+
[email protected]("provides_reading_order", [False, True])
[email protected]("with_body", [False, True])
[email protected]("full_overlap_dedupe", [False, True])
+def test_demo_header_footer_are_layout_only(
+ monkeypatch, provides_reading_order, with_body, full_overlap_dedupe,
+):
+ header = block(0, BlockType.PAGE_HEADER, "Header must not be rendered")
+ header.bbox = [0, 0, 40, 4]
+ footer = block(2, BlockType.PAGE_FOOTER, "Footer must not be rendered")
+ footer.bbox = [0, 26, 40, 30]
+ formula = block(1, BlockType.FORMULA, "x = 1")
+ formula.bbox = [0, 8, 20, 18]
+ formula.text_before = "(1)"
+ formula.text_after = "(2)"
+ captured = {}
+
+ async def layout(_images, _options):
+ return [[header, formula, footer] if with_body else [header, footer]]
+
+ async def recognize(pages, *_args):
+ captured["recognition"] = [[b.type for b in page] for page in pages]
+ return pages
+
+ async def reading_order(pages, *_args):
+ captured["reading_order"] = [[b.type for b in page] for page in pages]
+ return [list(range(len(page))) for page in pages]
+
+ monkeypatch.setattr(orchestrator, "analyze_layouts", layout)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(orchestrator, "resolve_reading_orders", reading_order)
+ monkeypatch.setattr(
+ orchestrator.settings.pipeline, "full_overlap_dedupe", full_overlap_dedupe,
+ )
+ monkeypatch.setattr(
+ orchestrator.settings.layout_analyze_model,
+ "provides_reading_order", provides_reading_order,
+ )
+ result = asyncio.run(orchestrator.process_decoded_document(
+ [np.zeros((30, 40, 3), dtype=np.uint8)], "test.png", ["markdown", "json"],
+ demo=True,
+ ))
+
+ expected_inputs = [[BlockType.FORMULA] if with_body else []]
+ assert captured["recognition"] == expected_inputs
+ if not provides_reading_order:
+ assert captured["reading_order"] == expected_inputs
+ page = result["demo_pages"][0]
+ margins = page["blocks"][-2:]
+ assert [b["type"] for b in margins] == ["Page-header", "Page-footer"]
+ assert [b["bbox"] for b in margins] == [header.bbox, footer.bbox]
+ assert all(b["content"] == "" for b in margins)
+ assert all(b["start_line"] is None and b["end_line"] is None for b in margins)
+ assert len({b["idx"] for b in page["blocks"]}) == len(page["blocks"])
+ assert page["markdown"] == result["outputs"]["markdown"]
+ assert "Header" not in page["markdown"] and "Footer" not in page["markdown"]
+ body = result["outputs"]["json"]["pages"][0]["blocks"]
+ assert all(b["type"] not in {"Page-header", "Page-footer"} for b in body)
+ assert [
+ {key: value for key, value in b.items() if key not in {"start_line", "end_line"}}
+ for b in page["blocks"][:-2]
+ ] == body
+ if with_body:
+ assert [b["idx"] for b in body] == [1]
+ assert [b["idx"] for b in margins] == [3, 4]
+ assert all(b["start_line"] is not None for b in page["blocks"][:-2])
+ assert "(1)" in page["markdown"] and "(2)" in page["markdown"]
+ assert body[0]["type"] == "Formula"
+ assert body[0]["content"] == r"x = 1\leqno (1)\tag{2}"
+ region = page["blocks"][0]
+ selected = "\n".join(page["markdown"].splitlines()[
+ region["start_line"]:region["end_line"]
+ ])
+ assert "(1)" in selected and "(2)" in selected and "x = 1" in selected
+ else:
+ assert page["markdown"] == ""
+ assert body == []
+
+
+def test_demo_orphan_numbering_is_a_note_without_a_layout_region(monkeypatch):
+ formula = block(0, BlockType.FORMULA, "x = 1")
+ formula.text_after = "(48)"
+
+ async def layout(*_args):
+ return [[formula]]
+
+ async def recognize(pages, *_args):
+ return pages
+
+ monkeypatch.setattr(orchestrator, "analyze_layouts", layout)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(orchestrator.settings.pipeline, "full_overlap_dedupe", True)
+ monkeypatch.setattr(orchestrator.settings.layout_analyze_model, "provides_reading_order", True)
+ monkeypatch.setattr(orchestrator, "_dedupe_full_page", lambda _raw, blocks, _image: blocks[1:])
+ result = asyncio.run(orchestrator.process_decoded_document(
+ [np.zeros((30, 40, 3), dtype=np.uint8)], "test.png", ["markdown", "json"],
+ demo=True,
+ ))
+ page = result["demo_pages"][0]
+ api_page = result["outputs"]["json"]["pages"][0]
+ assert page["blocks"] == api_page["blocks"] == []
+ assert page["unattached_formula_numbering"] == api_page["unattached_formula_numbering"] == [
+ {"idx": 1, "content": "(48)"},
+ ]
+ assert page["markdown"] == result["outputs"]["markdown"] == "(48)\n"
+
+
+def test_markdown_delimiter_repair_preserves_entire_json_and_demo_regions(monkeypatch):
+ from oxr.pipeline.postprocess import assembly_postprocess
+
+ formula = block(0, BlockType.FORMULA, r"I=$ $\sum a_n")
+ formula.text_after = "(57)"
+ text = block(1, BlockType.TEXT, "Keep $5 and code `x$ $y` intact")
+ text.bbox = [0, 21, 30, 29]
+
+ async def layout(*_args):
+ return [[deepcopy(formula), deepcopy(text)]]
+
+ async def recognize(pages, *_args):
+ return pages
+
+ monkeypatch.setattr(orchestrator, "analyze_layouts", layout)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(orchestrator.settings.pipeline, "full_overlap_dedupe", False)
+ monkeypatch.setattr(orchestrator.settings.layout_analyze_model, "provides_reading_order", True)
+
+ def run():
+ return asyncio.run(orchestrator.process_decoded_document(
+ [np.zeros((30, 40, 3), dtype=np.uint8)], "test.png", ["markdown", "json"], demo=True,
+ ))
+
+ with patch.object(assembly_postprocess, "clean_formula_markdown_delimiters", side_effect=lambda s: s):
+ baseline = run()
+ candidate = run()
+ assert candidate["outputs"]["json"] == baseline["outputs"]["json"]
+ assert candidate["demo_pages"][0]["blocks"] == baseline["demo_pages"][0]["blocks"]
+ assert r"I= \sum a_n" in candidate["outputs"]["markdown"]
+ assert "(57)" in candidate["outputs"]["markdown"]
+ assert text.content in candidate["outputs"]["markdown"]
+ assert candidate["demo_pages"][0]["markdown"] == candidate["outputs"]["markdown"]
diff --git a/tests/unit/test_error_propagation.py b/tests/unit/test_error_propagation.py
new file mode 100644
index 0000000..70ff211
--- /dev/null
+++ b/tests/unit/test_error_propagation.py
@@ -0,0 +1,203 @@
+import asyncio
+
+import numpy as np
+import pytest
+from fastapi.testclient import TestClient
+
+from oxr.config.settings import settings
+from oxr.pipeline.errors import PipelineError
+from oxr.pipeline.layout import analyze_layouts
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.recognition import recognize_block
+from oxr.server.app import app
+from oxr.server import routes
+
+
+INVALID_DOCUMENT_MESSAGE = "Unable to decode document into valid page images."
+
+
[email protected](autouse=True)
+def configure_server_model_urls(monkeypatch):
+ monkeypatch.setattr(settings.layout_analyze_model, "url", "http://layout:8081")
+ monkeypatch.setattr(settings.oxr_model, "url", "http://oxr:8080/v1")
+
+
+class UpstreamServiceUnavailableError(Exception):
+ status_code = 503
+
+
+def test_layout_failure_raises_pipeline_error(monkeypatch):
+ async def fail_layout(_encoded_images):
+ raise UpstreamServiceUnavailableError("Error code: 503")
+
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.request_batch", fail_layout)
+ monkeypatch.setattr(settings.layout_analyze_model, "retry_times", 1)
+
+ with np.testing.assert_raises(PipelineError) as exc_info:
+ asyncio.run(analyze_layouts([np.zeros((8, 8, 3), dtype=np.uint8)]))
+
+ assert exc_info.exception.status_code == 503
+ assert "Layout analysis failed" in str(exc_info.exception)
+
+
+def test_layout_timeout_has_clear_error_message(monkeypatch):
+ async def fail_layout(_encoded_images):
+ raise TimeoutError()
+
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.request_batch", fail_layout)
+ monkeypatch.setattr(settings.layout_analyze_model, "retry_times", 1)
+ monkeypatch.setattr(settings.layout_analyze_model, "timeout", 7)
+
+ with np.testing.assert_raises(PipelineError) as exc_info:
+ asyncio.run(analyze_layouts([np.zeros((8, 8, 3), dtype=np.uint8)]))
+
+ assert "Timeout after 7s" in str(exc_info.exception)
+
+
+def test_recognition_failure_raises_pipeline_error(monkeypatch):
+ async def fail_recognize(_image, _model_options=None):
+ raise UpstreamServiceUnavailableError("Error code: 503")
+
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_text", fail_recognize)
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+
+ block = Block(
+ idx=0,
+ type=BlockType.TEXT,
+ bbox=[0, 0, 8, 8],
+ content="",
+ format=ContentFormat.TEXT,
+ )
+
+ with np.testing.assert_raises(PipelineError) as exc_info:
+ asyncio.run(
+ recognize_block(
+ block,
+ np.zeros((8, 8, 3), dtype=np.uint8),
+ asyncio.Semaphore(1),
+ "demo.png",
+ 0,
+ )
+ )
+
+ assert exc_info.exception.status_code == 503
+ assert "Recognition failed for block 0" in str(exc_info.exception)
+
+
+def test_parse_sync_returns_somark_error_envelope(monkeypatch):
+ async def fail_process_document(
+ _file_bytes,
+ _file_name,
+ _output_formats,
+ keep_header_footer=False,
+ model_options=None,
+ element_formats=None,
+ ):
+ raise PipelineError("Layout analysis failed after 1 attempts: Error code: 503", status_code=503)
+
+ monkeypatch.setattr(routes, "process_document", fail_process_document)
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={"api_key": "dummy"},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 1137
+ assert response.json()["message"] == "Unable to process this document. Please try again later."
+ assert response.json()["warnings"] == []
+
+
[email protected]("mode", ["sync", "async"])
[email protected]("error_type", [RuntimeError, PipelineError, OSError])
+def test_parse_failures_hide_backend_details(monkeypatch, caplog, mode, error_type):
+ details = ("/synthetic-private/checkpoint.pth", "http://backend.example.invalid", "DUMMY_CREDENTIAL")
+
+ async def fail_process_document(*args, **kwargs):
+ raise error_type(" ".join(details))
+
+ monkeypatch.setattr(routes, "process_document", fail_process_document)
+ with TestClient(app) as client:
+ response = client.post(
+ f"/v1/parse/{mode}",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={"api_key": "dummy"},
+ )
+ assert response.status_code == 200
+ if mode == "async":
+ assert response.json()["code"] == 0
+ response = client.post(
+ "/v1/parse/async_check",
+ data={"api_key": "dummy", "task_id": response.json()["data"]["task_id"]},
+ )
+ assert response.status_code == 200
+ assert response.json()["code"] == 0
+ assert response.json()["data"]["status"] == "failed"
+ message = response.json()["data"]["error"]
+ else:
+ assert response.json()["code"] == 1137
+ assert response.json()["warnings"] == []
+ assert response.json()["data"] is None
+ message = response.json()["message"]
+
+ assert message == "Unable to process this document. Please try again later."
+ assert "Document processing failed" in caplog.text
+ assert error_type.__name__ in caplog.text
+ assert all(detail not in response.text and detail not in caplog.text for detail in details)
+
+
+def test_decoder_exception_keeps_safe_public_message(monkeypatch):
+ from oxr.pipeline import orchestrator
+
+ def fail_pdf_decode(*args, **kwargs):
+ raise RuntimeError("/synthetic-private/checkpoint.pth DUMMY_CREDENTIAL")
+
+ monkeypatch.setattr(orchestrator, "pdf_to_images", fail_pdf_decode)
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("broken.pdf", b"fake-pdf", "application/pdf")},
+ data={"api_key": "dummy"},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 1137
+ assert response.json()["message"] == INVALID_DOCUMENT_MESSAGE
+ assert "synthetic-private" not in response.text and "DUMMY_CREDENTIAL" not in response.text
+
+
[email protected]("file_bytes", [b"", b"not-an-image"])
+def test_parse_sync_returns_stable_error_for_invalid_image_bytes(file_bytes):
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("broken.png", file_bytes, "image/png")},
+ data={"api_key": "dummy"},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 1137
+ assert response.json()["message"] == INVALID_DOCUMENT_MESSAGE
+ assert "OpenCV" not in response.json()["message"]
+
+
[email protected]("file_bytes", [b"", b"not-an-image"])
+def test_parse_async_records_stable_error_for_invalid_image_bytes(file_bytes):
+ with TestClient(app) as client:
+ submit = client.post(
+ "/v1/parse/async",
+ files={"file": ("broken.png", file_bytes, "image/png")},
+ data={"api_key": "dummy"},
+ )
+ task_id = submit.json()["data"]["task_id"]
+ response = client.post(
+ "/v1/parse/async_check",
+ data={"api_key": "dummy", "task_id": task_id},
+ )
+
+ assert submit.json()["code"] == 0
+ assert response.json()["data"]["status"] == "failed"
+ assert response.json()["data"]["error"] == INVALID_DOCUMENT_MESSAGE
+ assert "OpenCV" not in response.json()["data"]["error"]
diff --git a/tests/unit/test_exact_text_dedupe.py b/tests/unit/test_exact_text_dedupe.py
new file mode 100644
index 0000000..29a5f86
--- /dev/null
+++ b/tests/unit/test_exact_text_dedupe.py
@@ -0,0 +1,93 @@
+from copy import deepcopy
+
+import pytest
+
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.exact_text_dedupe import dedupe_exact_textual_blocks
+
+
+def _block(kind, score=0.8, **updates):
+ fields = dict(
+ idx=17, type=kind, bbox=[0.0, 0.0, 100.0, 10.0], content="a",
+ format=ContentFormat.TEXT, layout_score=score,
+ )
+ fields.update(updates)
+ return Block(**fields)
+
+
+def test_triple_keeps_original_winner_and_surrounding_order_without_mutation():
+ blocks = [
+ _block(BlockType.FORMULA, idx=40),
+ _block(BlockType.TEXT, 0.6, idx=30),
+ _block(BlockType.CAPTION, 0.7, idx=20),
+ _block(BlockType.TITLE, 0.9, idx=10),
+ _block(BlockType.TEXT, idx=1, content="other"),
+ ]
+ before = deepcopy(blocks)
+ result = dedupe_exact_textual_blocks(blocks)
+ assert [block.idx for block in result] == [40, 10, 1]
+ assert all(a is b for a, b in zip(result, [blocks[0], blocks[3], blocks[4]]))
+ assert blocks == before
+ assert dedupe_exact_textual_blocks(result) is result
+
+
+ (BlockType.TEXT, BlockType.CAPTION),
+ (BlockType.TEXT, BlockType.TITLE),
+ (BlockType.CAPTION, BlockType.TITLE),
+])
+def test_each_cross_category_pair(kinds):
+ blocks = [_block(kinds[0], 0.9), _block(kinds[1], 0.5)]
+ assert dedupe_exact_textual_blocks(blocks) == [blocks[0]]
+
+
+def test_equal_score_uses_list_position_instead_of_idx_or_type_priority():
+ blocks = [_block(BlockType.CAPTION, idx=9), _block(BlockType.TITLE, idx=0)]
+ assert dedupe_exact_textual_blocks(blocks)[0] is blocks[0]
+
+
[email protected]("score", [None, float("nan"), float("inf"), True, "0.9"])
+def test_missing_or_invalid_confidence_skips_whole_group(score):
+ blocks = [_block(BlockType.TEXT), _block(BlockType.CAPTION, score)]
+ assert dedupe_exact_textual_blocks(blocks) is blocks
+
+
[email protected]("field,value", [
+ ("bbox", [0, 0, 100, 10.00001]), ("content", "a "), ("content", "A"),
+ ("format", ContentFormat.MARKDOWN), ("generated_role", "heading"),
+ ("text_before", "# "), ("text_after", "\n"),
+])
+def test_different_geometry_text_or_assembly_fields_are_preserved(field, value):
+ blocks = [_block(BlockType.TEXT), _block(BlockType.CAPTION, **{field: value})]
+ assert dedupe_exact_textual_blocks(blocks) is blocks
+
+
+ None, [0, 0, 100], [0, 0, 100, float("nan")],
+ [0, 0, 100, float("inf")], [0, 0, "100", 10],
+ [0, 0, 0, 10], [0, 10, 100, 0],
+])
+def test_invalid_geometry_is_preserved(bbox):
+ blocks = [_block(BlockType.TEXT, bbox=bbox), _block(BlockType.CAPTION, bbox=bbox)]
+ assert dedupe_exact_textual_blocks(blocks) is blocks
+
+
+def test_same_class_multiplicity_does_not_guess_a_winner():
+ blocks = [_block(BlockType.TEXT), _block(BlockType.TEXT), _block(BlockType.TITLE)]
+ assert dedupe_exact_textual_blocks(blocks) is blocks
+
+
+def test_unrelated_classes_and_blank_text_are_preserved():
+ blocks = [_block(kind) for kind in BlockType if kind != BlockType.CAPTION and kind != BlockType.TITLE]
+ assert dedupe_exact_textual_blocks(blocks) is blocks
+ blanks = [_block(BlockType.TEXT, content=" "), _block(BlockType.CAPTION, content=" ")]
+ assert dedupe_exact_textual_blocks(blanks) is blanks
+
+
+def test_invalid_group_does_not_block_an_independent_valid_pair():
+ blocks = [
+ _block(BlockType.TEXT, None), _block(BlockType.CAPTION),
+ _block(BlockType.TITLE, 0.9, content="second"),
+ _block(BlockType.TEXT, 0.2, content="second"),
+ ]
+ assert dedupe_exact_textual_blocks(blocks) == blocks[:3]
diff --git a/tests/unit/test_formula_postprocess.py b/tests/unit/test_formula_postprocess.py
new file mode 100644
index 0000000..747fdbe
--- /dev/null
+++ b/tests/unit/test_formula_postprocess.py
@@ -0,0 +1,241 @@
+import asyncio
+
+import numpy as np
+import pytest
+
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.orchestrator import process_document
+from oxr.pipeline.postprocess.assembly_postprocess import blocks_to_markdown
+from oxr.pipeline.postprocess import formula_postprocess
+from oxr.pipeline.postprocess.formula_postprocess import (
+ clean_formula_markdown_delimiters,
+ postprocess_formula,
+ space_latex_row_breaks,
+ space_markdown_math,
+)
+
+
[email protected](("before", "after"), [
+ (r"I= $ $\sum_{n=1}^{N}a_n", r"I= \sum_{n=1}^{N}a_n"),
+ (r"x=$ $1+ $ $2", "x= 1+ 2"),
+ ("x=$\n$1", "x=\n1"),
+ (r"$x=1$", "x=1"),
+ (r"x=\text{cost \$5}+$ $y", r"x=\text{cost \$5}+ y"),
+ (r"x=\text{$a$}+$ $y", r"x=\text{$a$}+ y"),
+])
+def test_markdown_delimiter_cleanup_preserves_tokens_lines_and_is_idempotent(before, after):
+ assert clean_formula_markdown_delimiters(before) == after
+ assert clean_formula_markdown_delimiters(after) == after
+ assert before.count("\n") == after.count("\n")
+
+
[email protected]("content", [
+ r"x=1$", r"x$y$z", r"x$$ $$y", r"x={$ $y}",
+ r"x=1$ and $y=2", r"$x$ 与 $y$", r"\text{price $5}",
+ r"x=1\$ \$y=2", r"\verb|$ $|", r"x=\text{unclosed$ $y",
+ "% $ $\nx=1", r"x=1$ $y={2", r"a\\[15pt]b",
+ r"x=1$ $y=2$ $z=3", "x=1$\n$y=2", r"x=$ $1$ $y=2",
+])
+def test_markdown_delimiter_cleanup_leaves_ambiguous_or_protected_content_intact(content):
+ assert clean_formula_markdown_delimiters(content) == content
+
+
+def _formula_block() -> Block:
+ return Block(0, BlockType.FORMULA, [0, 0, 1, 1], "", ContentFormat.TEXT)
+
+
+def test_formula_postprocess_strips_inline_dollar_wrappers():
+ block = postprocess_formula(_formula_block(), "$x^2 + y^2 = z^2$")
+
+ assert block.content == "x^2 + y^2 = z^2"
+ assert block.format == ContentFormat.LATEX
+
+
+def test_formula_postprocess_strips_display_dollar_wrappers():
+ block = postprocess_formula(_formula_block(), "$$\nx^2 + y^2 = z^2\n$$")
+
+ assert block.content == "x^2 + y^2 = z^2"
+
+
+def test_formula_postprocess_spaces_row_break_before_parenthesis():
+ block = postprocess_formula(_formula_block(), r"a&b\\(c)&d")
+
+ assert block.content == r"a&b\\ (c)&d"
+
+
+def test_markdown_formula_spacing_preserves_code_html_and_incomplete_math():
+ markdown = (
+ r"$a\\(b)$ `code $c\\(d)$` <span>$e\\(f)$</span> "
+ r"$incomplete\\(g)"
+ )
+
+ assert space_markdown_math(markdown) == (
+ r"$a\\ (b)$ `code $c\\(d)$` <span>$e\\ (f)$</span> "
+ r"$incomplete\\(g)"
+ )
+
+
+ ("before", "after"),
+ [
+ (r"a\\(b)", r"a\\ (b)"),
+ (r"a\\)b", r"a\\ )b"),
+ (r"a\\[2pt](b)", r"a\\[2pt](b)"),
+ (r"\(a\)", r"\(a\)"),
+ (r"\text{literal {a}\\(b)}\\(x)", r"\text{literal {a}\\(b)}\\ (x)"),
+ (r"\text{incomplete\\(b)", r"\text{incomplete\\(b)"),
+ (r"\%a\\(b)", r"\%a\\ (b)"),
+ ("%a\\\\(b)\nx\\\\(y)", "%a\\\\(b)\nx\\\\ (y)"),
+ (r"a\\{b}", r"a\\ {b}"),
+ (r"\text{a\\{b}}", r"\text{a\\{b}}"),
+ ],
+)
+def test_latex_row_break_spacing_is_conservative_and_idempotent(before, after):
+ assert space_latex_row_breaks(before) == after
+ assert space_latex_row_breaks(after) == after
+
+
+ "text",
+ [
+ r"$$$x\\(y)$$$",
+ r"$ x\\(y)$",
+ r"$x\\(y) $",
+ r"<!-- $x\\(y)$ -->",
+ r"``literal ` $a\\(b)$``",
+ ],
+)
+def test_markdown_formula_spacing_leaves_ambiguous_ranges_unchanged(text):
+ assert space_markdown_math(text) == text
+
+
+def test_currency_does_not_pair_across_html_or_hide_later_formula():
+ table = "<table><tr><td>10,000 mm btu's,$ per mm btu</td><td>$10</td></tr></table>"
+ encoded = "&lt;td&gt;$ per unit&lt;/td&gt;&lt;td&gt;$10&lt;/td&gt;"
+ later_formula = r"price $ per unit and later $x\\(y)$"
+
+ assert space_markdown_math(table) == table
+ assert space_markdown_math(encoded) == encoded
+ assert space_markdown_math(later_formula) == r"price $ per unit and later $x\\ (y)$"
+
+def test_formula_assembly_uses_single_display_math_wrapper():
+ block = postprocess_formula(_formula_block(), "$x^2 + y^2 = z^2$")
+
+ markdown = blocks_to_markdown([block])
+
+ assert markdown == "$$\nx^2 + y^2 = z^2\n$$\n"
+
+
+def test_formula_postprocess_moves_tag_number_after_formula():
+ block = postprocess_formula(_formula_block(), "$y=x+1 \\tag{1}$")
+
+ assert block.content == "y=x+1"
+ assert getattr(block, "text_after", "") == "(1)"
+
+
+def test_formula_postprocess_moves_tag_star_number_after_formula_without_parentheses():
+ block = postprocess_formula(_formula_block(), "$y=x+1 \\tag*{1}$")
+
+ assert block.content == "y=x+1"
+ assert getattr(block, "text_after", "") == "1"
+
+
+def test_formula_postprocess_moves_eqno_number_after_formula():
+ block = postprocess_formula(_formula_block(), "$y=x+1 \\eqno (1)$")
+
+ assert block.content == "y=x+1"
+ assert getattr(block, "text_after", "") == "(1)"
+
+
+def test_formula_postprocess_moves_leqno_number_before_formula():
+ block = postprocess_formula(_formula_block(), "$y=x+1 \\leqno (1)$")
+
+ assert block.content == "y=x+1"
+ assert getattr(block, "text_before", "") == "(1)"
+
+
+def test_formula_numbering_expansion_creates_text_blocks_with_contiguous_indexes():
+ block = postprocess_formula(_formula_block(), "$y=x+1 \\leqno (L) \\tag{R}$")
+ expand = getattr(formula_postprocess, "expand_formula_numbering_blocks", None)
+
+ assert expand is not None
+ expanded = expand([block])
+
+ assert [item.idx for item in expanded] == [0, 1, 2]
+ assert [item.type for item in expanded] == [
+ BlockType.TEXT,
+ BlockType.FORMULA,
+ BlockType.TEXT,
+ ]
+ assert [item.content for item in expanded] == ["(L)", "y=x+1", "(R)"]
+ assert all(item.bbox == block.bbox for item in expanded)
+ assert expanded[0].format == ContentFormat.TEXT
+ assert expanded[2].format == ContentFormat.TEXT
+
+
+def test_formula_numbering_markdown_stays_outside_formula_environment():
+ block = postprocess_formula(_formula_block(), "$y=x+1 \\tag{1}$")
+ expand = getattr(formula_postprocess, "expand_formula_numbering_blocks", None)
+
+ assert expand is not None
+ markdown = blocks_to_markdown(expand([block]))
+
+ assert markdown == "$$\ny=x+1\n$$\n(1)\n"
+
+
+def test_process_document_keeps_numbering_in_one_json_region_and_unchanged_markdown(monkeypatch):
+ async def fake_analyze_layouts(_images, _model_options=None):
+ return [[_formula_block()]]
+
+ async def fake_recognize_pages(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ block = pages_blocks[0][0]
+ return [[postprocess_formula(block, "$y=x+1 \\tag{1}$")]]
+
+ monkeypatch.setattr("oxr.pipeline.orchestrator.cv2.imdecode", lambda *_args: np.zeros((4, 4, 3), dtype=np.uint8))
+ monkeypatch.setattr("oxr.pipeline.orchestrator.analyze_layouts", fake_analyze_layouts)
+ monkeypatch.setattr("oxr.pipeline.orchestrator.recognize_pages", fake_recognize_pages)
+ monkeypatch.setattr("oxr.config.settings.settings.debug", True)
+
+ result = asyncio.run(process_document(b"image", "page.png", ["json", "markdown"], keep_header_footer=True))
+ blocks = result["outputs"]["json"]["pages"][0]["blocks"]
+
+ assert [(block["idx"], block["type"], block["content"], block["format"]) for block in blocks] == [
+ (0, "Formula", r"y=x+1\tag{1}", "latex"),
+ ]
+ assert result["outputs"]["markdown"] == "$$\ny=x+1\n$$\n(1)\n"
+ assert result["metadata"]["debug_stats"]["total_blocks"] == 1
+
+
[email protected]("raw", [r"x\tag{48}", r"x\tag*{A}", r"x\leqno (L) \tag{R}"])
+def test_numbered_json_round_trip_preserves_numbers_without_mutating_markdown(raw):
+ from copy import deepcopy
+ from oxr.pipeline.postprocess.json_postprocess import serialize_final_blocks
+
+ block = postprocess_formula(_formula_block(), raw)
+ expanded = formula_postprocess.expand_formula_numbering_blocks([block])
+ original = deepcopy(expanded)
+ expected_md = blocks_to_markdown(expanded)
+ records, notes = serialize_final_blocks(expanded)
+ assert len(records) == 1 and records[0]["bbox"] == block.bbox and notes == []
+ restored = postprocess_formula(_formula_block(), records[0]["content"])
+ assert (restored.content, restored.text_before, restored.text_after) == (
+ block.content, block.text_before, block.text_after,
+ )
+ assert expanded == original and blocks_to_markdown(expanded) == expected_md
+
+
+def test_numbering_without_a_surviving_formula_becomes_a_note_not_a_fake_region():
+ from oxr.pipeline.postprocess.json_postprocess import serialize_final_blocks
+
+ expanded = formula_postprocess.expand_formula_numbering_blocks([
+ postprocess_formula(_formula_block(), r"x\tag{48}"),
+ ])
+ records, notes = serialize_final_blocks(expanded[1:])
+ assert records == [] and notes == [{"idx": 1, "content": "(48)"}]
diff --git a/tests/unit/test_full_overlap_dedupe.py b/tests/unit/test_full_overlap_dedupe.py
new file mode 100644
index 0000000..dd9818e
--- /dev/null
+++ b/tests/unit/test_full_overlap_dedupe.py
@@ -0,0 +1,286 @@
+from copy import deepcopy
+
+import pytest
+import numpy as np
+
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.full_overlap_dedupe import dedupe_full_overlaps
+
+
+def _block(kind=BlockType.TEXT, box=None, score=0.8, idx=17, content="different"):
+ return Block(
+ idx, kind, [0, 0, 10, 10] if box is None else box, content,
+ ContentFormat.TEXT, layout_score=score,
+ )
+
+
[email protected]("kind", list(BlockType))
+def test_containment_requires_a_parent_with_verified_textual_content(kind):
+ outer = _block(kind, [0, 0, 100, 100], 0.2)
+ inner = _block(BlockType.FORMULA, [20, 20, 60, 60], 0.99)
+ expected = [inner, outer] if kind in {BlockType.PICTURE, BlockType.TABLE} else [outer]
+ assert dedupe_full_overlaps([inner, outer]) == expected
+
+
[email protected]("kind", list(BlockType))
+def test_equal_geometry_across_every_category_uses_confidence_for_duplicates(kind):
+ lower = _block(kind, score=0.2, content="same text")
+ higher = _block(BlockType.TEXT, score=0.9, content="same text")
+ expected = [lower, higher] if kind in {BlockType.CODE_BLOCK, BlockType.TABLE} else [higher]
+ assert dedupe_full_overlaps([lower, higher]) == expected
+
+
[email protected]("kind", list(BlockType))
+def test_tiny_overlap_across_every_category_keeps_both_blocks(kind):
+ a = _block(kind, [0, 0, 10, 10], 0.2)
+ b = _block(BlockType.FORMULA, [9, 9, 20, 20], 0.9)
+ assert dedupe_full_overlaps([a, b]) == [a, b]
+
+
+def test_formula_text_overlap_uses_confidence_despite_distinct_recognized_content():
+ formula = _block(BlockType.FORMULA, score=0.7, content="x^{2}")
+ text = _block(BlockType.TEXT, score=0.9, content="incorrect but higher confidence")
+ assert dedupe_full_overlaps([formula, text]) == [text]
+ formula.layout_score = 0.99
+ assert dedupe_full_overlaps([formula, text]) == [formula]
+
+
[email protected]("outer_kind, inner_kind", [
+ (BlockType.TEXT, BlockType.FORMULA),
+ (BlockType.FORMULA, BlockType.TEXT),
+ (BlockType.FORMULA, BlockType.FORMULA),
+])
+def test_formula_containment_does_not_require_recognized_content_inclusion(outer_kind, inner_kind):
+ outer = _block(outer_kind, [0, 0, 100, 100], 0.2, content="parent OCR")
+ inner = _block(inner_kind, [10, 10, 90, 30], 0.99, content="different child OCR")
+ assert dedupe_full_overlaps([inner, outer]) == [outer]
+
+
+def test_formula_overlap_exemption_keeps_code_and_generated_numbers():
+ formula = _block(BlockType.FORMULA, score=0.99, content="x^{2}")
+ code = _block(BlockType.CODE_BLOCK, score=0.7, content="unique code")
+ number = _block(BlockType.TEXT, score=0.7, content="(48)")
+ number.generated_role = "formula_numbering"
+ assert dedupe_full_overlaps([code, formula, number]) == [code, formula, number]
+ code.layout_score = 1.0
+ assert dedupe_full_overlaps([code, formula, number]) == [code, formula, number]
+
+
+def test_nested_containment_retains_text_not_verified_by_visual_parent():
+ blocks = [
+ _block(BlockType.FORMULA, [10, 10, 20, 20], 0.99),
+ _block(BlockType.PICTURE, [0, 0, 100, 100], None),
+ _block(BlockType.CAPTION, [5, 5, 30, 30], 0.9),
+ ]
+ assert dedupe_full_overlaps(blocks) == [blocks[1], blocks[2]]
+
+
+def test_outer_box_wins_when_child_shares_some_boundaries():
+ outer = _block(box=[0, 0, 10, 20], score=0.1)
+ inner = _block(box=[0, 0, 10, 10], score=1.0)
+ assert dedupe_full_overlaps([inner, outer]) == [outer]
+
+
+def test_containment_does_not_make_tiny_overlaps_delete_parents():
+ outer = _block(box=[0, 0, 10, 10], score=0.2)
+ inner = _block(box=[0, 0, 2, 2], score=0.99)
+ crossing = _block(box=[9, 9, 20, 20], score=0.9)
+ assert dedupe_full_overlaps([outer, inner, crossing]) == [outer, crossing]
+
+
+def test_suppressed_intermediary_cannot_suppress_nonoverlapping_neighbor():
+ # A-B and B-C qualify as duplicates; A-C does not. Only survivors suppress.
+ a = _block(box=[0, 0, 100, 100], score=0.9)
+ b = _block(box=[5, 0, 105, 100], score=0.8)
+ c = _block(box=[10, 0, 110, 100], score=0.7)
+ assert dedupe_full_overlaps([c, b, a]) == [c, a]
+
+
+def test_ties_keep_page_position_instead_of_smaller_idx():
+ a = _block(BlockType.TEXT, idx=99)
+ b = _block(BlockType.FORMULA, idx=0)
+ assert dedupe_full_overlaps([a, b]) == [a]
+
+
[email protected]("box", [[10, 0, 20, 10], [10, 10, 20, 20], [20, 0, 30, 10]])
+def test_touching_or_disjoint_boxes_are_preserved(box):
+ blocks = [_block(), _block(box=box)]
+ assert dedupe_full_overlaps(blocks) is blocks
+
+
[email protected]("score", [None, float("nan"), float("inf"), True, "0.9"])
[email protected]("box", [[0, 0, 10, 10], [9, 0, 19, 10]])
+def test_unknown_or_invalid_scores_are_not_guessed(score, box):
+ blocks = [_block(score=1.0), _block(box=box, score=score)]
+ assert dedupe_full_overlaps(blocks) is blocks
+
+
+ [0, 0, 0, 10], [10, 0, 0, 10], [0, 0, 10],
+ [0, 0, "10", 10], [0, 0, True, 10], [0, 0, 10, float("nan")],
+ [0, 0, 10, float("inf")],
+])
+def test_invalid_geometry_cannot_delete_valid_blocks(box):
+ blocks = [_block(box=box, score=1.0), _block(score=0.1)]
+ assert dedupe_full_overlaps(blocks) is blocks
+
+
+def test_retained_fields_references_and_page_order_are_unchanged():
+ blocks = [
+ _block(box=[20, 0, 30, 10], idx=88),
+ _block(BlockType.FORMULA, score=1.0, idx=5, content="x"),
+ _block(BlockType.TEXT, score=0.2, idx=6, content="x"),
+ ]
+ blocks[1].format = ContentFormat.LATEX
+ blocks[1].text_after = "(1)"
+ before = deepcopy(blocks)
+ result = dedupe_full_overlaps(blocks)
+ assert result[0] is blocks[0] and result[1] is blocks[1]
+ assert blocks == before
+ assert dedupe_full_overlaps(result) is result
+
+
[email protected]("box, suppressed", [
+ ([5, 0, 105, 100], True),
+ ([5.01, 0, 105.01, 100], False),
+ ([0.01, 0, 124.9875, 100], True),
+ ([0.01, 0, 124.99, 100], False),
+])
+def test_overlap_requires_both_iou_and_smaller_coverage_thresholds(box, suppressed):
+ a = _block(BlockType.PICTURE, box=[0, 0, 100, 100], score=0.2)
+ b = _block(BlockType.PICTURE, box=box, score=0.9)
+ image = np.full((100, 130), 255, dtype=np.uint8)
+ image[40:60, 40:60] = 0
+ result = dedupe_full_overlaps([a, b], image)
+ assert result == ([b] if suppressed else [a, b])
+
+
+def test_children_reappear_when_their_parent_is_suppressed():
+ parent = _block(BlockType.PICTURE, [0, 0, 100, 100], 0.2)
+ child = _block(BlockType.PICTURE, [99.1, 10, 99.9, 20], 0.99)
+ crossing = _block(BlockType.PICTURE, [-1, 0, 99, 100], 0.9)
+ image = np.full((100, 100), 255, dtype=np.uint8)
+ image[40:60, 40:60] = 0
+ assert dedupe_full_overlaps([parent, child, crossing], image) == [child, crossing]
+
+
[email protected]("kind", [BlockType.TEXT, BlockType.CAPTION, BlockType.TITLE, BlockType.CHEMICAL_STRUCTURE, BlockType.FORMULA])
[email protected]("visual", [BlockType.PICTURE, BlockType.TABLE])
+def test_textual_boxes_cannot_preserve_independent_visual_content(kind, visual):
+ parent = _block(kind, [0, 0, 100, 100], 0.95, content="Section heading")
+ child = _block(visual, [10, 10, 90, 90], 0.8, content="Unique visual content")
+ assert dedupe_full_overlaps([parent, child]) == [parent, child]
+ child.bbox = parent.bbox.copy()
+ expected = [parent] if visual == BlockType.PICTURE and kind != BlockType.CHEMICAL_STRUCTURE else [parent, child]
+ assert dedupe_full_overlaps([parent, child]) == expected
+
+
+def test_tables_require_identical_complete_content_and_structure():
+ a = _block(BlockType.TABLE, score=0.9, content='<table><tr><td>123</td></tr></table>')
+ b = _block(BlockType.TABLE, score=0.8, content=a.content)
+ assert dedupe_full_overlaps([a, b]) == [a]
+ b.content = '<table><tr><td colspan="2">123</td></tr></table>'
+ assert dedupe_full_overlaps([a, b]) == [a, b]
+ b.content = a.content
+ b.text_after = 'Unique note'
+ assert dedupe_full_overlaps([a, b]) == [a, b]
+
+
+def test_shifted_picture_requires_ink_coverage_not_just_geometry():
+ left = _block(BlockType.PICTURE, [0, 0, 100, 100], 0.8, content='![](left.png)')
+ right = _block(BlockType.PICTURE, [5, 0, 105, 100], 0.9, content='![](right.png)')
+ image = np.full((100, 105, 3), 255, dtype=np.uint8)
+ image[40:60, 50:60] = 0
+ assert dedupe_full_overlaps([left, right]) == [left, right]
+ assert dedupe_full_overlaps([left, right], image) == [right]
+ image[40:60, 0:4] = 0
+ assert dedupe_full_overlaps([left, right], image) == [left, right]
+
+
+def test_complete_text_containment_ignores_recognition_differences():
+ outer = _block(box=[0, 0, 100, 100], content="题干")
+ child = _block(box=[10, 10, 50, 20], content="A B C D")
+ empty = _block(box=[10, 30, 50, 40], content="")
+ assert dedupe_full_overlaps([outer, child, empty]) == [outer]
+
+
[email protected]("scale", [0.25, 1.0, 4.0])
+def test_height_relative_tolerance_is_scale_invariant_and_content_proven(scale):
+ outer = _block(box=[0, 0, 100, 100], content="题干 选项")
+ child = _block(box=[-2, 10, 50, 20], content="选 项")
+ for block in [outer, child]:
+ block.bbox = [coordinate * scale for coordinate in block.bbox]
+ assert dedupe_full_overlaps([outer, child]) == [outer]
+ child.bbox[0] = -2.01 * scale
+ assert dedupe_full_overlaps([outer, child]) == [outer, child]
+ child.bbox[0] = -1 * scale
+ child.content = "另一行"
+ assert dedupe_full_overlaps([outer, child]) == [outer, child]
+
+
+def test_near_containment_requires_coverage_and_preserves_the_formula_exemption():
+ parent = _block(box=[0, 0, 100, 100], content="x")
+ child = _block(BlockType.FORMULA, [-2, 10, 4, 30], content="x")
+ assert dedupe_full_overlaps([parent, child]) == [parent, child]
+ child.bbox = [-2, 10, 8, 30]
+ assert dedupe_full_overlaps([parent, child]) == [parent]
+ child.content = "y"
+ assert dedupe_full_overlaps([parent, child]) == [parent]
+ child.type = BlockType.TEXT
+ assert dedupe_full_overlaps([parent, child]) == [parent, child]
+
+
+def test_complete_containment_does_not_bypass_code_or_number_protection():
+ parent = _block(box=[0, 0, 100, 100], content="正文")
+ code = _block(BlockType.CODE_BLOCK, [10, 10, 50, 30], content="unique code")
+ number = _block(BlockType.TEXT, [10, 40, 50, 50], content="(48)")
+ number.generated_role = "formula_numbering"
+ assert dedupe_full_overlaps([parent, code, number]) == [parent, code, number]
+
+
+def test_equivalent_chemical_equation_notations_are_deduplicated():
+ canonical = _block(score=0.9, content=r"\ce{C6H12O6 -> 2C2H5OH + 2CO2}")
+ text = _block(score=0.7, content=r"$\mathrm{C}_{6}\mathrm{H}_{12}\mathrm{O}_{6}\to2\mathrm{C}_{2}\mathrm{H}_{5}\mathrm{OH}+2\mathrm{CO}_{2}$")
+ assert dedupe_full_overlaps([canonical, text]) == [canonical]
+ text.content = text.content.replace("2\\mathrm{CO}", "3\\mathrm{CO}")
+ assert dedupe_full_overlaps([canonical, text]) == [canonical, text]
+
+
+def test_image_paths_cannot_prove_text_coverage_and_code_indentation_is_preserved():
+ picture = _block(BlockType.PICTURE, [0, 0, 100, 100], content='![](/tmp/A.png)')
+ text = _block(box=[10, 10, 20, 20], content='A')
+ assert dedupe_full_overlaps([picture, text]) == [picture, text]
+ a = _block(BlockType.CODE_BLOCK, score=0.9, content='if ok:\n run()\nfinish()')
+ b = _block(BlockType.CODE_BLOCK, score=0.7, content='if ok:\n run()\n finish()')
+ assert dedupe_full_overlaps([a, b]) == [a, b]
+
+
[email protected]("kind", [BlockType.CAPTION, BlockType.TEXT, BlockType.FORMULA])
+def test_chemical_structure_cannot_absorb_independent_contained_text(kind):
+ structure = _block(BlockType.CHEMICAL_STRUCTURE, [0, 0, 100, 100], content=r"$\smiles{CC(=O)O}$")
+ label = _block(kind, [10, 70, 40, 90], content="(a) Aspirin")
+ assert dedupe_full_overlaps([structure, label]) == [structure, label]
+
+
[email protected]("kind", [BlockType.TEXT, BlockType.TITLE, BlockType.CAPTION, BlockType.FORMULA, BlockType.CODE_BLOCK])
[email protected]("scores", [(0.99, 0.1), (None, None)])
+def test_exact_picture_text_alias_prefers_text_independent_of_confidence(kind, scores):
+ picture = _block(BlockType.PICTURE, score=scores[0], content="![](label.png)")
+ text = _block(kind, score=scores[1], content="例3 变式4")
+ assert dedupe_full_overlaps([picture, text]) == [text]
+ assert dedupe_full_overlaps([text, picture]) == [text]
+ text.bbox[2] += 0.01
+ assert dedupe_full_overlaps([picture, text]) == [picture, text]
+
+
+def test_picture_alias_requires_surviving_nonempty_text_not_generated_number():
+ picture = _block(BlockType.PICTURE, score=0.99, content="![](label.png)")
+ text = _block(score=0.7, content=" ")
+ assert dedupe_full_overlaps([picture, text]) == [picture, text]
+ text.content = "(48)"
+ text.generated_role = "formula_numbering"
+ assert dedupe_full_overlaps([picture, text]) == [picture, text]
+ text.generated_role = ""
+ text.content = "same text"
+ crossing = _block(box=[0.1, 0, 10.1, 10], score=0.9, content="same text")
+ assert dedupe_full_overlaps([picture, text, crossing]) == [picture, crossing]
diff --git a/tests/unit/test_image_utils.py b/tests/unit/test_image_utils.py
new file mode 100644
index 0000000..45976b5
--- /dev/null
+++ b/tests/unit/test_image_utils.py
@@ -0,0 +1,20 @@
+import numpy as np
+
+from oxr.utils.image import crop_image
+
+
+def test_crop_image_rounds_float_coordinates_to_nearest_pixel() -> None:
+ image = np.arange(6 * 7, dtype=np.uint8).reshape(6, 7)
+
+ crop = crop_image(image, [1.6, 1.6, 5.6, 4.6])
+
+ np.testing.assert_array_equal(crop, image[2:5, 2:6])
+
+
+def test_crop_image_clamps_rounded_coordinates_and_returns_copy() -> None:
+ image = np.arange(4 * 5, dtype=np.uint8).reshape(4, 5)
+
+ crop = crop_image(image, [-0.4, -0.4, 6.2, 5.2])
+
+ np.testing.assert_array_equal(crop, image)
+ assert not np.shares_memory(crop, image)
diff --git a/tests/unit/test_layout_client.py b/tests/unit/test_layout_client.py
new file mode 100644
index 0000000..f090f10
--- /dev/null
+++ b/tests/unit/test_layout_client.py
@@ -0,0 +1,80 @@
+import asyncio
+
+import cv2
+import httpx
+import numpy as np
+import pytest
+
+from oxr.config.settings import LayoutAnalyzeModelConfig
+from oxr.model.layout_client import LayoutAnalyzeClient
+
+
+def test_encode_images_returns_lossless_pngs():
+ client = LayoutAnalyzeClient(LayoutAnalyzeModelConfig(url="http://layout:8081"))
+ image = np.arange(8 * 8 * 3, dtype=np.uint8).reshape(8, 8, 3)
+
+ encoded = client.encode_images([image])
+
+ assert len(encoded) == 1
+ assert encoded[0].startswith(b"\x89PNG\r\n\x1a\n")
+ decoded = cv2.imdecode(np.frombuffer(encoded[0], dtype=np.uint8), cv2.IMREAD_COLOR)
+ assert np.array_equal(decoded, image)
+
+
+def test_request_batch_posts_repeated_images_to_inference_endpoint():
+ requests = []
+ native_response = {
+ "status": "success",
+ "params": {},
+ "data": {"labels": [[], []], "boxes": [[], []], "scores": [[], []]},
+ }
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ return httpx.Response(200, json=native_response)
+
+ transport = httpx.MockTransport(handler)
+ http_client = httpx.AsyncClient(transport=transport, base_url="http://layout:8081")
+ client = LayoutAnalyzeClient(
+ LayoutAnalyzeModelConfig(url="http://layout:8081/"),
+ http_client=http_client,
+ )
+
+ result = asyncio.run(client.request_batch([b"first", b"second"]))
+ asyncio.run(client.aclose())
+
+ assert result == native_response
+ assert requests[0].url == httpx.URL("http://layout:8081/inference")
+ assert requests[0].content.count(b'name="images"') == 2
+ assert requests[0].content.count(b".png") == 2
+ assert requests[0].content.count(b"application/octet-stream") == 2
+ assert http_client.is_closed is True
+
+
+ "configured_url",
+ [
+ "http://layout:8081/v1/layout/analyze",
+ "http://layout:8081/v1/layout/analyze/",
+ ],
+)
+def test_request_batch_replaces_legacy_layout_endpoint_with_inference(configured_url):
+ requests = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ return httpx.Response(200, json={})
+
+ http_client = httpx.AsyncClient(
+ transport=httpx.MockTransport(handler),
+ base_url="http://layout:8081",
+ )
+ client = LayoutAnalyzeClient(
+ LayoutAnalyzeModelConfig(url=configured_url),
+ http_client=http_client,
+ )
+
+ asyncio.run(client.request_batch([b"page"]))
+ asyncio.run(client.aclose())
+
+ assert requests[0].url == httpx.URL("http://layout:8081/inference")
diff --git a/tests/unit/test_layout_pipeline.py b/tests/unit/test_layout_pipeline.py
new file mode 100644
index 0000000..d8c3cfa
--- /dev/null
+++ b/tests/unit/test_layout_pipeline.py
@@ -0,0 +1,224 @@
+import asyncio
+
+import numpy as np
+import pytest
+
+from oxr.config.settings import LayoutAnalyzeModelConfig, settings
+from oxr.pipeline.errors import PipelineError
+from oxr.pipeline.layout import analyze_layouts
+
+
+def response_for(encoded_images):
+ labels = []
+ boxes = []
+ scores = []
+ for image in encoded_images:
+ marker = image[0] if len(image) == 1 else 0
+ labels.append([3])
+ boxes.append([[marker, 1, marker + 1, 2]])
+ scores.append([0.99])
+ return {
+ "status": "success",
+ "params": {},
+ "data": {"labels": labels, "boxes": boxes, "scores": scores},
+ }
+
+
+def test_analyze_layouts_passes_configured_score_threshold(monkeypatch):
+ captured = {}
+
+ def encode_images(_images):
+ return [b"page"]
+
+ async def request_batch(encoded_images):
+ return response_for(encoded_images)
+
+ def parse_layout_batch(payload, image_sizes, score_threshold, nms_iou_threshold):
+ captured["payload"] = payload
+ captured["image_sizes"] = image_sizes
+ captured["score_threshold"] = score_threshold
+ captured["nms_iou_threshold"] = nms_iou_threshold
+ return [[]]
+
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.encode_images", encode_images)
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.request_batch", request_batch)
+ monkeypatch.setattr("oxr.pipeline.layout.parse_layout_batch", parse_layout_batch)
+ monkeypatch.setattr(settings.layout_analyze_model, "score_threshold", 0.73)
+ monkeypatch.setattr(settings.layout_analyze_model, "retry_times", 1)
+
+ result = asyncio.run(analyze_layouts([np.zeros((8, 9, 3), dtype=np.uint8)]))
+
+ assert result == [[]]
+ assert captured["image_sizes"] == [(9, 8)]
+ assert captured["score_threshold"] == 0.73
+ assert captured["nms_iou_threshold"] == 0.6
+
+
+def test_analyze_layouts_batches_concurrently_and_restores_document_order(monkeypatch):
+ images = [np.full((10, 10, 3), index, dtype=np.uint8) for index in range(5)]
+ calls = []
+
+ def encode_images(batch):
+ return [bytes([int(image[0, 0, 0])]) for image in batch]
+
+ async def request_batch(encoded_images):
+ calls.append(tuple(encoded_images))
+ await asyncio.sleep(0.01 if encoded_images[0] == b"\x00" else 0)
+ return response_for(encoded_images)
+
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.encode_images", encode_images)
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.request_batch", request_batch)
+ monkeypatch.setattr(settings.layout_analyze_model, "batch_size", 2)
+ monkeypatch.setattr(settings.layout_analyze_model, "max_concurrency", 3)
+ monkeypatch.setattr(settings.layout_analyze_model, "retry_times", 1)
+
+ blocks = asyncio.run(analyze_layouts(images))
+
+ assert sorted(calls) == [(b"\x00", b"\x01"), (b"\x02", b"\x03"), (b"\x04",)]
+ assert len(blocks) == 5
+ assert [page[0].bbox for page in blocks] == [
+ [0.0, 1.0, 1.0, 2.0],
+ [1.0, 1.0, 2.0, 2.0],
+ [2.0, 1.0, 3.0, 2.0],
+ [3.0, 1.0, 4.0, 2.0],
+ [4.0, 1.0, 5.0, 2.0],
+ ]
+
+
+def test_analyze_layouts_encodes_once_and_retries_whole_batch(monkeypatch):
+ images = [np.zeros((10, 10, 3), dtype=np.uint8), np.ones((10, 10, 3), dtype=np.uint8)]
+ encode_calls = 0
+ requests = []
+
+ def encode_images(batch):
+ nonlocal encode_calls
+ encode_calls += 1
+ return [b"first", b"second"]
+
+ async def request_batch(encoded_images):
+ requests.append(tuple(encoded_images))
+ if len(requests) == 1:
+ raise RuntimeError("transient layout failure")
+ return response_for(encoded_images)
+
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.encode_images", encode_images)
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.request_batch", request_batch)
+ monkeypatch.setattr(settings.layout_analyze_model, "batch_size", 2)
+ monkeypatch.setattr(settings.layout_analyze_model, "retry_times", 2)
+ original_sleep = asyncio.sleep
+ monkeypatch.setattr("oxr.pipeline.layout.asyncio.sleep", lambda _seconds: original_sleep(0))
+
+ assert len(asyncio.run(analyze_layouts(images))) == 2
+ assert encode_calls == 1
+ assert requests == [(b"first", b"second"), (b"first", b"second")]
+
+
+def test_request_semaphore_is_limited_and_released_during_backoff(monkeypatch):
+ images = [np.full((10, 10, 3), index, dtype=np.uint8) for index in range(2)]
+ active = 0
+ peak = 0
+ first_batch_attempts = 0
+ second_request_started = asyncio.Event()
+
+ def encode_images(batch):
+ return [bytes([int(image[0, 0, 0])]) for image in batch]
+
+ async def request_batch(encoded_images):
+ nonlocal active, peak, first_batch_attempts
+ active += 1
+ peak = max(peak, active)
+ try:
+ if encoded_images == [b"\x00"]:
+ first_batch_attempts += 1
+ if first_batch_attempts == 1:
+ raise RuntimeError("retry me")
+ second_request_started.set()
+ return response_for(encoded_images)
+ finally:
+ active -= 1
+
+ original_sleep = asyncio.sleep
+
+ async def immediate_backoff(_seconds):
+ await original_sleep(0)
+ assert second_request_started.is_set()
+
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.encode_images", encode_images)
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.request_batch", request_batch)
+ monkeypatch.setattr(settings.layout_analyze_model, "batch_size", 1)
+ monkeypatch.setattr(settings.layout_analyze_model, "max_concurrency", 1)
+ monkeypatch.setattr(settings.layout_analyze_model, "retry_times", 2)
+ monkeypatch.setattr("oxr.pipeline.layout.asyncio.sleep", immediate_backoff)
+
+ assert len(asyncio.run(analyze_layouts(images))) == 2
+ assert peak == 1
+
+
+def test_analyze_layouts_cancels_and_drains_sibling_batches_on_failure(monkeypatch):
+ sibling_started = asyncio.Event()
+ sibling_cancelled = asyncio.Event()
+
+ def encode_images(images):
+ return [bytes([int(image[0, 0, 0])]) for image in images]
+
+ async def request_batch(encoded_images):
+ if encoded_images == [b"\x00"]:
+ await sibling_started.wait()
+ raise RuntimeError("failed batch")
+ sibling_started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ sibling_cancelled.set()
+
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.encode_images", encode_images)
+ monkeypatch.setattr("oxr.pipeline.layout.layout_client.request_batch", request_batch)
+ monkeypatch.setattr(settings.layout_analyze_model, "batch_size", 1)
+ monkeypatch.setattr(settings.layout_analyze_model, "max_concurrency", 2)
+ monkeypatch.setattr(settings.layout_analyze_model, "retry_times", 1)
+
+ async def scenario():
+ images = [
+ np.zeros((8, 8, 3), dtype=np.uint8),
+ np.ones((8, 8, 3), dtype=np.uint8),
+ ]
+ with pytest.raises(PipelineError, match="failed batch"):
+ await analyze_layouts(images)
+ assert sibling_cancelled.is_set()
+
+ asyncio.run(scenario())
+
+
+def test_analyze_layouts_uses_injected_client_and_config():
+ calls = []
+ config = LayoutAnalyzeModelConfig(
+ url="http://layout.example",
+ batch_size=1,
+ max_concurrency=1,
+ retry_times=1,
+ score_threshold=0.8,
+ )
+
+ class Client:
+ def encode_images(self, images):
+ assert len(images) == 1
+ return [b"injected"]
+
+ async def request_batch(self, encoded_images):
+ calls.append(encoded_images)
+ return {
+ "status": "success",
+ "params": {},
+ "data": {
+ "labels": [[3, 7]],
+ "boxes": [[[0, 0, 5, 5], [5, 5, 10, 10]]],
+ "scores": [[0.79, 0.8]],
+ },
+ }
+
+ image = np.zeros((10, 10, 3), dtype=np.uint8)
+ pages = asyncio.run(analyze_layouts([image], client=Client(), config=config))
+
+ assert calls == [[b"injected"]]
+ assert len(pages[0]) == 1
+ assert pages[0][0].type.value == "Title"
diff --git a/tests/unit/test_layout_postprocess.py b/tests/unit/test_layout_postprocess.py
new file mode 100644
index 0000000..10004f3
--- /dev/null
+++ b/tests/unit/test_layout_postprocess.py
@@ -0,0 +1,184 @@
+import math
+
+import pytest
+
+from oxr.pipeline.models import BlockType
+from oxr.pipeline.postprocess.layout_postprocess import parse_layout_batch
+
+
+def payload(labels, boxes, scores, **extra):
+ return {
+ "status": "success",
+ "params": {},
+ "data": {"labels": labels, "boxes": boxes, "scores": scores},
+ **extra,
+ }
+
+
+def test_parse_layout_batch_maps_all_native_class_ids():
+ boxes = [[index, 0, index + 0.5, 1] for index in range(12)]
+
+ pages = parse_layout_batch(
+ payload([list(range(12))], [boxes], [[0.5] * 12]),
+ [(20, 2)],
+ 0.5,
+ )
+
+ assert [block.type for block in pages[0]] == [
+ BlockType.CAPTION,
+ BlockType.FOOTNOTE,
+ BlockType.FORMULA,
+ BlockType.TEXT,
+ BlockType.PAGE_FOOTER,
+ BlockType.PAGE_HEADER,
+ BlockType.PICTURE,
+ BlockType.TITLE,
+ BlockType.TABLE,
+ BlockType.CODE_BLOCK,
+ BlockType.STAMP,
+ BlockType.CHEMICAL_STRUCTURE,
+ ]
+ assert [block.idx for block in pages[0]] == list(range(12))
+ assert [block.layout_score for block in pages[0]] == [0.5] * 12
+
+
+def test_parse_layout_batch_applies_classwise_nms_by_default():
+ pages = parse_layout_batch(
+ payload(
+ [[3, 3, 7]],
+ [[
+ [0, 0, 100, 100],
+ [5, 5, 100, 100],
+ [5, 5, 100, 100],
+ ]],
+ [[0.8, 0.9, 0.7]],
+ ),
+ [(100, 100)],
+ 0.5,
+ )
+
+ assert [block.type for block in pages[0]] == [BlockType.TEXT, BlockType.TITLE]
+ assert pages[0][0].bbox == [5.0, 5.0, 100.0, 100.0]
+ assert pages[0][0].layout_score == 0.9
+
+
+def test_parse_layout_batch_can_disable_nms():
+ pages = parse_layout_batch(
+ payload(
+ [[3, 3]],
+ [[[0, 0, 100, 100], [5, 5, 100, 100]]],
+ [[0.8, 0.9]],
+ ),
+ [(100, 100)],
+ 0.5,
+ None,
+ )
+
+ assert len(pages[0]) == 2
+
+
+def test_parse_layout_batch_filters_inclusively_and_reindexes_retained_blocks():
+ pages = parse_layout_batch(
+ payload(
+ [[3, 7, 2]],
+ [[[-5, 0, 10, 10], [10, 10, 30, 30], [40, 40, 60, 60]]],
+ [[0.49, 0.5, 0.9]],
+ request_id="ignored",
+ ),
+ [(100, 100)],
+ 0.5,
+ )
+
+ assert [block.type for block in pages[0]] == [BlockType.TITLE, BlockType.FORMULA]
+ assert [block.idx for block in pages[0]] == [0, 1]
+ assert [block.bbox for block in pages[0]] == [
+ [10.0, 10.0, 30.0, 30.0],
+ [40.0, 40.0, 60.0, 60.0],
+ ]
+
+
+def test_parse_layout_batch_preserves_empty_page_positions():
+ pages = parse_layout_batch(
+ payload([[], [3]], [[], [[1, 2, 30, 40]]], [[], [0.4]]),
+ [(100, 100), (100, 100)],
+ 0.5,
+ )
+
+ assert pages == [[], []]
+
+
+def test_parse_layout_batch_clamps_retained_boxes_to_image_bounds():
+ pages = parse_layout_batch(
+ payload(
+ [[3, 7]],
+ [[[-1, -2, 101, 102], [90, 95, 110, 120]]],
+ [[0.9, 0.8]],
+ ),
+ [(100, 100)],
+ 0.5,
+ )
+
+ assert [block.bbox for block in pages[0]] == [
+ [0.0, 0.0, 100.0, 100.0],
+ [90.0, 95.0, 100.0, 100.0],
+ ]
+
+
+def test_parse_layout_batch_discards_boxes_outside_image_after_clamping():
+ pages = parse_layout_batch(
+ payload(
+ [[3, 7, 2]],
+ [[[-20, 1, -10, 10], [101, 1, 110, 10], [1, 101, 10, 110]]],
+ [[0.9, 0.9, 0.9]],
+ ),
+ [(100, 100)],
+ 0.5,
+ )
+
+ assert pages == [[]]
+
+
+ ("response", "image_sizes", "match"),
+ [
+ (None, [(100, 100)], "response must be an object"),
+ ({"status": "failed", "params": {}, "data": {}}, [(100, 100)], "status"),
+ ({"status": "success", "params": [], "data": {}}, [(100, 100)], "params"),
+ ({"status": "success", "params": {}, "data": []}, [(100, 100)], "data"),
+ ({"status": "success", "params": {}, "data": {}}, [(100, 100)], "labels"),
+ (payload([[]], [[]], [[]]), [(100, 100), (100, 100)], "batch count"),
+ (payload([[3]], [[]], [[0.9]]), [(100, 100)], "candidate count"),
+ (payload([[True]], [[[1, 2, 3, 4]]], [[0.9]]), [(100, 100)], "label"),
+ (payload([[3.0]], [[[1, 2, 3, 4]]], [[0.9]]), [(100, 100)], "label"),
+ (payload([[12]], [[[1, 2, 3, 4]]], [[0.9]]), [(100, 100)], "label"),
+ (payload([[3]], [[[1, 2, 3, 4]]], [[True]]), [(100, 100)], "score"),
+ (payload([[3]], [[[1, 2, 3, 4]]], [[math.nan]]), [(100, 100)], "finite"),
+ (payload([[3]], [[[1, 2, 3, 4]]], [[1.1]]), [(100, 100)], "score"),
+ (payload([[3]], [[[1, 2, 3]]], [[0.9]]), [(100, 100)], "four coordinates"),
+ (payload([[3]], [[[True, 2, 3, 4]]], [[0.9]]), [(100, 100)], "numeric"),
+ (payload([[3]], [[[1, 2, math.inf, 4]]], [[0.9]]), [(100, 100)], "finite"),
+ (payload([[3]], [[[3, 2, 3, 4]]], [[0.9]]), [(100, 100)], "nondegenerate"),
+ (payload([[3]], [[[4, 2, 3, 4]]], [[0.9]]), [(100, 100)], "nondegenerate"),
+ ],
+)
+def test_parse_layout_batch_rejects_invalid_native_response(response, image_sizes, match):
+ with pytest.raises(ValueError, match=match):
+ parse_layout_batch(response, image_sizes, 0.5)
+
+
[email protected]("threshold", [True, -0.01, 1.01, math.nan])
+def test_parse_layout_batch_rejects_invalid_score_threshold(threshold):
+ with pytest.raises(ValueError, match="score threshold"):
+ parse_layout_batch(payload([[]], [[]], [[]]), [(100, 100)], threshold)
+
+
[email protected]("threshold", [True, -0.01, 1.01, math.nan])
+def test_parse_layout_batch_rejects_invalid_nms_threshold(threshold):
+ with pytest.raises(ValueError, match="NMS IoU threshold"):
+ parse_layout_batch(payload([[]], [[]], [[]]), [(100, 100)], 0.5, threshold)
+
+
[email protected]("image_size", [(0, 100), (100, 0), (True, 100), (100, math.inf)])
+def test_parse_layout_batch_rejects_invalid_image_dimensions(image_size):
+ with pytest.raises(ValueError, match="image dimensions"):
+ parse_layout_batch(payload([[]], [[]], [[]]), [image_size], 0.5)
diff --git a/tests/unit/test_model_client_options.py b/tests/unit/test_model_client_options.py
new file mode 100644
index 0000000..d443947
--- /dev/null
+++ b/tests/unit/test_model_client_options.py
@@ -0,0 +1,174 @@
+import asyncio
+import base64
+from types import SimpleNamespace
+
+import cv2
+import numpy as np
+
+from oxr.config.settings import OXRModelConfig
+from oxr.model.client import (
+ DEFAULT_MODEL_OPTIONS,
+ ModelOutput,
+ OXRModelClient,
+ resolve_model_options,
+)
+from oxr.model.prompts import (
+ PROMPT_CHEMICAL_STRUCTURE_RECOGNITION,
+ PROMPT_LAYOUT_ANALYSIS,
+ PROMPT_WHOLE_PAGE_RECOGNITION,
+)
+
+
+class FakeCompletions:
+ def __init__(self):
+ self.kwargs = None
+
+ async def create(self, **kwargs):
+ self.kwargs = kwargs
+ message = SimpleNamespace(content="ok")
+ choice = SimpleNamespace(message=message, finish_reason="stop")
+ return SimpleNamespace(choices=[choice], usage={"completion_tokens": 1})
+
+
+class FakeClient:
+ def __init__(self):
+ self.completions = FakeCompletions()
+ self.chat = SimpleNamespace(completions=self.completions)
+
+
+def test_resolve_model_options_uses_client_defaults():
+ assert resolve_model_options() == DEFAULT_MODEL_OPTIONS
+
+
+def test_oxr_client_disables_openai_sdk_retries(monkeypatch):
+ captured = {}
+ fake_client = object()
+ fake_http_client = object()
+
+ def build_client(**kwargs):
+ captured.update(kwargs)
+ return fake_client
+
+ monkeypatch.setattr("oxr.model.client.AsyncOpenAI", build_client)
+ monkeypatch.setattr(
+ "oxr.model.client.DefaultAsyncHttpxClient",
+ lambda **_kwargs: fake_http_client,
+ )
+
+ client = OXRModelClient(OXRModelConfig(url="http://oxr.example/v1"))
+
+ assert client.client is fake_client
+ assert captured["max_retries"] == 0
+
+
+def test_call_vision_model_passes_sampling_options():
+ fake_client = FakeClient()
+ client = OXRModelClient()
+ client._client = fake_client
+ options = {"temperature": 0.4, "top_p": 0.8, "repetition_penalty": 1.3}
+
+ result = asyncio.run(
+ client._call_vision_model(
+ prompt="prompt",
+ image=np.zeros((8, 8, 3), dtype=np.uint8),
+ timeout=1,
+ model_options=options,
+ )
+ )
+
+ kwargs = fake_client.completions.kwargs
+ assert result == "ok"
+ assert isinstance(result, ModelOutput)
+ assert result.finish_reason == "stop"
+ assert result.usage == {"completion_tokens": 1}
+ assert kwargs["temperature"] == 0.4
+ assert kwargs["top_p"] == 0.8
+ assert kwargs["extra_body"]["repetition_penalty"] == 1.3
+ assert "chat_template_kwargs" not in kwargs["extra_body"]
+ content = kwargs["messages"][0]["content"]
+ assert [item["type"] for item in content] == ["image_url", "text"]
+ assert content[1] == {"type": "text", "text": "prompt"}
+
+
+def test_vision_requests_use_lossless_png_images():
+ image = np.arange(8 * 8 * 3, dtype=np.uint8).reshape(8, 8, 3)
+ client = OXRModelClient()
+
+ data_url = client._image_to_data_url(image)
+
+ prefix, encoded = data_url.split(",", 1)
+ decoded = cv2.imdecode(
+ np.frombuffer(base64.b64decode(encoded), dtype=np.uint8),
+ cv2.IMREAD_COLOR,
+ )
+ assert prefix == "data:image/png;base64"
+ assert np.array_equal(decoded, image)
+
+
+def test_reading_order_uses_deterministic_options_and_max_token_override():
+ fake_client = FakeClient()
+ client = OXRModelClient()
+ client._client = fake_client
+
+ result = asyncio.run(
+ client.request_reading_order(
+ prompt="reading-order prompt",
+ image=np.zeros((8, 8, 3), dtype=np.uint8),
+ max_tokens=24,
+ )
+ )
+
+ kwargs = fake_client.completions.kwargs
+ assert result == "ok"
+ assert kwargs["temperature"] == 0.0
+ assert kwargs["top_p"] == 1.0
+ assert kwargs["extra_body"]["repetition_penalty"] == 1.0
+ assert kwargs["max_tokens"] == 24
+
+
+def test_oxr_client_closes_persistent_client():
+ class ClosableFakeClient(FakeClient):
+ def __init__(self):
+ super().__init__()
+ self.closed = False
+
+ async def close(self):
+ self.closed = True
+
+ fake_client = ClosableFakeClient()
+ client = OXRModelClient()
+ client._client = fake_client
+
+ asyncio.run(client.aclose())
+
+ assert fake_client.closed is True
+ assert client._client is None
+
+
+def test_diagnostic_client_methods_use_central_prompt_definitions():
+ calls = []
+ client = OXRModelClient(OXRModelConfig(url="http://oxr.example/v1", timeout=17))
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ options = {"temperature": 0.2}
+
+ async def call(prompt, image, timeout, model_options=None, max_tokens=None):
+ calls.append((prompt, image, timeout, model_options, max_tokens))
+ return "ok"
+
+ client._call_vision_model = call
+
+ async def scenario():
+ assert await client.analyze_layout(image, options) == "ok"
+ assert await client.recognize_whole_page(image, options) == "ok"
+ assert await client.recognize_chemical_structure(image, options) == "ok"
+
+ asyncio.run(scenario())
+
+ assert [entry[0] for entry in calls] == [
+ PROMPT_LAYOUT_ANALYSIS,
+ PROMPT_WHOLE_PAGE_RECOGNITION,
+ PROMPT_CHEMICAL_STRUCTURE_RECOGNITION,
+ ]
+ assert all(entry[1] is image for entry in calls)
+ assert all(entry[2] == 17 for entry in calls)
+ assert all(entry[3] == options for entry in calls)
diff --git a/tests/unit/test_model_repository_launcher.py b/tests/unit/test_model_repository_launcher.py
new file mode 100644
index 0000000..4ef706a
--- /dev/null
+++ b/tests/unit/test_model_repository_launcher.py
@@ -0,0 +1,52 @@
+"""Validate launch wiring without installing vLLM or invoking a GPU."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def test_launcher_uses_repository_plugin_and_root_template(tmp_path):
+ model = tmp_path / "model with spaces"
+ (model / "plugins/vllm").mkdir(parents=True)
+ (model / "plugins/vllm/pyproject.toml").touch()
+ (model / "chat_template.jinja").touch()
+ bins = tmp_path / "bin"
+ bins.mkdir()
+ output = tmp_path / "calls.jsonl"
+ for name in ("python3", "vllm"):
+ stub = bins / name
+ stub.write_text(
+ f"#!{sys.executable}\n"
+ "import json, os, sys\n"
+ "with open(os.environ['CALLS'], 'a') as f:\n"
+ " f.write(json.dumps([sys.argv, os.getenv('VLLM_PLUGINS')]) + '\\n')\n"
+ )
+ stub.chmod(0o755)
+ env = {**os.environ, "PATH": f"{bins}:{os.environ['PATH']}",
+ "MODEL_PATH": str(model), "CALLS": str(output)}
+ subprocess.run(["bash", str(ROOT / "services/oxr/start_vllm.sh"),
+ "--port", "9090"], env=env, check=True)
+ install, serve = [json.loads(line) for line in output.read_text().splitlines()]
+ assert install[0][1:] == ["-m", "pip", "install", str(model / "plugins/vllm")]
+ args, plugins = serve
+ assert plugins == "oxr"
+ assert args[1:3] == ["serve", str(model)]
+ assert args[args.index("--chat-template") + 1] == str(model / "chat_template.jinja")
+ assert args[args.index("--served-model-name") + 1] == "oxr"
+ assert args[args.index("--max-model-len") + 1] == "16384"
+ assert "--trust-remote-code" in args
+ assert json.loads(args[args.index("--attention-config") + 1]) == {"backend": "TRITON_ATTN"}
+ assert args[-2:] == ["--port", "9090"]
+
+
+def test_launcher_rejects_old_or_incomplete_layout(tmp_path):
+ result = subprocess.run(
+ ["bash", str(ROOT / "services/oxr/start_vllm.sh")],
+ env={**os.environ, "MODEL_PATH": str(tmp_path)},
+ capture_output=True, text=True,
+ )
+ assert result.returncode == 1
+ assert "Expected an oxr-model repository root" in result.stderr
diff --git a/tests/unit/test_overlap_dedupe.py b/tests/unit/test_overlap_dedupe.py
new file mode 100644
index 0000000..1f9a679
--- /dev/null
+++ b/tests/unit/test_overlap_dedupe.py
@@ -0,0 +1,235 @@
+from dataclasses import asdict
+
+import numpy as np
+import pytest
+
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.overlap_dedupe import dedupe_complete_text, dedupe_visual_parents
+
+
+def block(idx, kind, box, text='', score=0.9):
+ return Block(idx, kind, box, text, ContentFormat.TEXT, layout_score=score)
+
+
+def text_group(separator='\n'):
+ return [
+ block(42, BlockType.TEXT, [0, 0, 100, 100], ' hello' + separator + 'world '),
+ block(91, BlockType.TEXT, [0, 0, 100, 40], 'hello'),
+ block(3, BlockType.TEXT, [0, 50, 100, 90], 'world'),
+ ]
+
+
[email protected]('separator,expected', [('\n', ' hello\n\nworld '), (' ', ' hello world '), ('', ' helloworld ')])
+def test_text_preserves_parent_boundaries_native_ids_and_roles(separator, expected):
+ blocks = text_group(separator)
+ blocks[0].generated_role = 'formula_number'
+ before = [asdict(b) for b in blocks]
+ result = dedupe_complete_text(blocks)
+ assert len(result) == 1
+ assert asdict(result[0]) == {**before[0], 'content': expected}
+ assert [asdict(b) for b in blocks] == before
+
+
[email protected]('case', ['unique_text', 'interleaved', 'reversed', 'title', 'short'])
+def test_text_skips_incomplete_or_unsafe_groups(case):
+ blocks = text_group()
+ if case == 'unique_text':
+ blocks[0].content += ' missing'
+ elif case == 'interleaved':
+ blocks.insert(2, block(18, BlockType.FORMULA, [0, 0, 1, 1], 'x'))
+ elif case == 'reversed':
+ blocks[1], blocks[2] = blocks[2], blocks[1]
+ elif case == 'title':
+ blocks[2].type = BlockType.TITLE
+ else:
+ blocks[1].content = 'hi'
+ assert dedupe_complete_text(blocks) == blocks
+
+
+def visual_group(kind):
+ parent = block(35, kind, [0, 0, 100, 100], 'parent', 0.6)
+ children = [block(8, kind, [0, 0, 45, 90], 'one'), block(17, kind, [55, 0, 100, 90], 'two')]
+ caption = block(29, BlockType.CAPTION, [0, 90, 100, 100], 'caption')
+ text = block(28, BlockType.TEXT, [2, 2, 10, 10], 'inside image')
+ image = np.full((100, 100, 3), 255, np.uint8)
+ image[10:20, 10:20] = 0
+ image[10:20, 65:75] = 0
+ image[95:98, 10:80] = 0
+ return [parent, *children, caption, text], image
+
+
[email protected]('kind', [BlockType.PICTURE, BlockType.CHEMICAL_STRUCTURE])
+def test_visual_parent_removed_with_captions_and_all_retained_fields_intact(kind):
+ raw, image = visual_group(kind)
+ final = [raw[2], raw[0], raw[4], raw[1], raw[3]]
+ before = [asdict(b) for b in final]
+ result = dedupe_visual_parents(raw, final, image)
+ assert [asdict(b) for b in result] == [b for b in before if b['idx'] != 35]
+ assert [asdict(b) for b in final] == before
+
+
[email protected]('case', ['uncovered_ink', 'low_confidence', 'missing_score', 'missing_child', 'missing_caption', 'duplicate_final', 'duplicate_raw', 'blank', 'one_child', 'formula'])
+def test_visual_parent_requires_complete_unambiguous_evidence(case):
+ raw, image = visual_group(BlockType.PICTURE)
+ final = list(raw)
+ if case == 'uncovered_ink':
+ image[10:30, 48:52] = 0
+ elif case == 'low_confidence':
+ raw[1].layout_score = 0.61
+ elif case == 'missing_score':
+ raw[0].layout_score = None
+ elif case == 'missing_child':
+ final.remove(raw[1])
+ elif case == 'missing_caption':
+ final.remove(raw[3])
+ elif case == 'duplicate_final':
+ final.append(raw[1])
+ elif case == 'duplicate_raw':
+ raw[1].idx = raw[2].idx
+ elif case == 'blank':
+ image[:] = 255
+ elif case == 'one_child':
+ raw.remove(raw[2])
+ else:
+ for b in raw[:3]:
+ b.type = BlockType.FORMULA
+ assert dedupe_visual_parents(raw, final, image) == final
+
+
+def test_postprocessing_is_enabled_by_code_local_constants():
+ from oxr.pipeline import orchestrator
+
+ assert orchestrator._SYSTEMATIC_CROSS_CATEGORY_DEDUPE is True
+ assert orchestrator._VISUAL_PARENT_DEDUPE is True
+ assert orchestrator._COMPLETE_TEXT_DEDUPE is True
+
+
[email protected]('enabled', [True, False])
+def test_pipeline_cleans_final_blocks_after_original_recognition_and_order(monkeypatch, enabled):
+ import asyncio
+ from oxr.config.settings import settings
+ from oxr.pipeline import orchestrator
+
+ raw_visual, image = visual_group(BlockType.PICTURE)
+ raw = raw_visual + text_group()
+ # Give the second group distinct native IDs without changing its list order.
+ for i, b in enumerate(raw[5:], 100):
+ b.idx = i
+ original_ids = [b.idx for b in raw]
+ events = []
+
+ async def layout(_images, _options):
+ return [raw]
+
+ async def recognize(pages, *_args):
+ assert [b.idx for b in pages[0]] == original_ids
+ events.append('recognize')
+ # Recognition may mutate its input: visual evidence must be snapshotted.
+ pages[0][0].layout_score = None
+ return pages
+
+ async def order(pages, *_args):
+ assert [b.idx for b in pages[0]] == original_ids
+ events.append('order')
+ return [list(range(len(raw)))]
+
+ expand = orchestrator.expand_formula_numbering_blocks
+
+ def expansion(blocks):
+ events.append('expand')
+ return expand(blocks)
+
+ monkeypatch.setattr(orchestrator, '_decode_document_images', lambda *_: [image])
+ monkeypatch.setattr(orchestrator, 'analyze_layouts', layout)
+ monkeypatch.setattr(orchestrator, 'recognize_pages', recognize)
+ monkeypatch.setattr(orchestrator, 'resolve_reading_orders', order)
+ monkeypatch.setattr(orchestrator, 'expand_formula_numbering_blocks', expansion)
+ monkeypatch.setattr(settings.layout_analyze_model, 'provides_reading_order', False)
+ monkeypatch.setattr(orchestrator, '_SYSTEMATIC_CROSS_CATEGORY_DEDUPE', False)
+ monkeypatch.setattr(orchestrator, '_VISUAL_PARENT_DEDUPE', enabled)
+ monkeypatch.setattr(orchestrator, '_COMPLETE_TEXT_DEDUPE', enabled)
+ result = asyncio.run(orchestrator.process_document(b'fixture', 'fixture.png', ['json']))
+ final = result['outputs']['json']['pages'][0]['blocks']
+ assert events[-1] == 'expand'
+ # Existing formula expansion renumbers first; cleanup preserves those IDs.
+ assert {b['idx'] for b in final} == set(range(len(raw))) - ({0, 6, 7} if enabled else set())
+ if enabled:
+ assert next(b for b in final if b['idx'] == 5)['content'] == ' hello\n\nworld '
+
+
[email protected]('parent,child', [
+ ('New York is lovely', 'NewYork is lovely'),
+ (r'Visit $\text{New York}$ now', r'Visit $\text{NewYork}$ now'),
+ ('NewYork is lovely', 'New York is lovely'),
+ ('Keep\tthese spaces', 'Keep these spaces'),
+])
+def test_parent_internal_whitespace_is_authoritative(parent, child):
+ blocks = [block(0, BlockType.TEXT, [0, 0, 100, 100], parent),
+ block(1, BlockType.TEXT, [0, 0, 100, 40], child)]
+ result = dedupe_complete_text(blocks)
+ assert len(result) == 1
+ assert result[0].content == parent
+
+
[email protected]('first,second', [
+ (r'Visit $\text{New', 'York}$ now'),
+ ('Use `New', 'York` now'),
+ ('Visit [New', 'York](https://example.test)'),
+ ('<span>New', 'York</span>'),
+ ('**New', 'York**'),
+ ('Heading', '====='),
+ ('Heading', '-----'),
+ ('hello ', 'world'),
+ ('- New first', '- New second'),
+ (' code first', ' code second'),
+ (r'Visit \(New', r'York\) now'),
+])
+def test_structured_text_keeps_original_boundary_and_parent_content(first, second):
+ parent = first + '\n' + second
+ blocks = [block(0, BlockType.TEXT, [0, 0, 100, 100], parent),
+ block(1, BlockType.TEXT, [0, 0, 100, 40], first),
+ block(2, BlockType.TEXT, [0, 50, 100, 90], second)]
+ result = dedupe_complete_text(blocks)
+ assert len(result) == 1
+ assert result[0].content == parent
+
+
+def test_multichild_preserves_internal_spaces_and_plain_paragraph_boundary():
+ blocks = [block(0, BlockType.TEXT, [0, 0, 100, 100], ' New York\nLos Angeles '),
+ block(1, BlockType.TEXT, [0, 0, 100, 40], 'NewYork'),
+ block(2, BlockType.TEXT, [0, 50, 100, 90], 'LosAngeles')]
+ result = dedupe_complete_text(blocks)
+ assert result[0].content == ' New York\n\nLos Angeles '
+ assert len(result) == 1
+
+
[email protected]('case', ['complete', 'uncovered_ink', 'missing_child', 'missing_title'])
+def test_mixed_visual_parent_requires_retained_children_and_complete_ink(case):
+ raw, image = visual_group(BlockType.PICTURE)
+ raw[1].type = raw[2].type = BlockType.CHEMICAL_STRUCTURE
+ raw[3].type = BlockType.TITLE
+ lower = block(37, BlockType.CHEMICAL_STRUCTURE, [45, 0, 55, 30], 'three', 0.5)
+ raw.append(lower)
+ image[10:20, 48:52] = 0
+ final = list(raw)
+ if case == 'uncovered_ink':
+ image[70:75, 48:52] = 0
+ elif case == 'missing_child':
+ final.remove(lower)
+ elif case == 'missing_title':
+ final.remove(raw[3])
+ assert dedupe_visual_parents(raw, final, image) == final
+ result = dedupe_visual_parents(raw, final, image, allow_mixed_children=True)
+ assert result == ([b for b in final if b is not raw[0]] if case == 'complete' else final)
+
+
+def test_visual_parent_is_restored_if_a_coverage_witness_loses_later_cleanup():
+ from oxr.pipeline.orchestrator import _dedupe_full_page
+
+ raw, image = visual_group(BlockType.PICTURE)
+ stamp = block(38, BlockType.STAMP, [0, 90.5, 100, 100.5], 'caption', 0.99)
+ raw.append(stamp)
+ result = _dedupe_full_page(raw, list(raw), image)
+ assert raw[3] not in result
+ assert raw[0] in result
+ assert stamp in result
diff --git a/tests/unit/test_pdf.py b/tests/unit/test_pdf.py
new file mode 100644
index 0000000..9bc1eea
--- /dev/null
+++ b/tests/unit/test_pdf.py
@@ -0,0 +1,116 @@
+"""Verify PDFium exclusion covers open/render/close and releases on errors."""
+from concurrent.futures import ThreadPoolExecutor
+from threading import Event
+from unittest.mock import Mock
+
+import cv2
+import numpy as np
+import pytest
+
+from oxr.utils import pdf
+
+
+def _png():
+ image = np.full((3, 4, 3), 71, dtype=np.uint8)
+ success, encoded = cv2.imencode(".png", image)
+ assert success
+ return image, encoded.tobytes()
+
+
[email protected]("stage", ["open", "render", "close"])
+def test_concurrent_documents_exclude_every_pdfium_stage(monkeypatch, stage):
+ entered, release, second_started, second_opened = Event(), Event(), Event(), Event()
+ expected, png = _png()
+ events = []
+
+ def hold(name, current):
+ events.append((name, current))
+ if name == "first" and current == stage:
+ entered.set()
+ assert release.wait(2)
+
+ class Document:
+ def __init__(self, name):
+ self.name = name
+ self.pages = [self]
+
+ def __enter__(self):
+ return self
+
+ def render(self, *, dpi):
+ assert dpi == 150
+ hold(self.name, "render")
+ return png
+
+ def __exit__(self, *_args):
+ hold(self.name, "close")
+
+ def open_document(*, stream):
+ name = stream.decode()
+ if name == "second":
+ second_opened.set()
+ hold(name, "open")
+ return Document(name)
+
+ opened = Mock(side_effect=open_document)
+ monkeypatch.setattr(pdf.sopdf, "open", opened)
+
+ def second_call():
+ second_started.set()
+ return pdf.pdf_to_images(b"second")
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ first = pool.submit(pdf.pdf_to_images, b"first")
+ try:
+ assert entered.wait(1)
+ second = pool.submit(second_call)
+ assert second_started.wait(1)
+ # The first document is deliberately held inside each native stage.
+ assert not second_opened.wait(0.05)
+ assert not second.done()
+ assert opened.call_count == 1
+ finally:
+ release.set()
+ first_result = first.result(timeout=2)
+ second_result = second.result(timeout=2)
+ assert events == [(name, current) for name in ["first", "second"]
+ for current in ["open", "render", "close"]]
+ assert np.array_equal(first_result[0], expected)
+ assert np.array_equal(second_result[0], expected)
+
+
[email protected]("stage", ["open", "render", "close"])
+def test_pdfium_lock_is_released_after_native_failure(monkeypatch, stage):
+ expected, png = _png()
+
+ class Document:
+ def __init__(self, broken):
+ self.broken = broken
+ self.pages = [self]
+
+ def __enter__(self):
+ return self
+
+ def render(self, *, dpi):
+ if self.broken and stage == "render":
+ raise ValueError("native render failed")
+ return png
+
+ def __exit__(self, *_args):
+ if self.broken and stage == "close":
+ raise ValueError("native close failed")
+
+ def open_document(*, stream):
+ if stream == b"broken" and stage == "open":
+ raise ValueError("native open failed")
+ return Document(stream == b"broken")
+
+ monkeypatch.setattr(pdf.sopdf, "open", open_document)
+ with pytest.raises(ValueError, match="native .* failed"):
+ pdf.pdf_to_images(b"broken")
+ # A non-daemon worker could hang the test process if a broken lock leaked.
+ assert pdf._PDFIUM_LOCK.acquire(timeout=1)
+ pdf._PDFIUM_LOCK.release()
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ result = pool.submit(pdf.pdf_to_images, b"healthy").result(timeout=2)
+ assert np.array_equal(result[0], expected)
diff --git a/tests/unit/test_pipeline_parallelism.py b/tests/unit/test_pipeline_parallelism.py
new file mode 100644
index 0000000..c629bdc
--- /dev/null
+++ b/tests/unit/test_pipeline_parallelism.py
@@ -0,0 +1,500 @@
+import asyncio
+
+import numpy as np
+import pytest
+
+from oxr.config.settings import settings
+from oxr.model.client import model_client
+from oxr.pipeline import orchestrator
+from oxr.pipeline.concurrency import gather_cancel_on_error
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.reading_order import resolve_reading_orders
+from oxr.pipeline.recognition import recognize_block, recognize_pages
+
+
+def _block(idx: int, block_type: BlockType = BlockType.TEXT, bbox=None) -> Block:
+ return Block(idx, block_type, bbox or [0, 0, 4, 4], "", ContentFormat.TEXT)
+
+
+def test_gather_cancel_on_error_cancels_and_drains_siblings():
+ sibling_started = asyncio.Event()
+ sibling_cancelled = asyncio.Event()
+
+ async def fail_after_sibling_starts():
+ await sibling_started.wait()
+ raise RuntimeError("branch failed")
+
+ async def sibling():
+ sibling_started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ sibling_cancelled.set()
+
+ async def scenario():
+ with pytest.raises(RuntimeError, match="branch failed"):
+ await gather_cancel_on_error(fail_after_sibling_starts(), sibling())
+ assert sibling_cancelled.is_set()
+
+ asyncio.run(scenario())
+
+
+def test_reading_order_and_recognition_share_combined_oxr_concurrency(monkeypatch):
+ active = 0
+ maximum = 0
+ two_requests_entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def enter_request():
+ nonlocal active, maximum
+ active += 1
+ maximum = max(maximum, active)
+ if active == 2:
+ two_requests_entered.set()
+ await release.wait()
+ active -= 1
+
+ async def request_reading_order(_prompt, _image, _max_tokens):
+ await enter_request()
+ return "0 1"
+
+ async def recognize_text(_image, _model_options=None):
+ await enter_request()
+ return "text"
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr("oxr.pipeline.reading_order.model_client.request_reading_order", request_reading_order)
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_text", recognize_text)
+
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ pages = [[_block(0, bbox=[0, 0, 4, 4]), _block(1, bbox=[4, 4, 8, 8])]]
+
+ async def scenario():
+ semaphore = asyncio.Semaphore(2)
+ order_task = asyncio.create_task(resolve_reading_orders(pages, [image], semaphore))
+ recognition_task = asyncio.create_task(
+ recognize_pages(pages, [image], "demo.png", semaphore)
+ )
+ await asyncio.wait_for(two_requests_entered.wait(), timeout=1)
+ release.set()
+ await gather_cancel_on_error(order_task, recognition_task)
+
+ asyncio.run(scenario())
+
+ assert maximum == 2
+
+
+def test_concurrent_documents_share_process_oxr_concurrency_limit(monkeypatch):
+ active = 0
+ maximum = 0
+
+ async def analyze_layouts(_images, _model_options=None):
+ return [[_block(0)]]
+
+ async def recognize(
+ pages_blocks,
+ _images,
+ _file_name,
+ semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ nonlocal active, maximum
+ async with semaphore:
+ active += 1
+ maximum = max(maximum, active)
+ await asyncio.sleep(0.01)
+ active -= 1
+ return pages_blocks
+
+ monkeypatch.setattr(
+ orchestrator.cv2,
+ "imdecode",
+ lambda *_args: np.zeros((8, 8, 3), dtype=np.uint8),
+ )
+ monkeypatch.setattr(orchestrator, "analyze_layouts", analyze_layouts)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(settings.layout_analyze_model, "provides_reading_order", True)
+ monkeypatch.setattr(settings.oxr_model, "max_concurrency", 1)
+
+ async def scenario():
+ await asyncio.gather(
+ orchestrator.process_document(b"first", "first.png", ["json"]),
+ orchestrator.process_document(b"second", "second.png", ["json"]),
+ )
+
+ asyncio.run(scenario())
+
+ assert maximum == 1
+
+
+def test_process_oxr_limiter_is_safe_across_asyncio_run_loops(monkeypatch):
+ monkeypatch.setattr(settings.oxr_model, "max_concurrency", 1)
+
+ async def bind_limiter_to_current_loop():
+ semaphore = model_client.get_request_semaphore()
+ await semaphore.acquire()
+ waiter = asyncio.create_task(semaphore.acquire())
+ await asyncio.sleep(0)
+ assert not waiter.done()
+ waiter.cancel()
+ await asyncio.gather(waiter, return_exceptions=True)
+ semaphore.release()
+ return semaphore
+
+ first = asyncio.run(bind_limiter_to_current_loop())
+ second = asyncio.run(bind_limiter_to_current_loop())
+
+ assert first is not second
+
+
+def test_recognition_releases_semaphore_during_retry_backoff(monkeypatch):
+ call_count = 0
+ second_request_finished = asyncio.Event()
+
+ async def recognize_text(_image, _model_options=None):
+ nonlocal call_count
+ call_count += 1
+ if call_count == 1:
+ raise RuntimeError("first attempt fails")
+ if call_count == 2:
+ second_request_finished.set()
+ return "ok"
+
+ async def retry_backoff(_seconds):
+ await asyncio.wait_for(second_request_finished.wait(), timeout=1)
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 2)
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_text", recognize_text)
+ monkeypatch.setattr("oxr.pipeline.recognition.asyncio.sleep", retry_backoff)
+
+ async def scenario():
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ semaphore = asyncio.Semaphore(1)
+ await gather_cancel_on_error(
+ recognize_block(_block(0), image, semaphore, "demo.png", 0),
+ recognize_block(_block(1), image, semaphore, "demo.png", 0),
+ )
+
+ asyncio.run(scenario())
+
+ assert call_count == 3
+
+
+def test_recognize_pages_preserves_input_positions_without_sorting(monkeypatch):
+ async def recognize_text(image, _model_options=None):
+ return str(int(image[0, 0, 0]))
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_text", recognize_text)
+
+ image = np.zeros((4, 8, 3), dtype=np.uint8)
+ image[:, 4:, :] = 7
+ blocks = [_block(5, bbox=[0, 0, 4, 4]), _block(1, bbox=[4, 0, 8, 4])]
+
+ result = asyncio.run(
+ recognize_pages([blocks], [image], "demo.png", asyncio.Semaphore(2))
+ )
+
+ assert [block.idx for block in result[0]] == [5, 1]
+ assert [block.content for block in result[0]] == ["0", "7"]
+
+
+def test_orchestrator_starts_reading_order_before_recognition_and_overlaps_branches(monkeypatch):
+ starts = []
+ reading_order_started = asyncio.Event()
+ recognition_started = asyncio.Event()
+
+ async def analyze_layouts(_images, _model_options=None):
+ return [[_block(0), _block(1)]]
+
+ async def resolve_orders(pages_blocks, _images, _semaphore):
+ starts.append("reading-order")
+ reading_order_started.set()
+ await recognition_started.wait()
+ return [list(range(len(page))) for page in pages_blocks]
+
+ async def recognize(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ starts.append("recognition")
+ recognition_started.set()
+ await reading_order_started.wait()
+ return pages_blocks
+
+ monkeypatch.setattr(orchestrator.cv2, "imdecode", lambda *_args: np.zeros((8, 8, 3), dtype=np.uint8))
+ monkeypatch.setattr(orchestrator, "analyze_layouts", analyze_layouts)
+ monkeypatch.setattr(orchestrator, "resolve_reading_orders", resolve_orders)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(settings.layout_analyze_model, "provides_reading_order", False)
+
+ asyncio.run(orchestrator.process_document(b"image", "page.png", ["json"], keep_header_footer=True))
+
+ assert starts == ["reading-order", "recognition"]
+
+
+def test_orchestrator_bypasses_reading_order_and_preserves_layout_order(monkeypatch):
+ async def analyze_layouts(_images, _model_options=None):
+ return [[_block(0, BlockType.TITLE), _block(1, BlockType.TEXT)]]
+
+ async def unexpected_resolve(*_args, **_kwargs):
+ raise AssertionError("reading order must be bypassed")
+
+ async def recognize(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ return pages_blocks
+
+ monkeypatch.setattr(orchestrator.cv2, "imdecode", lambda *_args: np.zeros((8, 8, 3), dtype=np.uint8))
+ monkeypatch.setattr(orchestrator, "analyze_layouts", analyze_layouts)
+ monkeypatch.setattr(orchestrator, "resolve_reading_orders", unexpected_resolve)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(settings.layout_analyze_model, "provides_reading_order", True)
+
+ result = asyncio.run(
+ orchestrator.process_document(b"image", "page.png", ["json"], keep_header_footer=True)
+ )
+
+ assert [block["type"] for block in result["outputs"]["json"]["pages"][0]["blocks"]] == [
+ BlockType.TITLE.value,
+ BlockType.TEXT.value,
+ ]
+
+
+def test_orchestrator_applies_local_permutation_then_expands_formula_indexes(monkeypatch):
+ async def analyze_layouts(_images, _model_options=None):
+ return [[
+ _block(0, BlockType.TEXT),
+ _block(1, BlockType.TEXT),
+ _block(2, BlockType.FORMULA),
+ ]]
+
+ async def resolve_orders(_pages_blocks, _images, _semaphore):
+ return [[2, 0, 1]]
+
+ async def recognize(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ pages_blocks[0][0].content = "first"
+ pages_blocks[0][1].content = "second"
+ pages_blocks[0][2].content = "x"
+ pages_blocks[0][2].format = ContentFormat.LATEX
+ pages_blocks[0][2].text_after = "(1)"
+ return pages_blocks
+
+ monkeypatch.setattr(orchestrator.cv2, "imdecode", lambda *_args: np.zeros((8, 8, 3), dtype=np.uint8))
+ monkeypatch.setattr(orchestrator, "analyze_layouts", analyze_layouts)
+ monkeypatch.setattr(orchestrator, "resolve_reading_orders", resolve_orders)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(settings.layout_analyze_model, "provides_reading_order", False)
+
+ result = asyncio.run(
+ orchestrator.process_document(b"image", "page.png", ["json"], keep_header_footer=True)
+ )
+ blocks = result["outputs"]["json"]["pages"][0]["blocks"]
+
+ assert [block["idx"] for block in blocks] == [0, 2, 3]
+ assert [(block["type"], block["content"]) for block in blocks] == [
+ (BlockType.FORMULA.value, r"x\tag{1}"),
+ (BlockType.TEXT.value, "first"),
+ (BlockType.TEXT.value, "second"),
+ ]
+ assert all("generated_role" not in block for block in blocks)
+
+
+def test_orchestrator_dedupes_before_expanding_formula_numbering(monkeypatch):
+ async def analyze_layouts(_images, _model_options=None):
+ blocks = [
+ _block(0, BlockType.TEXT, [0, 0, 4, 4]),
+ _block(1, BlockType.FORMULA, [0, 0, 4, 4]),
+ _block(2, BlockType.TEXT, [0, 4, 4, 8]),
+ _block(3, BlockType.FORMULA, [0, 4, 4, 8]),
+ ]
+ for block, score in zip(blocks, [0.9, 0.2, 0.3, 0.8]):
+ block.layout_score = score
+ return [blocks]
+
+ async def recognize(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ contents = ["$x$", "x", r"\[y\]", "y"]
+ for block, content in zip(pages_blocks[0], contents):
+ block.content = content
+ pages_blocks[0][1].format = ContentFormat.LATEX
+ pages_blocks[0][1].text_after = "removed numbering"
+ pages_blocks[0][3].format = ContentFormat.LATEX
+ pages_blocks[0][3].text_after = "(2)"
+ return pages_blocks
+
+ monkeypatch.setattr(orchestrator.cv2, "imdecode", lambda *_args: np.zeros((8, 8, 3), dtype=np.uint8))
+ monkeypatch.setattr(orchestrator, "analyze_layouts", analyze_layouts)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(settings.layout_analyze_model, "provides_reading_order", True)
+
+ result = asyncio.run(
+ orchestrator.process_document(b"image", "page.png", ["json"], keep_header_footer=True)
+ )
+ blocks = result["outputs"]["json"]["pages"][0]["blocks"]
+
+ assert [block["idx"] for block in blocks] == [0, 1]
+ assert [(block["type"], block["content"]) for block in blocks] == [
+ (BlockType.TEXT.value, "$x$"),
+ (BlockType.FORMULA.value, r"y\tag{2}"),
+ ]
+
+
[email protected]("provides_reading_order", [True, False])
+def test_orchestrator_exact_text_dedupe_only_changes_final_outputs(monkeypatch, provides_reading_order):
+ blocks = [
+ Block(8, BlockType.TEXT, [0, 0, 4, 4], "", ContentFormat.TEXT, layout_score=0.6),
+ Block(3, BlockType.CAPTION, [0, 0, 4, 4], "", ContentFormat.TEXT, layout_score=0.7),
+ Block(5, BlockType.TITLE, [0, 0, 4, 4], "", ContentFormat.TEXT, layout_score=0.9),
+ ]
+
+ async def analyze_layouts(_images, _model_options=None):
+ return [blocks]
+
+ async def resolve_orders(pages, _images, _semaphore):
+ assert len(pages[0]) == 3
+ assert all(a is b for a, b in zip(pages[0], blocks))
+ return [[0, 1, 2]]
+
+ async def recognize(pages, *_args):
+ assert len(pages[0]) == 3
+ assert all(a is b for a, b in zip(pages[0], blocks))
+ for block in pages[0]:
+ block.content = "same heading"
+ return pages
+
+ monkeypatch.setattr(orchestrator.cv2, "imdecode", lambda *_args: np.zeros((8, 8, 3), dtype=np.uint8))
+ monkeypatch.setattr(orchestrator, "analyze_layouts", analyze_layouts)
+ monkeypatch.setattr(orchestrator, "resolve_reading_orders", resolve_orders)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(settings.layout_analyze_model, "provides_reading_order", provides_reading_order)
+
+ result = asyncio.run(orchestrator.process_document(b"image", "page.png", ["json", "markdown"]))
+ final = result["outputs"]["json"]["pages"][0]["blocks"]
+ # Formula-number expansion already assigns sequential idx before this rule.
+ assert final == [{"idx": 2, "type": "Title", "bbox": [0, 0, 4, 4], "content": "same heading", "format": "text"}]
+ assert result["outputs"]["markdown"].count("same heading") == 1
+ assert len(blocks) == 3
+ assert [block.idx for block in blocks] == [0, 1, 2]
+
+
[email protected]("enabled", [True, False])
[email protected]("provides_reading_order", [True, False])
+def test_full_overlap_mode_switches_final_policy_without_changing_model_inputs(
+ monkeypatch, enabled, provides_reading_order,
+):
+ blocks = [
+ Block(0, BlockType.TEXT, [0, 0, 40, 20], "", ContentFormat.TEXT, layout_score=0.4),
+ Block(1, BlockType.FORMULA, [2, 2, 12, 12], "", ContentFormat.LATEX, layout_score=0.95),
+ Block(2, BlockType.TEXT, [50, 0, 70, 20], "", ContentFormat.TEXT, layout_score=0.2),
+ Block(3, BlockType.FORMULA, [60, 0, 80, 20], "", ContentFormat.LATEX, layout_score=0.9),
+ Block(4, BlockType.PICTURE, [90, 0, 120, 20], "", ContentFormat.TEXT, layout_score=0.8),
+ Block(5, BlockType.CAPTION, [95, 5, 115, 15], "", ContentFormat.TEXT, layout_score=0.99),
+ ]
+
+ async def analyze_layouts(_images, _model_options=None):
+ return [blocks]
+
+ async def resolve_orders(pages, _images, _semaphore):
+ assert len(pages[0]) == 6
+ return [list(range(6))]
+
+ async def recognize(pages, *_args):
+ assert len(pages[0]) == 6
+ for block, content in zip(pages[0], ["paragraph", "x", "text", "y", "picture", "caption"]):
+ block.content = content
+ pages[0][3].text_after = "(2)"
+ return pages
+
+ def unexpected_local_policy(*_args):
+ pytest.fail("full mode must replace the local cleanup policies")
+
+ if enabled:
+ for name in (
+ "dedupe_systematic_cross_category_blocks",
+ "dedupe_complete_text", "dedupe_exact_textual_blocks",
+ ):
+ monkeypatch.setattr(orchestrator, name, unexpected_local_policy)
+ monkeypatch.setattr(settings.pipeline, "full_overlap_dedupe", enabled)
+ monkeypatch.setattr(settings.layout_analyze_model, "provides_reading_order", provides_reading_order)
+ monkeypatch.setattr(orchestrator.cv2, "imdecode", lambda *_args: np.zeros((24, 128, 3), dtype=np.uint8))
+ monkeypatch.setattr(orchestrator, "analyze_layouts", analyze_layouts)
+ monkeypatch.setattr(orchestrator, "resolve_reading_orders", resolve_orders)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+
+ result = asyncio.run(orchestrator.process_document(b"image", "page.png", ["json", "markdown"]))
+ final = result["outputs"]["json"]["pages"][0]["blocks"]
+ # Full mode absorbs the contained formula despite different OCR content;
+ # merely intersecting rows and generated equation numbers still survive.
+ expected = [0, 2, 3, 5, 6] if enabled else [0, 1, 2, 3, 5, 6]
+ assert [block["idx"] for block in final] == expected
+ expected_content = ["paragraph", "text", r"y\tag{2}", "picture", "caption"] if enabled else [
+ "paragraph", "x", "text", r"y\tag{2}", "picture", "caption",
+ ]
+ assert [block["content"] for block in final] == expected_content
+ markdown = result["outputs"]["markdown"]
+ assert "caption" in markdown
+ assert "(2)" in markdown # Generated numbering has no LA confidence to compare.
+ assert len(blocks) == 6
+
+
+def test_orchestrator_cancels_recognition_when_reading_order_fails(monkeypatch):
+ recognition_started = asyncio.Event()
+ recognition_cancelled = asyncio.Event()
+
+ async def analyze_layouts(_images, _model_options=None):
+ return [[_block(0), _block(1)]]
+
+ async def fail_reading_order(_pages_blocks, _images, _semaphore):
+ await recognition_started.wait()
+ raise RuntimeError("reading-order failed")
+
+ async def recognize(
+ _pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ recognition_started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ recognition_cancelled.set()
+
+ monkeypatch.setattr(orchestrator.cv2, "imdecode", lambda *_args: np.zeros((8, 8, 3), dtype=np.uint8))
+ monkeypatch.setattr(orchestrator, "analyze_layouts", analyze_layouts)
+ monkeypatch.setattr(orchestrator, "resolve_reading_orders", fail_reading_order)
+ monkeypatch.setattr(orchestrator, "recognize_pages", recognize)
+ monkeypatch.setattr(settings.layout_analyze_model, "provides_reading_order", False)
+
+ with pytest.raises(RuntimeError, match="reading-order failed"):
+ asyncio.run(
+ orchestrator.process_document(b"image", "page.png", ["json"], keep_header_footer=True)
+ )
+
+ assert recognition_cancelled.is_set()
diff --git a/tests/unit/test_postprocess_new_types.py b/tests/unit/test_postprocess_new_types.py
new file mode 100644
index 0000000..16bc6cd
--- /dev/null
+++ b/tests/unit/test_postprocess_new_types.py
@@ -0,0 +1,21 @@
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.chemical_structure_postprocess import postprocess_chemical_structure
+from oxr.pipeline.postprocess.code_postprocess import postprocess_code
+
+
+def test_chemical_structure_postprocess_outputs_somarkdown_smiles():
+ block = Block(0, BlockType.CHEMICAL_STRUCTURE, [0, 0, 1, 1], "", ContentFormat.TEXT)
+
+ result = postprocess_chemical_structure(block, "$\\smiles{CCO}$")
+
+ assert result.content == "$\\smiles{CCO}$"
+ assert result.format == ContentFormat.MARKDOWN
+
+
+def test_code_postprocess_normalizes_markdown_code_block():
+ block = Block(0, BlockType.CODE_BLOCK, [0, 0, 1, 1], "", ContentFormat.TEXT)
+
+ result = postprocess_code(block, "```python\nprint('ok')\n```")
+
+ assert result.content == "```\nprint('ok')\n```"
+ assert result.format == ContentFormat.MARKDOWN
diff --git a/tests/unit/test_queue_and_settings.py b/tests/unit/test_queue_and_settings.py
new file mode 100644
index 0000000..ce58fa0
--- /dev/null
+++ b/tests/unit/test_queue_and_settings.py
@@ -0,0 +1,421 @@
+import asyncio
+import inspect
+
+import pytest
+import typer
+from pydantic import ValidationError
+from typer.testing import CliRunner
+
+from oxr.cli.main import app as cli_app
+from oxr.cli.cmd_serve import _ensure_supported_workers, serve
+from oxr.config.settings import Settings
+from oxr.server.queue.memory_store import MemoryTaskStore
+
+
+def test_memory_task_store_transitions():
+ async def scenario():
+ store = MemoryTaskStore()
+ await store.create("task-1")
+ await store.set_processing("task-1")
+ await store.set_success(
+ "task-1",
+ {
+ "result": {"file_name": "demo.pdf"},
+ "metadata": {"pages": 1},
+ },
+ )
+ return await store.get("task-1")
+
+ task = asyncio.run(scenario())
+
+ assert task == {
+ "record_id": None,
+ "task_id": "task-1",
+ "status": "success",
+ "file_name": None,
+ "result": {"file_name": "demo.pdf"},
+ "error": None,
+ "metadata": {"pages": 1},
+ }
+
+
+def test_settings_load_from_yaml_without_queue_config(tmp_path):
+ config_file = tmp_path / "config.yaml"
+ config_file.write_text(
+ "\n".join(
+ [
+ "server:",
+ " host: 127.0.0.1",
+ "layout_analyze_model:",
+ " url: http://localhost:8081",
+ " batch_size: 4",
+ "oxr_model:",
+ " url: http://localhost:8080/v1",
+ " max_concurrency: 8",
+ "pipeline:",
+ " image_output_dir: parsed",
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ settings = Settings.load_from_yaml(str(config_file))
+
+ assert settings.server.host == "127.0.0.1"
+ assert settings.layout_analyze_model.url == "http://localhost:8081"
+ assert settings.layout_analyze_model.batch_size == 4
+ assert settings.layout_analyze_model.nms_iou_threshold == 0.6
+ assert settings.oxr_model.url == "http://localhost:8080/v1"
+ assert settings.oxr_model.max_concurrency == 8
+ assert settings.pipeline.image_output_dir == "parsed"
+ assert settings.server.workers == 1
+
+
+def test_settings_loads_layout_score_threshold_from_yaml(tmp_path):
+ config_file = tmp_path / "config.yaml"
+ config_file.write_text(
+ "\n".join(
+ [
+ "layout_analyze_model:",
+ " url: http://localhost:8081",
+ " score_threshold: 0.65",
+ "oxr_model:",
+ " url: http://localhost:8080/v1",
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ loaded = Settings.load_from_yaml(str(config_file))
+
+ assert loaded.layout_analyze_model.score_threshold == 0.65
+
+
+def test_settings_reads_layout_score_threshold_from_environment(monkeypatch):
+ monkeypatch.setenv("OXR__LAYOUT_ANALYZE_MODEL__SCORE_THRESHOLD", "0.7")
+
+ loaded = Settings()
+
+ assert loaded.layout_analyze_model.score_threshold == 0.7
+
+
+def test_settings_reads_layout_nms_threshold_from_environment(monkeypatch):
+ monkeypatch.setenv("OXR__LAYOUT_ANALYZE_MODEL__NMS_IOU_THRESHOLD", "0.55")
+
+ loaded = Settings()
+
+ assert loaded.layout_analyze_model.nms_iou_threshold == 0.55
+
+
+def test_pipeline_full_overlap_dedupe_defaults_to_false():
+ loaded = Settings()
+
+ assert loaded.pipeline.model_dump() == {
+ "image_output_dir": "outputs",
+ "full_overlap_dedupe": False,
+ "table_image_placeholders": False,
+ "table_image_min_score": 0.5,
+ }
+
+
[email protected]("enabled", [True, False])
+def test_full_overlap_dedupe_loads_from_yaml_and_environment(tmp_path, monkeypatch, enabled):
+ monkeypatch.setenv("OXR__PIPELINE__FULL_OVERLAP_DEDUPE", str(enabled).lower())
+ assert Settings().pipeline.full_overlap_dedupe is enabled
+ config_file = tmp_path / "config.yaml"
+ config_file.write_text(
+ f"pipeline:\n full_overlap_dedupe: {str(not enabled).lower()}\n", encoding="utf-8",
+ )
+ assert Settings.load_from_yaml(str(config_file)).pipeline.full_overlap_dedupe is not enabled
+
+
+def test_full_overlap_dedupe_rejects_invalid_boolean():
+ with pytest.raises(ValidationError, match="full_overlap_dedupe"):
+ Settings(pipeline={"full_overlap_dedupe": "typo"})
+
+
[email protected]("enabled", [True, False])
+def test_table_image_setting_loads_yaml_and_environment(tmp_path, monkeypatch, enabled):
+ monkeypatch.setenv("OXR__PIPELINE__TABLE_IMAGE_PLACEHOLDERS", str(enabled).lower())
+ monkeypatch.setenv("OXR__PIPELINE__TABLE_IMAGE_MIN_SCORE", "0.75")
+ assert Settings().pipeline.table_image_placeholders is enabled
+ assert Settings().pipeline.table_image_min_score == 0.75
+ config = tmp_path / "config.yaml"
+ config.write_text(
+ f"pipeline:\n table_image_placeholders: {str(not enabled).lower()}\n"
+ " table_image_min_score: 0.6\n", encoding="utf-8",
+ )
+ loaded = Settings.load_from_yaml(str(config))
+ assert loaded.pipeline.table_image_placeholders is not enabled
+ assert loaded.pipeline.table_image_min_score == 0.6
+
+
[email protected]("score", [-0.1, 1.1, float("nan"), float("inf")])
+def test_table_image_score_rejects_invalid_values(score):
+ with pytest.raises(ValidationError, match="table_image_min_score"):
+ Settings(pipeline={"table_image_min_score": score})
+
+
[email protected]("enabled", [True, False])
+def test_table_image_cli_overrides_yaml_and_exports_runtime_environment(tmp_path, monkeypatch, enabled):
+ from oxr.config.settings import settings as runtime_settings
+
+ config = tmp_path / "config.yaml"
+ config.write_text(
+ "layout_analyze_model:\n url: http://layout:8081\noxr_model:\n url: http://oxr:8080/v1\n"
+ f"pipeline:\n table_image_placeholders: {str(not enabled).lower()}\n table_image_min_score: 0.6\n",
+ encoding="utf-8",
+ )
+ for field in ("server", "layout_analyze_model", "oxr_model", "pipeline"):
+ monkeypatch.setattr(runtime_settings, field, getattr(runtime_settings, field))
+ captured = {}
+ monkeypatch.setattr("oxr.cli.cmd_serve.os.environ", captured)
+ monkeypatch.setattr("oxr.cli.cmd_serve.uvicorn.run", lambda *a, **k: None)
+ flag = "--table-image-placeholders" if enabled else "--no-table-image-placeholders"
+ result = CliRunner().invoke(cli_app, ["serve", "--config", str(config), flag, "--table-image-min-score", "0.75"])
+ assert result.exit_code == 0, result.output
+ assert runtime_settings.pipeline.table_image_placeholders is enabled
+ assert captured["OXR__PIPELINE__TABLE_IMAGE_PLACEHOLDERS"] == str(enabled).lower()
+ assert captured["OXR__PIPELINE__TABLE_IMAGE_MIN_SCORE"] == "0.75"
+
+
[email protected]("enabled", [True, False])
+def test_serve_full_overlap_flag_overrides_yaml_and_propagates_environment(tmp_path, monkeypatch, enabled):
+ from oxr.config.settings import settings as runtime_settings
+
+ config_file = tmp_path / "config.yaml"
+ config_file.write_text(
+ "layout_analyze_model:\n url: http://layout:8081\n"
+ "oxr_model:\n url: http://oxr:8080/v1\n"
+ f"pipeline:\n full_overlap_dedupe: {str(not enabled).lower()}\n",
+ encoding="utf-8",
+ )
+ # Restore the global configuration replaced by serve after the test.
+ for field in ("server", "layout_analyze_model", "oxr_model", "pipeline"):
+ monkeypatch.setattr(runtime_settings, field, getattr(runtime_settings, field))
+ captured = {}
+ monkeypatch.setattr("oxr.cli.cmd_serve.os.environ", captured)
+ monkeypatch.setattr("oxr.cli.cmd_serve.uvicorn.run", lambda *args, **kwargs: None)
+ flag = "--full-overlap-dedupe" if enabled else "--no-full-overlap-dedupe"
+ result = CliRunner().invoke(cli_app, ["serve", "--config", str(config_file), flag])
+ assert result.exit_code == 0, result.output
+ assert runtime_settings.pipeline.full_overlap_dedupe is enabled
+ assert captured["OXR__PIPELINE__FULL_OVERLAP_DEDUPE"] == str(enabled).lower()
+
+
+ "field",
+ ["systematic_cross_category_dedupe", "visual_parent_dedupe", "complete_text_dedupe"],
+)
+def test_settings_reject_removed_postprocessing_environment(monkeypatch, field):
+ monkeypatch.setenv(f"OXR__PIPELINE__{field.upper()}", "false")
+
+ with pytest.raises(ValidationError, match=field):
+ Settings()
+
+
+ "field",
+ ["systematic_cross_category_dedupe", "visual_parent_dedupe", "complete_text_dedupe"],
+)
+def test_settings_reject_removed_postprocessing_yaml(tmp_path, field):
+ config_file = tmp_path / "config.yaml"
+ config_file.write_text(f"pipeline:\n {field}: false\n", encoding="utf-8")
+
+ with pytest.raises(ValidationError, match=field):
+ Settings.load_from_yaml(str(config_file))
+
+
[email protected]("value", [-0.01, 1.01])
+def test_layout_score_threshold_must_be_between_zero_and_one(value):
+ with pytest.raises(ValidationError):
+ Settings(layout_analyze_model={"score_threshold": value})
+
+
[email protected]("value", [-0.01, 1.01])
+def test_layout_nms_threshold_must_be_between_zero_and_one(value):
+ with pytest.raises(ValidationError):
+ Settings(layout_analyze_model={"nms_iou_threshold": value})
+
+
+ "pipeline_key",
+ [
+ "layout_batch_size",
+ "max_layout_concurrency",
+ "layout_timeout",
+ "max_recognition_concurrency",
+ "recognition_timeout",
+ "retry_times",
+ ],
+)
+def test_settings_rejects_removed_pipeline_model_bridge_fields(pipeline_key):
+ with pytest.raises(ValidationError, match=pipeline_key):
+ Settings(pipeline={pipeline_key: 1})
+
+
+def test_settings_reads_double_underscore_model_environment(monkeypatch):
+ monkeypatch.setenv("OXR__LAYOUT_ANALYZE_MODEL__URL", "http://layout:8081")
+ monkeypatch.setenv("OXR__OXR_MODEL__URL", "http://oxr:8080/v1")
+
+ settings = Settings()
+
+ assert settings.layout_analyze_model.url == "http://layout:8081"
+ assert settings.oxr_model.url == "http://oxr:8080/v1"
+
+
+def test_settings_use_8k_default_oxr_output_limit():
+ assert Settings().oxr_model.max_tokens == 8192
+
+
+ "config",
+ [
+ {"layout_analyze_model": {"url": "http://layout", "batch_size": 0}},
+ {"oxr_model": {"url": "http://oxr/v1", "max_tokens": 0}},
+ {"layout_analyze_model": {"url": "not-a-url"}},
+ ],
+)
+def test_model_settings_require_positive_values_and_http_urls(config):
+ with pytest.raises(ValidationError):
+ Settings(**config)
+
+
[email protected]("legacy_name", ["OXR_MODEL__URL", "OXR__MODEL__URL"])
+def test_settings_reject_legacy_model_environment(monkeypatch, legacy_name):
+ monkeypatch.setenv(legacy_name, "http://legacy:8080/v1")
+
+ with pytest.raises(ValueError, match="legacy model configuration"):
+ Settings()
+
+
+def test_settings_reject_legacy_model_yaml(tmp_path):
+ config_file = tmp_path / "legacy.yaml"
+ config_file.write_text("model:\n url: http://legacy:8080/v1\n", encoding="utf-8")
+
+ with pytest.raises(ValueError, match="layout_analyze_model.*oxr_model"):
+ Settings.load_from_yaml(str(config_file))
+
+
+def test_server_validation_requires_both_model_urls():
+ with pytest.raises(ValueError, match="layout_analyze_model.url.*oxr_model.url"):
+ Settings().validate_for_server()
+
+
+def test_serve_uses_namespaced_model_flags():
+ options = inspect.signature(serve).parameters
+ option_declarations = {
+ declaration
+ for parameter in options.values()
+ for declaration in parameter.default.param_decls
+ }
+
+ assert "--layout-analyze-model-url" in option_declarations
+ assert "--layout-analyze-model-score-threshold" in option_declarations
+ assert "--layout-analyze-model-nms-iou-threshold" in option_declarations
+ assert "--oxr-model-url" in option_declarations
+
+
+def test_serve_propagates_layout_score_threshold(monkeypatch):
+ from oxr.config.settings import settings as runtime_settings
+
+ captured_environment = {}
+ monkeypatch.setattr(runtime_settings.layout_analyze_model, "url", None)
+ monkeypatch.setattr(runtime_settings.layout_analyze_model, "score_threshold", 0.5)
+ monkeypatch.setattr(runtime_settings.oxr_model, "url", None)
+ monkeypatch.setattr("oxr.cli.cmd_serve.os.environ", captured_environment)
+ monkeypatch.setattr("oxr.cli.cmd_serve.uvicorn.run", lambda *args, **kwargs: None)
+
+ result = CliRunner().invoke(
+ cli_app,
+ [
+ "serve",
+ "--layout-analyze-model-url",
+ "http://layout:8081",
+ "--layout-analyze-model-score-threshold",
+ "0.65",
+ "--oxr-model-url",
+ "http://oxr:8080/v1",
+ ],
+ )
+
+ assert result.exit_code == 0
+ assert captured_environment["OXR__LAYOUT_ANALYZE_MODEL__SCORE_THRESHOLD"] == "0.65"
+
+
+def test_serve_propagates_layout_nms_threshold(monkeypatch):
+ from oxr.config.settings import settings as runtime_settings
+
+ captured_environment = {}
+ monkeypatch.setattr(runtime_settings.layout_analyze_model, "url", None)
+ monkeypatch.setattr(runtime_settings.oxr_model, "url", None)
+ monkeypatch.setattr("oxr.cli.cmd_serve.os.environ", captured_environment)
+ monkeypatch.setattr("oxr.cli.cmd_serve.uvicorn.run", lambda *args, **kwargs: None)
+
+ result = CliRunner().invoke(
+ cli_app,
+ [
+ "serve",
+ "--layout-analyze-model-url",
+ "http://layout:8081",
+ "--layout-analyze-model-nms-iou-threshold",
+ "0.55",
+ "--oxr-model-url",
+ "http://oxr:8080/v1",
+ ],
+ )
+
+ assert result.exit_code == 0
+ assert captured_environment["OXR__LAYOUT_ANALYZE_MODEL__NMS_IOU_THRESHOLD"] == "0.55"
+
+
+ ("legacy_flag", "value", "replacement"),
+ [
+ ("--model-url", "http://legacy:8080/v1", "--oxr-model-url"),
+ ("--model-name", "legacy", "--oxr-model-name"),
+ ("--max-tokens", "1024", "--oxr-model-max-tokens"),
+ ("--layout-batch-size", "4", "--layout-analyze-model-batch-size"),
+ ("--max-layout-concurrency", "2", "--layout-analyze-model-max-concurrency"),
+ ("--max-recognition-concurrency", "8", "--oxr-model-max-concurrency"),
+ ],
+)
+def test_serve_legacy_flags_report_explicit_migration_mapping(
+ legacy_flag,
+ value,
+ replacement,
+):
+ result = CliRunner().invoke(cli_app, ["serve", legacy_flag, value])
+
+ assert result.exit_code == 2
+ normalized_output = " ".join(result.output.replace("│", "").split())
+ assert f"{legacy_flag} is no longer supported; use" in normalized_output
+ assert replacement in normalized_output
+
+
+def test_serve_help_hides_legacy_flags():
+ result = CliRunner().invoke(cli_app, ["serve", "--help"])
+
+ assert result.exit_code == 0
+ assert "--model-url" not in result.output
+ assert "--model-name" not in result.output
+ assert "--max-tokens" not in result.output
+ assert "--layout-batch-size" not in result.output
+ assert "--max-layout-concurrency" not in result.output
+ assert "--max-recognition-concurrency" not in result.output
+
+
+def test_settings_reads_debug_from_plain_environment(monkeypatch):
+ monkeypatch.setenv("DEBUG", "yes")
+ assert Settings().debug is True
+
+ monkeypatch.setenv("DEBUG", "false")
+ assert Settings().debug is False
+
+ monkeypatch.delenv("DEBUG")
+ assert Settings().debug is False
+
+
+def test_workers_must_be_single_process():
+ with pytest.raises(typer.BadParameter):
+ _ensure_supported_workers(2)
diff --git a/tests/unit/test_reading_order.py b/tests/unit/test_reading_order.py
new file mode 100644
index 0000000..2055fdf
--- /dev/null
+++ b/tests/unit/test_reading_order.py
@@ -0,0 +1,482 @@
+import asyncio
+
+import numpy as np
+import pytest
+
+import oxr.pipeline.reading_order as reading_order_module
+from oxr.config.settings import OXRModelConfig, settings
+from oxr.model.prompts import build_reading_order_prompt
+from oxr.pipeline.errors import PipelineError
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.reading_order import (
+ parse_reading_order,
+ repair_incomplete_reading_order,
+ resolve_reading_orders,
+ supplement_incomplete_reading_order,
+)
+
+
+def _block(idx: int, block_type: BlockType, bbox: list[float]) -> Block:
+ return Block(idx, block_type, bbox, "", ContentFormat.TEXT)
+
+
+def test_build_reading_order_prompt_matches_oxr_model_pixel_normalization():
+ prompt = build_reading_order_prompt(
+ {
+ "ref": [BlockType.TITLE.value, BlockType.TEXT.value],
+ "bbox": [[10, 20, 110, 80], [0, 0, 200, 100]],
+ "bbox_type": "real",
+ },
+ image_size=(200, 100),
+ )
+
+ assert prompt == """
+Given the detected layout boxes below, output the reading order as a whitespace-separated permutation of 0-based box IDs only.
+
+Boxes:
+0 | <|object_ref_start|>Title<|object_ref_end|> | <|box_start|>(50,200),(550,800)<|box_end|>
+1 | <|object_ref_start|>Text<|object_ref_end|> | <|box_start|>(0,0),(1000,1000)<|box_end|>
+
+Output only the box IDs."""
+
+
+ ("raw_text", "block_count", "expected"),
+ [
+ ("", 0, []),
+ (" \n\t", 0, []),
+ ("0", 1, [0]),
+ ("2 0\n1\t3", 4, [2, 0, 1, 3]),
+ ("2\r\n0\u20031", 3, [2, 0, 1]),
+ ],
+)
+def test_parse_reading_order_accepts_only_whitespace_separated_permutations(
+ raw_text,
+ block_count,
+ expected,
+):
+ assert parse_reading_order(raw_text, block_count) == expected
+
+
+ ("raw_text", "block_count"),
+ [
+ ("0, 1", 2),
+ ("order: 0 1", 2),
+ ("```\n0 1\n```", 2),
+ ("0 0", 2),
+ ("0", 2),
+ ("0 1 2", 2),
+ ("0 2", 2),
+ ("-1 0", 2),
+ ],
+)
+def test_parse_reading_order_rejects_invalid_syntax_or_non_permutations(raw_text, block_count):
+ with pytest.raises(ValueError, match="reading order"):
+ parse_reading_order(raw_text, block_count)
+
+
+def test_repair_incomplete_reading_order_preserves_model_order():
+ blocks = [
+ _block(0, BlockType.TEXT, [50, 50, 80, 80]),
+ _block(1, BlockType.TEXT, [10, 10, 40, 30]),
+ _block(2, BlockType.TEXT, [50, 10, 90, 30]),
+ ]
+
+ assert repair_incomplete_reading_order("1 0", blocks) == [1, 2, 0]
+
+
+def test_repair_incomplete_reading_order_accepts_two_of_many_missing():
+ blocks = [
+ _block(index, BlockType.TEXT, [0, index * 10, 10, (index + 1) * 10])
+ for index in range(20)
+ ]
+ partial_order = " ".join(str(index) for index in range(20) if index not in {3, 17})
+
+ assert repair_incomplete_reading_order(partial_order, blocks) == list(range(20))
+
+
+def test_xycut_supplement_preserves_oxr_order_and_collapses_duplicates(monkeypatch):
+ blocks = [
+ _block(index, BlockType.TEXT, [0, index * 10, 10, (index + 1) * 10])
+ for index in range(4)
+ ]
+ monkeypatch.setattr(
+ reading_order_module,
+ "xycut_plus_order",
+ lambda _blocks: [0, 1, 2, 3],
+ )
+
+ supplemented = supplement_incomplete_reading_order("3 1 1", blocks)
+
+ assert supplemented == [0, 2, 3, 1]
+ assert [block_id for block_id in supplemented if block_id in {3, 1}] == [3, 1]
+
+
+def test_xycut_supplement_rejects_output_with_less_than_half_coverage():
+ blocks = [
+ _block(index, BlockType.TEXT, [0, index * 10, 10, (index + 1) * 10])
+ for index in range(5)
+ ]
+
+ assert supplement_incomplete_reading_order("1 1", blocks) is None
+
+
+def test_xycut_supplement_rejects_out_of_range_ids():
+ blocks = [
+ _block(index, BlockType.TEXT, [0, index * 10, 10, (index + 1) * 10])
+ for index in range(4)
+ ]
+
+ assert supplement_incomplete_reading_order("0 1 4", blocks) is None
+
+
+def test_xycut_supplement_handles_dense_page_without_reordering_oxr_ids():
+ blocks = [
+ _block(index, BlockType.TEXT, [0, index * 4, 100, index * 4 + 3])
+ for index in range(300)
+ ]
+ oxr_order = list(range(180))
+ raw_order = " ".join(str(index) for index in [*oxr_order, *range(100)])
+
+ supplemented = supplement_incomplete_reading_order(raw_order, blocks)
+
+ assert supplemented is not None
+ assert sorted(supplemented) == list(range(300))
+ assert [block_id for block_id in supplemented if block_id < 180] == oxr_order
+
+
[email protected]("raw_text", ["0 0", "0 3", "0", "order: 0 1"])
+def test_repair_incomplete_reading_order_rejects_ambiguous_output(raw_text):
+ blocks = [
+ _block(0, BlockType.TEXT, [0, 0, 10, 10]),
+ _block(1, BlockType.TEXT, [0, 10, 10, 20]),
+ _block(2, BlockType.TEXT, [0, 20, 10, 30]),
+ ]
+
+ assert repair_incomplete_reading_order(raw_text, blocks) is None
+
+
+def test_resolve_reading_orders_fast_paths_zero_and_one_block_without_oxr(monkeypatch):
+ async def unexpected_request(*_args, **_kwargs):
+ raise AssertionError("OXR must not be called for zero or one block")
+
+ monkeypatch.setattr(
+ "oxr.pipeline.reading_order.model_client.request_reading_order",
+ unexpected_request,
+ )
+
+ image = np.zeros((100, 200, 3), dtype=np.uint8)
+ pages = [[], [_block(0, BlockType.TEXT, [10, 20, 110, 80])]]
+ result = asyncio.run(resolve_reading_orders(pages, [image, image], asyncio.Semaphore(1)))
+
+ assert result == [[], [0]]
+
+
+def test_resolve_reading_orders_uses_original_image_labels_token_cap_and_retries(monkeypatch):
+ calls = []
+ original_image = np.zeros((100, 200, 3), dtype=np.uint8)
+ blocks = [
+ _block(9, BlockType.TITLE, [10, 20, 110, 80]),
+ _block(4, BlockType.TEXT, [0, 0, 200, 100]),
+ ]
+
+ async def request(prompt, image, max_tokens):
+ calls.append((prompt, image, max_tokens))
+ if len(calls) == 1:
+ raise RuntimeError("retry me")
+ return "1 0"
+
+ async def no_delay(_seconds):
+ return None
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 2)
+ monkeypatch.setattr(settings.oxr_model, "max_tokens", 12)
+ monkeypatch.setattr("oxr.pipeline.reading_order.model_client.request_reading_order", request)
+ monkeypatch.setattr("oxr.pipeline.reading_order.asyncio.sleep", no_delay)
+
+ result = asyncio.run(resolve_reading_orders([blocks], [original_image], asyncio.Semaphore(1)))
+
+ assert result == [[1, 0]]
+ assert len(calls) == 2
+ assert all(image is original_image for _prompt, image, _max_tokens in calls)
+ assert all(max_tokens == 12 for _prompt, _image, max_tokens in calls)
+ assert (
+ "0 | <|object_ref_start|>Title<|object_ref_end|> | "
+ "<|box_start|>(50,200),(550,800)<|box_end|>"
+ ) in calls[0][0]
+ assert (
+ "1 | <|object_ref_start|>Text<|object_ref_end|> | "
+ "<|box_start|>(0,0),(1000,1000)<|box_end|>"
+ ) in calls[0][0]
+
+
+def test_reading_order_token_cap_has_sixteen_token_floor(monkeypatch):
+ captured = {}
+
+ async def request(_prompt, _image, max_tokens):
+ captured["max_tokens"] = max_tokens
+ return "0 1"
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr(settings.oxr_model, "max_tokens", 4096)
+ monkeypatch.setattr("oxr.pipeline.reading_order.model_client.request_reading_order", request)
+
+ image = np.zeros((10, 10, 3), dtype=np.uint8)
+ blocks = [
+ _block(0, BlockType.TEXT, [0, 0, 5, 5]),
+ _block(1, BlockType.TEXT, [5, 5, 10, 10]),
+ ]
+ asyncio.run(resolve_reading_orders([blocks], [image], asyncio.Semaphore(1)))
+
+ assert captured["max_tokens"] == 16
+
+
+def test_resolve_reading_orders_uses_injected_client_and_config():
+ calls = []
+ config = OXRModelConfig(
+ url="http://oxr.example/v1",
+ max_tokens=9,
+ retry_times=1,
+ )
+
+ class Client:
+ async def request_reading_order(self, prompt, image, max_tokens):
+ calls.append((prompt, image, max_tokens))
+ return "1 0"
+
+ image = np.zeros((100, 200, 3), dtype=np.uint8)
+ blocks = [
+ _block(0, BlockType.TITLE, [0, 0, 100, 50]),
+ _block(1, BlockType.TEXT, [0, 50, 100, 100]),
+ ]
+ result = asyncio.run(
+ resolve_reading_orders(
+ [blocks],
+ [image],
+ asyncio.Semaphore(1),
+ client=Client(),
+ config=config,
+ )
+ )
+
+ assert result == [[1, 0]]
+ assert len(calls) == 1
+ assert calls[0][1] is image
+ assert calls[0][2] == 9
+
+
+def test_invalid_reading_order_falls_back_to_xycut_without_logging_raw_text(
+ caplog,
+ monkeypatch,
+):
+ calls = []
+
+ async def request(_prompt, _image, _max_tokens):
+ calls.append(1)
+ return "0 0 4"
+
+ async def no_delay(_seconds):
+ return None
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 2)
+ monkeypatch.setattr(
+ "oxr.pipeline.reading_order.model_client.request_reading_order",
+ request,
+ )
+ monkeypatch.setattr(
+ reading_order_module,
+ "xycut_plus_order",
+ lambda _blocks: [2, 1, 0],
+ )
+ monkeypatch.setattr("oxr.pipeline.reading_order.asyncio.sleep", no_delay)
+ image = np.zeros((10, 10, 3), dtype=np.uint8)
+ blocks = [
+ _block(0, BlockType.TEXT, [0, 0, 3, 10]),
+ _block(1, BlockType.TEXT, [3, 0, 6, 10]),
+ _block(2, BlockType.TEXT, [6, 0, 10, 10]),
+ ]
+
+ with caplog.at_level("WARNING", logger="oxr.pipeline.reading_order"):
+ result = asyncio.run(
+ resolve_reading_orders([blocks], [image], asyncio.Semaphore(1))
+ )
+
+ assert result == [[2, 1, 0]]
+ assert len(calls) == 2
+ assert "reading_order_xycut_fallback" in caplog.text
+ assert "missing_ids=[1, 2]" in caplog.text
+ assert "duplicate_ids=[0]" in caplog.text
+ assert "out_of_range_ids=[4]" in caplog.text
+ assert "raw_sha256=" in caplog.text
+ assert "raw_text=" not in caplog.text
+
+
[email protected]("raw_text", ["order: 0 1", "0"])
+def test_unusable_reading_order_uses_xycut_only_on_final_attempt(
+ raw_text,
+ caplog,
+ monkeypatch,
+):
+ calls = []
+ config = OXRModelConfig(
+ url="http://oxr.example/v1",
+ max_tokens=32,
+ retry_times=2,
+ )
+
+ class Client:
+ async def request_reading_order(self, _prompt, _image, _max_tokens):
+ calls.append(1)
+ return raw_text
+
+ monkeypatch.setattr(
+ reading_order_module,
+ "xycut_plus_order",
+ lambda _blocks: [2, 0, 1],
+ )
+
+ async def no_delay(_seconds):
+ return None
+
+ monkeypatch.setattr(reading_order_module.asyncio, "sleep", no_delay)
+ image = np.zeros((100, 100, 3), dtype=np.uint8)
+ blocks = [
+ _block(index, BlockType.TEXT, [0, index * 10, 10, (index + 1) * 10])
+ for index in range(3)
+ ]
+
+ with caplog.at_level("WARNING", logger="oxr.pipeline.reading_order"):
+ result = asyncio.run(
+ resolve_reading_orders(
+ [blocks],
+ [image],
+ asyncio.Semaphore(1),
+ client=Client(),
+ config=config,
+ )
+ )
+
+ assert result == [[2, 0, 1]]
+ assert len(calls) == 2
+ assert caplog.text.count("reading_order_invalid") == 1
+ assert caplog.text.count("reading_order_xycut_fallback") == 1
+
+
+def test_reading_order_request_failure_does_not_fall_back_to_xycut(monkeypatch):
+ calls = []
+ xycut_calls = []
+
+ async def request(_prompt, _image, _max_tokens):
+ calls.append(1)
+ raise TimeoutError("model unavailable")
+
+ async def no_delay(_seconds):
+ return None
+
+ def xycut(_blocks):
+ xycut_calls.append(1)
+ return [0, 1]
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 2)
+ monkeypatch.setattr(
+ "oxr.pipeline.reading_order.model_client.request_reading_order",
+ request,
+ )
+ monkeypatch.setattr(reading_order_module, "xycut_plus_order", xycut)
+ monkeypatch.setattr(reading_order_module.asyncio, "sleep", no_delay)
+ image = np.zeros((10, 10, 3), dtype=np.uint8)
+ blocks = [
+ _block(0, BlockType.TEXT, [0, 0, 5, 10]),
+ _block(1, BlockType.TEXT, [5, 0, 10, 10]),
+ ]
+
+ with pytest.raises(PipelineError, match="Reading order failed"):
+ asyncio.run(resolve_reading_orders([blocks], [image], asyncio.Semaphore(1)))
+
+ assert len(calls) == 2
+ assert xycut_calls == []
+
+
+def test_incomplete_reading_order_is_repaired_without_retry(caplog):
+ calls = []
+ config = OXRModelConfig(
+ url="http://oxr.example/v1",
+ max_tokens=32,
+ retry_times=2,
+ )
+
+ class Client:
+ async def request_reading_order(self, _prompt, _image, _max_tokens):
+ calls.append(1)
+ return "1 0"
+
+ image = np.zeros((100, 100, 3), dtype=np.uint8)
+ blocks = [
+ _block(0, BlockType.TEXT, [50, 50, 80, 80]),
+ _block(1, BlockType.TEXT, [10, 10, 40, 30]),
+ _block(2, BlockType.TEXT, [50, 10, 90, 30]),
+ ]
+
+ with caplog.at_level("WARNING", logger="oxr.pipeline.reading_order"):
+ result = asyncio.run(
+ resolve_reading_orders(
+ [blocks],
+ [image],
+ asyncio.Semaphore(1),
+ client=Client(),
+ config=config,
+ )
+ )
+
+ assert result == [[1, 2, 0]]
+ assert len(calls) == 1
+ assert "reading_order_repaired" in caplog.text
+ assert "missing_ids=[2]" in caplog.text
+ assert "raw_text=" not in caplog.text
+
+
+def test_broad_xycut_supplement_runs_only_after_final_retry(caplog, monkeypatch):
+ calls = []
+ config = OXRModelConfig(
+ url="http://oxr.example/v1",
+ max_tokens=32,
+ retry_times=2,
+ )
+
+ class Client:
+ async def request_reading_order(self, _prompt, _image, _max_tokens):
+ calls.append(1)
+ return "3 1 1"
+
+ monkeypatch.setattr(
+ reading_order_module,
+ "xycut_plus_order",
+ lambda _blocks: [0, 1, 2, 3],
+ )
+
+ async def no_delay(_seconds):
+ return None
+
+ monkeypatch.setattr(reading_order_module.asyncio, "sleep", no_delay)
+ image = np.zeros((100, 100, 3), dtype=np.uint8)
+ blocks = [
+ _block(index, BlockType.TEXT, [0, index * 10, 10, (index + 1) * 10])
+ for index in range(4)
+ ]
+
+ with caplog.at_level("WARNING", logger="oxr.pipeline.reading_order"):
+ result = asyncio.run(
+ resolve_reading_orders(
+ [blocks],
+ [image],
+ asyncio.Semaphore(1),
+ client=Client(),
+ config=config,
+ )
+ )
+
+ assert result == [[0, 2, 3, 1]]
+ assert len(calls) == 2
+ assert "reading_order_supplemented" in caplog.text
+ assert "missing_ids=[0, 2]" in caplog.text
diff --git a/tests/unit/test_recognition_routing.py b/tests/unit/test_recognition_routing.py
new file mode 100644
index 0000000..db227d4
--- /dev/null
+++ b/tests/unit/test_recognition_routing.py
@@ -0,0 +1,271 @@
+import asyncio
+
+import numpy as np
+from oxr.config.settings import settings
+from oxr.model.client import ModelOutput
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.recognition import recognize_block
+
+
+def _block(block_type: BlockType) -> Block:
+ return Block(0, block_type, [0, 0, 4, 4], "", ContentFormat.TEXT)
+
+
+def test_recognition_routes_by_block_type(monkeypatch, tmp_path):
+ calls = []
+
+ async def record(name):
+ async def inner(_image, _model_options=None):
+ calls.append(name)
+ return {
+ "text": "hello",
+ "table": "<table></table>",
+ "formula": "x^2",
+ "code": "print('ok')",
+ "chemical": "CCO",
+ }[name]
+ return inner
+
+ monkeypatch.setattr(settings.pipeline, "image_output_dir", str(tmp_path))
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_text", asyncio.run(record("text")))
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_table", asyncio.run(record("table")))
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_formula", asyncio.run(record("formula")))
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_code", asyncio.run(record("code")))
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_chemical_structure",
+ asyncio.run(record("chemical")),
+ )
+
+ async def scenario():
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ sem = asyncio.Semaphore(8)
+ results = []
+ for block_type in [
+ BlockType.TEXT,
+ BlockType.STAMP,
+ BlockType.CHEMICAL_STRUCTURE,
+ BlockType.TABLE,
+ BlockType.FORMULA,
+ BlockType.CODE_BLOCK,
+ BlockType.PICTURE,
+ ]:
+ results.append(await recognize_block(_block(block_type), image, sem, "demo.png", 0))
+ return results
+
+ results = asyncio.run(scenario())
+
+ assert calls == ["text", "text", "chemical", "table", "formula", "code"]
+ assert results[2].content == "$\\smiles{CCO}$"
+ assert results[3].format == ContentFormat.HTML
+ assert results[4].format == ContentFormat.LATEX
+ assert results[5].format == ContentFormat.MARKDOWN
+ assert results[6].format == ContentFormat.MARKDOWN
+
+
+def test_recognition_outputs_table_markdown_when_requested(monkeypatch):
+ async def recognize_table(_image, _model_options=None):
+ return "<table><tr><th>A</th></tr><tr><td>B</td></tr></table>"
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_table", recognize_table)
+
+ async def scenario():
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ sem = asyncio.Semaphore(8)
+ return await recognize_block(
+ _block(BlockType.TABLE),
+ image,
+ sem,
+ "demo.png",
+ 0,
+ element_formats={"table": "markdown"},
+ )
+
+ result = asyncio.run(scenario())
+
+ assert result.format == ContentFormat.MARKDOWN
+ assert result.content == "| A |\n| --- |\n| B |"
+
+
+def test_recognition_routes_chemical_structure_smiles(monkeypatch):
+ async def recognize_chemical_structure(_image, _model_options=None):
+ return "CCO"
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_chemical_structure",
+ recognize_chemical_structure,
+ )
+
+ async def scenario():
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ sem = asyncio.Semaphore(8)
+ return await recognize_block(
+ _block(BlockType.CHEMICAL_STRUCTURE),
+ image,
+ sem,
+ "demo.png",
+ 0,
+ element_formats={"cs": "smiles"},
+ )
+
+ result = asyncio.run(scenario())
+
+ assert result.format == ContentFormat.MARKDOWN
+ assert result.content == "$\\smiles{CCO}$"
+
+
+def test_recognition_routes_chemical_structure_image(monkeypatch, tmp_path):
+ calls = []
+
+ async def recognize_text(_image, _model_options=None):
+ calls.append("text")
+ return "CCO"
+
+ monkeypatch.setattr(settings.pipeline, "image_output_dir", str(tmp_path))
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr("oxr.pipeline.recognition.model_client.recognize_text", recognize_text)
+
+ async def scenario():
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ sem = asyncio.Semaphore(8)
+ return await recognize_block(
+ _block(BlockType.CHEMICAL_STRUCTURE),
+ image,
+ sem,
+ "demo.png",
+ 0,
+ element_formats={"cs": "image"},
+ )
+
+ result = asyncio.run(scenario())
+
+ assert calls == []
+ assert result.format == ContentFormat.MARKDOWN
+ assert result.content.startswith("![](")
+ assert (tmp_path / "demo" / "imgs" / "0_0.png").exists()
+
+
+def test_text_length_response_retries_with_repetition_penalty(monkeypatch):
+ calls = []
+
+ async def recognize_text(image, model_options=None):
+ calls.append((image, model_options))
+ if len(calls) == 1:
+ return ModelOutput("looping", finish_reason="length")
+ return ModelOutput("recovered", finish_reason="stop")
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_text",
+ recognize_text,
+ )
+
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ result = asyncio.run(
+ recognize_block(
+ _block(BlockType.TEXT),
+ image,
+ asyncio.Semaphore(1),
+ "demo.png",
+ 0,
+ model_options={"temperature": 0.0},
+ )
+ )
+
+ assert result.content == "recovered"
+ assert len(calls) == 2
+ assert calls[0][0].shape == (4, 4, 3)
+ assert calls[1][0] is calls[0][0]
+ assert calls[0][1] == {"temperature": 0.0}
+ assert calls[1][1] == {
+ "temperature": 0.0,
+ "repetition_penalty": 1.1,
+ }
+
+
+def test_table_length_response_retries_with_downscaled_crop(monkeypatch):
+ calls = []
+
+ async def recognize_table(image, model_options=None):
+ calls.append((image, model_options))
+ if len(calls) == 1:
+ return ModelOutput("<table>", finish_reason="length")
+ return ModelOutput("<table></table>", finish_reason="stop")
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_table",
+ recognize_table,
+ )
+
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ result = asyncio.run(
+ recognize_block(
+ _block(BlockType.TABLE),
+ image,
+ asyncio.Semaphore(1),
+ "demo.png",
+ 0,
+ )
+ )
+
+ assert result.content == "<table></table>"
+ assert [call[0].shape for call in calls] == [(4, 4, 3), (3, 3, 3)]
+ assert calls[0][1] is None
+ assert calls[1][1] is None
+
+
+def test_unrecovered_text_length_response_preserves_model_output(monkeypatch):
+ calls = []
+
+ async def recognize_text(_image, _model_options=None):
+ calls.append(_model_options)
+ return ModelOutput("looping", finish_reason="length")
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_text",
+ recognize_text,
+ )
+
+ result = asyncio.run(
+ recognize_block(
+ _block(BlockType.TEXT),
+ np.zeros((8, 8, 3), dtype=np.uint8),
+ asyncio.Semaphore(1),
+ "demo.png",
+ 0,
+ )
+ )
+
+ assert result.content == "looping"
+ assert calls == [None, {"repetition_penalty": 1.1}]
+
+
+def test_formula_length_response_preserves_model_output_without_retry(monkeypatch):
+ calls = []
+
+ async def recognize_formula(_image, _model_options=None):
+ calls.append(_model_options)
+ return ModelOutput("x^2", finish_reason="length")
+
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_formula",
+ recognize_formula,
+ )
+
+ result = asyncio.run(
+ recognize_block(
+ _block(BlockType.FORMULA),
+ np.zeros((8, 8, 3), dtype=np.uint8),
+ asyncio.Semaphore(1),
+ "demo.png",
+ 0,
+ )
+ )
+
+ assert result.content == "x^2"
+ assert calls == [None]
diff --git a/tests/unit/test_server_lifespan.py b/tests/unit/test_server_lifespan.py
new file mode 100644
index 0000000..c506caf
--- /dev/null
+++ b/tests/unit/test_server_lifespan.py
@@ -0,0 +1,55 @@
+import asyncio
+
+import pytest
+
+from oxr.config.settings import settings
+from oxr.server.app import app, lifespan
+
+
+ ("layout_url", "oxr_url", "missing_name"),
+ [
+ (None, "http://oxr:8080/v1", "layout_analyze_model.url"),
+ ("http://layout:8081", None, "oxr_model.url"),
+ ],
+)
+def test_direct_asgi_lifespan_requires_both_model_urls(
+ monkeypatch,
+ layout_url,
+ oxr_url,
+ missing_name,
+):
+ monkeypatch.setattr(settings.layout_analyze_model, "url", layout_url)
+ monkeypatch.setattr(settings.oxr_model, "url", oxr_url)
+
+ async def scenario():
+ with pytest.raises(ValueError, match=missing_name):
+ async with lifespan(app):
+ pass
+
+ asyncio.run(scenario())
+
+
+def test_lifespan_closes_both_clients_when_one_close_fails(monkeypatch):
+ closed = []
+ monkeypatch.setattr(settings.layout_analyze_model, "url", "http://layout:8081")
+ monkeypatch.setattr(settings.oxr_model, "url", "http://oxr:8080/v1")
+
+ async def close_layout():
+ closed.append("layout")
+ raise RuntimeError("layout close failed")
+
+ async def close_oxr():
+ closed.append("oxr")
+
+ monkeypatch.setattr("oxr.server.app.layout_client.aclose", close_layout)
+ monkeypatch.setattr("oxr.server.app.model_client.aclose", close_oxr)
+
+ async def scenario():
+ with pytest.raises(RuntimeError, match="layout close failed"):
+ async with lifespan(app):
+ pass
+
+ asyncio.run(scenario())
+
+ assert closed == ["layout", "oxr"]
diff --git a/tests/unit/test_somark_api_contract.py b/tests/unit/test_somark_api_contract.py
new file mode 100644
index 0000000..8779a09
--- /dev/null
+++ b/tests/unit/test_somark_api_contract.py
@@ -0,0 +1,651 @@
+import asyncio
+import json
+
+import numpy as np
+import pytest
+from fastapi.testclient import TestClient
+from typer.testing import CliRunner
+
+from oxr.cli.main import app as cli_app
+from oxr.config.settings import settings
+from oxr.pipeline import orchestrator
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.server.app import app
+from oxr.server import routes
+
+
[email protected](autouse=True)
+def configure_server_model_urls(monkeypatch):
+ monkeypatch.setattr(settings.layout_analyze_model, "url", "http://layout:8081")
+ monkeypatch.setattr(settings.oxr_model, "url", "http://oxr:8080/v1")
+
+
+def test_oxr_help_exposes_only_supported_commands():
+ assert {command.name for command in cli_app.registered_commands} == {"serve"}
+
+ result = CliRunner().invoke(cli_app, ["--help"])
+
+ assert result.exit_code == 0
+ assert "serve" in result.output
+ assert "app" not in result.output
+ assert "parse" not in result.output
+
+
+def test_removed_app_command_is_rejected(monkeypatch):
+ def unexpected_server_start(*args, **kwargs):
+ pytest.fail("An unsupported command must not start the server")
+
+ monkeypatch.setattr("oxr.cli.cmd_serve.uvicorn.run", unexpected_server_start)
+ result = CliRunner().invoke(cli_app, ["app"])
+
+ assert result.exit_code == 2
+ assert "No such command 'app'" in result.output
+
+
+def test_parse_sync_accepts_default_somark_element_formats(monkeypatch):
+ captured = {}
+
+ async def fake_process_document(
+ _file_bytes,
+ _file_name,
+ output_formats,
+ keep_header_footer=False,
+ model_options=None,
+ element_formats=None,
+ ):
+ captured["output_formats"] = output_formats
+ captured["keep_header_footer"] = keep_header_footer
+ captured["model_options"] = model_options
+ captured["element_formats"] = element_formats
+ return {
+ "file_name": "demo.png",
+ "outputs": {"markdown": "ok", "json": {"pages": []}},
+ "metadata": {"page_num": 1, "file_type": ".png"},
+ }
+
+ monkeypatch.setattr(routes, "process_document", fake_process_document)
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={
+ "api_key": "dummy",
+ "element_formats": json.dumps({
+ "image": "url",
+ "formula": "latex",
+ "table": "html",
+ "cs": "image",
+ }),
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 0
+ assert response.json()["message"] == "任务成功"
+ assert response.json()["warnings"] == []
+ assert captured["element_formats"] == {
+ "image": "url",
+ "formula": "latex",
+ "table": "html",
+ "cs": "image",
+ }
+
+
+def test_parse_sync_reports_multiple_parameter_errors():
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={
+ "api_key": "dummy",
+ "output_formats": "zip",
+ "element_formats": json.dumps({
+ "image": "file",
+ "formula": "mathml",
+ "table": "image",
+ }),
+ },
+ )
+
+ message = response.json()["message"]
+ assert response.status_code == 200
+ assert response.json()["code"] == 1133
+ assert response.json()["warnings"] == []
+ assert "output_formats=zip" in message
+ assert "element_formats.image=file" in message
+ assert "element_formats.formula=mathml" in message
+ assert "element_formats.table=image" in message
+
+
+def test_parse_sync_rejects_zip_output_format():
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={
+ "api_key": "dummy",
+ "output_formats": "zip",
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 1133
+ assert response.json()["warnings"] == []
+ assert "output_formats=zip" in response.json()["message"]
+
+
+def test_parse_sync_passes_feature_config_keep_header_footer(monkeypatch):
+ captured = {}
+
+ async def fake_process_document(
+ _file_bytes,
+ _file_name,
+ output_formats,
+ keep_header_footer=False,
+ model_options=None,
+ element_formats=None,
+ ):
+ captured["output_formats"] = output_formats
+ captured["keep_header_footer"] = keep_header_footer
+ captured["model_options"] = model_options
+ captured["element_formats"] = element_formats
+ return {
+ "file_name": "demo.png",
+ "outputs": {"markdown": "ok", "json": {"pages": []}},
+ "metadata": {"page_num": 1, "file_type": ".png"},
+ }
+
+ monkeypatch.setattr(routes, "process_document", fake_process_document)
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={
+ "api_key": "dummy",
+ "output_formats": ["markdown", "json"],
+ "feature_config": json.dumps({"keep_header_footer": True}),
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 0
+ assert response.json()["warnings"] == []
+ assert captured == {
+ "output_formats": ["markdown", "json"],
+ "keep_header_footer": True,
+ "model_options": {},
+ "element_formats": {
+ "image": "url",
+ "formula": "latex",
+ "table": "html",
+ "cs": "smiles",
+ },
+ }
+
+
+def test_parse_sync_passes_extra_model_options(monkeypatch):
+ captured = {}
+
+ async def fake_process_document(
+ _file_bytes,
+ _file_name,
+ _output_formats,
+ keep_header_footer=False,
+ model_options=None,
+ element_formats=None,
+ ):
+ captured["keep_header_footer"] = keep_header_footer
+ captured["model_options"] = model_options
+ captured["element_formats"] = element_formats
+ return {
+ "file_name": "demo.png",
+ "outputs": {"markdown": "ok", "json": {"pages": []}},
+ "metadata": {"page_num": 1, "file_type": ".png"},
+ }
+
+ monkeypatch.setattr(routes, "process_document", fake_process_document)
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={
+ "api_key": "dummy",
+ "feature_config": json.dumps({"keep_header_footer": True}),
+ "extra": json.dumps({
+ "temperature": 0.2,
+ "top_p": 0.9,
+ "repetition_penalty": 1.1,
+ }),
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 0
+ assert response.json()["warnings"] == []
+ assert captured == {
+ "keep_header_footer": True,
+ "model_options": {
+ "temperature": 0.2,
+ "top_p": 0.9,
+ "repetition_penalty": 1.1,
+ },
+ "element_formats": {
+ "image": "url",
+ "formula": "latex",
+ "table": "html",
+ "cs": "smiles",
+ },
+ }
+
+
+def test_parse_sync_warns_for_unsupported_feature_config_true(monkeypatch):
+ async def fake_process_document(
+ _file_bytes,
+ _file_name,
+ _output_formats,
+ keep_header_footer=False,
+ model_options=None,
+ element_formats=None,
+ ):
+ return {
+ "file_name": "demo.png",
+ "outputs": {"markdown": "ok", "json": {"pages": []}},
+ "metadata": {"page_num": 1, "file_type": ".png"},
+ }
+
+ monkeypatch.setattr(routes, "process_document", fake_process_document)
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={
+ "api_key": "dummy",
+ "feature_config": json.dumps({
+ "enable_text_cross_page": True,
+ "enable_table_cross_page": True,
+ }),
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 0
+ assert response.json()["message"] == "任务成功"
+ assert len(response.json()["warnings"]) == 2
+ assert any(
+ "feature_config.enable_text_cross_page=true" in warning
+ for warning in response.json()["warnings"]
+ )
+ assert any(
+ "feature_config.enable_table_cross_page=true" in warning
+ for warning in response.json()["warnings"]
+ )
+
+
+def test_parse_sync_ignores_unsupported_feature_config_false(monkeypatch):
+ async def fake_process_document(
+ _file_bytes,
+ _file_name,
+ _output_formats,
+ keep_header_footer=False,
+ model_options=None,
+ element_formats=None,
+ ):
+ return {
+ "file_name": "demo.png",
+ "outputs": {"markdown": "ok", "json": {"pages": []}},
+ "metadata": {"page_num": 1, "file_type": ".png"},
+ }
+
+ monkeypatch.setattr(routes, "process_document", fake_process_document)
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={
+ "api_key": "dummy",
+ "feature_config": json.dumps({"enable_text_cross_page": False}),
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 0
+ assert response.json()["message"] == "任务成功"
+ assert response.json()["warnings"] == []
+
+
+def test_parse_async_warnings_keep_submit_message_stable(monkeypatch):
+ async def fake_process_document(
+ _file_bytes,
+ file_name,
+ _output_formats,
+ keep_header_footer=False,
+ model_options=None,
+ element_formats=None,
+ ):
+ return {
+ "file_name": file_name,
+ "outputs": {"markdown": "ok"},
+ "metadata": {"page_num": 1, "file_type": ".png"},
+ }
+
+ monkeypatch.setattr(routes, "process_document", fake_process_document)
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/parse/async",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={
+ "api_key": "dummy",
+ "feature_config": json.dumps({"enable_text_cross_page": True}),
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 0
+ assert response.json()["message"] == "任务已提交"
+ assert len(response.json()["warnings"]) == 1
+ assert "feature_config.enable_text_cross_page=true" in response.json()["warnings"][0]
+
+
+def test_parse_sync_rejects_invalid_extra_model_options():
+ invalid_extras = [
+ "{",
+ "[]",
+ json.dumps({"unsupported": True}),
+ {"temperature": "hot"},
+ {"temperature": 2.1},
+ {"top_p": 1.1},
+ {"repetition_penalty": 0},
+ ]
+
+ with TestClient(app) as client:
+ for extra in invalid_extras:
+ extra_value = extra if isinstance(extra, str) else json.dumps(extra)
+ response = client.post(
+ "/v1/parse/sync",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={
+ "api_key": "dummy",
+ "extra": extra_value,
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["code"] == 1133
+ assert response.json()["warnings"] == []
+ assert "extra" in response.json()["message"]
+
+
+def test_async_check_returns_somark_style_result(monkeypatch):
+ async def fake_process_document(
+ _file_bytes,
+ file_name,
+ _output_formats,
+ keep_header_footer=False,
+ model_options=None,
+ element_formats=None,
+ ):
+ return {
+ "file_name": file_name,
+ "outputs": {"markdown": "ok"},
+ "metadata": {"page_num": 1, "file_type": ".png"},
+ }
+
+ monkeypatch.setattr(routes, "process_document", fake_process_document)
+
+ with TestClient(app) as client:
+ submit = client.post(
+ "/v1/parse/async",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={"api_key": "dummy", "output_formats": "markdown"},
+ )
+ task_id = submit.json()["data"]["task_id"]
+
+ response = client.post(
+ "/v1/parse/async_check",
+ data={"api_key": "dummy", "task_id": task_id},
+ )
+
+ data = response.json()["data"]
+ assert response.status_code == 200
+ assert response.json()["warnings"] == []
+ assert data["task_id"] == task_id
+ assert data["status"] == "success"
+ assert data["file_name"] == "demo.png"
+ assert data["result"]["outputs"]["markdown"] == "ok"
+
+
+def test_async_check_preserves_debug_metadata(monkeypatch):
+ async def fake_process_document(
+ _file_bytes,
+ file_name,
+ _output_formats,
+ keep_header_footer=False,
+ model_options=None,
+ element_formats=None,
+ ):
+ return {
+ "file_name": file_name,
+ "outputs": {"markdown": "ok"},
+ "metadata": {
+ "page_num": 1,
+ "file_type": ".png",
+ "processing_time_ms": 10,
+ "debug_timing": {
+ "decode_time_ms": 1,
+ "layout_time_ms": 2,
+ "recognition_time_ms": 6,
+ "assembly_time_ms": 1,
+ },
+ "debug_stats": {
+ "total_blocks": 1,
+ "blocks_per_page": [1],
+ "block_type_counts": {BlockType.TEXT.value: 1},
+ },
+ },
+ }
+
+ monkeypatch.setattr(routes, "process_document", fake_process_document)
+
+ with TestClient(app) as client:
+ submit = client.post(
+ "/v1/parse/async",
+ files={"file": ("demo.png", b"fake-image", "image/png")},
+ data={"api_key": "dummy", "output_formats": "markdown"},
+ )
+ task_id = submit.json()["data"]["task_id"]
+
+ response = client.post(
+ "/v1/parse/async_check",
+ data={"api_key": "dummy", "task_id": task_id},
+ )
+
+ metadata = response.json()["data"]["metadata"]
+ assert metadata["debug_timing"]["layout_time_ms"] == 2
+ assert metadata["debug_stats"]["total_blocks"] == 1
+
+
+def test_process_document_filters_header_footer_by_default(monkeypatch):
+ captured = {}
+
+ async def fake_analyze_layouts(_images, _model_options=None):
+ return [[
+ Block(0, BlockType.PAGE_HEADER, [0, 0, 10, 5], "Header", ContentFormat.TEXT),
+ Block(1, BlockType.TEXT, [0, 5, 10, 10], "Body", ContentFormat.TEXT),
+ Block(2, BlockType.PAGE_FOOTER, [0, 10, 10, 15], "Footer", ContentFormat.TEXT),
+ ]]
+
+ async def fake_recognize_pages(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ captured["recognized_types"] = [
+ block.type
+ for page_blocks in pages_blocks
+ for block in page_blocks
+ ]
+ return pages_blocks
+
+ monkeypatch.setattr(orchestrator, "pdf_to_images", lambda _file_bytes: [np.zeros((16, 16, 3), dtype=np.uint8)])
+ monkeypatch.setattr(orchestrator, "analyze_layouts", fake_analyze_layouts)
+ monkeypatch.setattr(orchestrator, "recognize_pages", fake_recognize_pages)
+
+ result = asyncio.run(orchestrator.process_document(b"pdf", "demo.pdf", ["markdown", "json"]))
+
+ block_types = [block["type"] for block in result["outputs"]["json"]["pages"][0]["blocks"]]
+ assert block_types == [BlockType.TEXT.value]
+ assert captured["recognized_types"] == [BlockType.TEXT]
+ assert "Body" in result["outputs"]["markdown"]
+ assert "Header" not in result["outputs"]["markdown"]
+ assert "Footer" not in result["outputs"]["markdown"]
+
+
+def test_process_document_keeps_header_footer_when_enabled(monkeypatch):
+ async def fake_analyze_layouts(_images, _model_options=None):
+ return [[
+ Block(0, BlockType.PAGE_HEADER, [0, 0, 10, 5], "Header", ContentFormat.TEXT),
+ Block(1, BlockType.TEXT, [0, 5, 10, 10], "Body", ContentFormat.TEXT),
+ Block(2, BlockType.PAGE_FOOTER, [0, 10, 10, 15], "Footer", ContentFormat.TEXT),
+ ]]
+
+ async def fake_recognize_pages(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ return pages_blocks
+
+ monkeypatch.setattr(orchestrator, "pdf_to_images", lambda _file_bytes: [np.zeros((16, 16, 3), dtype=np.uint8)])
+ monkeypatch.setattr(orchestrator, "analyze_layouts", fake_analyze_layouts)
+ monkeypatch.setattr(orchestrator, "recognize_pages", fake_recognize_pages)
+ monkeypatch.setattr(orchestrator.settings.layout_analyze_model, "provides_reading_order", True)
+
+ result = asyncio.run(
+ orchestrator.process_document(b"pdf", "demo.pdf", ["markdown", "json"], keep_header_footer=True)
+ )
+
+ block_types = [block["type"] for block in result["outputs"]["json"]["pages"][0]["blocks"]]
+ assert block_types == [BlockType.PAGE_HEADER.value, BlockType.TEXT.value, BlockType.PAGE_FOOTER.value]
+ assert "Header" in result["outputs"]["markdown"]
+ assert "Footer" in result["outputs"]["markdown"]
+
+
+def test_process_document_passes_model_options(monkeypatch):
+ captured = {}
+ model_options = {"temperature": 0.3, "top_p": 0.8, "repetition_penalty": 1.2}
+
+ async def fake_analyze_layouts(_images, options=None):
+ captured["layout_options"] = options
+ return [[Block(0, BlockType.TEXT, [0, 0, 10, 10], "Body", ContentFormat.TEXT)]]
+
+ async def fake_recognize_pages(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ options=None,
+ element_formats=None,
+ ):
+ captured["recognition_options"] = options
+ captured["element_formats"] = element_formats
+ return pages_blocks
+
+ monkeypatch.setattr(orchestrator, "pdf_to_images", lambda _file_bytes: [np.zeros((16, 16, 3), dtype=np.uint8)])
+ monkeypatch.setattr(orchestrator, "analyze_layouts", fake_analyze_layouts)
+ monkeypatch.setattr(orchestrator, "recognize_pages", fake_recognize_pages)
+
+ asyncio.run(
+ orchestrator.process_document(
+ b"pdf",
+ "demo.pdf",
+ ["markdown", "json"],
+ model_options=model_options,
+ )
+ )
+
+ assert captured == {
+ "layout_options": model_options,
+ "recognition_options": model_options,
+ "element_formats": None,
+ }
+
+
+def test_process_document_hides_debug_metadata_by_default(monkeypatch):
+ async def fake_analyze_layouts(_images, _model_options=None):
+ return [[Block(0, BlockType.TEXT, [0, 0, 10, 10], "Body", ContentFormat.TEXT)]]
+
+ async def fake_recognize_pages(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ return pages_blocks
+
+ monkeypatch.setattr(orchestrator.settings, "debug", False)
+ monkeypatch.setattr(orchestrator, "pdf_to_images", lambda _file_bytes: [np.zeros((16, 16, 3), dtype=np.uint8)])
+ monkeypatch.setattr(orchestrator, "analyze_layouts", fake_analyze_layouts)
+ monkeypatch.setattr(orchestrator, "recognize_pages", fake_recognize_pages)
+
+ result = asyncio.run(orchestrator.process_document(b"pdf", "demo.pdf", ["markdown", "json"]))
+
+ assert "processing_time_ms" in result["metadata"]
+ assert "debug_timing" not in result["metadata"]
+ assert "debug_stats" not in result["metadata"]
+
+
+def test_process_document_returns_debug_metadata_when_enabled(monkeypatch):
+ async def fake_analyze_layouts(_images, _model_options=None):
+ return [[
+ Block(0, BlockType.TEXT, [0, 0, 10, 10], "Body", ContentFormat.TEXT),
+ Block(1, BlockType.TABLE, [0, 10, 10, 20], "<table></table>", ContentFormat.HTML),
+ ]]
+
+ async def fake_recognize_pages(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ return pages_blocks
+
+ monkeypatch.setattr(orchestrator.settings, "debug", True)
+ monkeypatch.setattr(orchestrator, "pdf_to_images", lambda _file_bytes: [np.zeros((16, 16, 3), dtype=np.uint8)])
+ monkeypatch.setattr(orchestrator, "analyze_layouts", fake_analyze_layouts)
+ monkeypatch.setattr(orchestrator, "recognize_pages", fake_recognize_pages)
+ monkeypatch.setattr(orchestrator.settings.layout_analyze_model, "provides_reading_order", True)
+
+ result = asyncio.run(orchestrator.process_document(b"pdf", "demo.pdf", ["markdown", "json"]))
+
+ timing = result["metadata"]["debug_timing"]
+ stats = result["metadata"]["debug_stats"]
+ assert set(timing) == {
+ "decode_time_ms",
+ "layout_time_ms",
+ "recognition_time_ms",
+ "assembly_time_ms",
+ }
+ assert stats == {
+ "total_blocks": 2,
+ "blocks_per_page": [2],
+ "block_type_counts": {
+ BlockType.TABLE.value: 1,
+ BlockType.TEXT.value: 1,
+ },
+ }
diff --git a/tests/unit/test_table_images.py b/tests/unit/test_table_images.py
new file mode 100644
index 0000000..6b8a6f1
--- /dev/null
+++ b/tests/unit/test_table_images.py
@@ -0,0 +1,279 @@
+import asyncio
+import base64
+
+import cv2
+import numpy as np
+import pytest
+
+from oxr.config.settings import settings
+from oxr.model.client import ModelOutput
+from oxr.pipeline import orchestrator
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.table_images import (
+ TABLE_IMAGE_ROLE,
+ group_table_images,
+ prepare_table_images,
+ restore_table_images,
+)
+from oxr.pipeline.recognition import recognize_block, recognize_pages
+from oxr.utils.table import html_table_to_markdown
+
+
+def block(idx, kind, box, score=0.9):
+ return Block(idx, kind, box, "", ContentFormat.TEXT, layout_score=score)
+
+
+def scene():
+ image = np.full((180, 260, 3), 255, dtype=np.uint8)
+ image[40:85, 135:235] = [10, 70, 130]
+ image[100:145, 135:235] = [40, 100, 160]
+ table = block(8, BlockType.TABLE, [10.4, 10.4, 250.2, 170.2])
+ first = block(23, BlockType.PICTURE, [135, 40, 235, 85])
+ second = block(41, BlockType.PICTURE, [135, 100, 235, 145])
+ return image, table, first, second
+
+
+def test_group_uses_confidence_smallest_parent_and_geometry_order():
+ _, table, first, second = scene()
+ outer = block(99, BlockType.TABLE, [0, 0, 260, 180])
+ low = block(32, BlockType.PICTURE, [20, 20, 120, 50], 0.26)
+ unknown = block(33, BlockType.PICTURE, [20, 60, 120, 90], None)
+ crossing = block(34, BlockType.PICTURE, [245, 160, 265, 175])
+ same_box = block(35, BlockType.PICTURE, table.bbox)
+ groups = group_table_images(
+ [second, outer, low, table, first, unknown, crossing, same_box], 0.5
+ )
+ assert groups[3] == [first, second]
+ assert groups[1] == [same_box]
+ assert low not in sum(groups.values(), [])
+ assert unknown not in sum(groups.values(), [])
+ assert crossing not in sum(groups.values(), [])
+
+
+def test_mask_keeps_original_image_and_correct_rounded_crops():
+ image, table, first, second = scene()
+ original = image.copy()
+ masked, sources = prepare_table_images(table, [first, second], image)
+ np.testing.assert_array_equal(image, original)
+ assert masked.shape == (160, 240, 3)
+ assert set(sources) == {1, 2}
+ restored = cv2.imdecode(
+ np.frombuffer(base64.b64decode(sources[1].split(",")[1]), dtype=np.uint8),
+ cv2.IMREAD_COLOR,
+ )
+ np.testing.assert_array_equal(restored, image[36:89, 131:239])
+ assert np.any(np.all(masked == [255, 0, 0], axis=2))
+ assert not sources[1] == sources[2]
+
+
+def test_full_overlap_mode_associates_images_with_surviving_outer_table():
+ _, table, first, second = scene()
+ outer = block(99, BlockType.TABLE, [0, 0, 260, 180])
+ assert group_table_images(
+ [table, first, outer, second], 0.5, keep_outer_tables=True
+ ) == {2: [first, second]}
+
+
[email protected]("variant", ["tiny", "overlap"])
+def test_ambiguous_or_tiny_masks_fail_before_recognition(variant):
+ image, table, first, second = scene()
+ if variant == "tiny":
+ first.bbox = [20, 20, 25, 25]
+ else:
+ second.bbox = first.bbox
+ with pytest.raises(ValueError):
+ prepare_table_images(table, [first, second], image)
+
+
+ "tokens",
+ [("<tit>2", "<tit>1"), ("&lt;tit>2", "&lt;tit&gt;1"), ("<TIT>2", "<TIT>1")],
+)
+def test_restore_maps_by_id_even_when_order_changes_and_preserves_text(tokens):
+ text = f"<table><tr><td>A {tokens[0]} B {tokens[1]}</td><td>x|x≠0</td></tr></table>"
+ restored = restore_table_images(
+ "```html\n" + text + "\n```",
+ {1: "data:image/png;base64,first", 2: "data:image/png;base64,second"},
+ )
+ assert restored.index("base64,second") < restored.index("base64,first")
+ assert "x|x≠0" in restored
+ assert restored.count("<img ") == 2
+
+
+ "text",
+ [
+ "<table><tr><td><tit>1</td></tr></table>",
+ "<table><tr><td><tit>1 <tit>1</td></tr></table>",
+ "<table><tr><td><tit>1 <tit>3</td></tr></table>",
+ "<table><tr><td><tit>1 <tit></td></tr></table>",
+ "<table><tr><td><tit>1 <tit>2",
+ "<tit>1<table><tr><td><tit>2</td></tr></table>",
+ '<table><tr><td title="<tit>1"><tit>2</td></tr></table>',
+ "<table><tr><td><tit>1 <tit>2 <tit>3</td></tr></table>",
+ ],
+)
+def test_incomplete_duplicate_unknown_or_outside_cell_ids_are_rejected(text):
+ assert restore_table_images(text, {1: "first", 2: "second"}) is None
+
+
+def test_markdown_keeps_multiple_inline_images_in_merged_cell():
+ html = restore_table_images(
+ '<table><tr><td colspan="2">A <tit>1 B <tit>2</td></tr></table>',
+ {1: "data:image/png;base64,first", 2: "data:image/png;base64,second"},
+ )
+ markdown = html_table_to_markdown(html)
+ assert markdown.count("![](data:image/png;base64,first)") == 2
+ assert markdown.count("![](data:image/png;base64,second)") == 2
+
+
+def test_restore_preserves_math_comparisons_before_later_image_cells():
+ text = "<table><tr><td>0<a&lt;1</td><td>&lt;tit>1</td></tr><tr><td>x<0</td><td>&lt;tit>2</td></tr></table>"
+ restored = restore_table_images(text, {1: "first", 2: "second"})
+ assert restored is not None
+ assert "0&lt;a&lt;1" in restored and "x&lt;0" in restored
+ assert restored.count("<img ") == 2
+ markdown = html_table_to_markdown(restored)
+ assert "0<a<1" in markdown and "x<0" in markdown
+
+
+def test_recognition_preserves_ro_index_space_without_extra_picture_files(
+ monkeypatch, tmp_path
+):
+ image, table, first, second = scene()
+ calls = []
+
+ async def table_request(_image, _options=None):
+ calls.append("table")
+ return "<table><tr><td><tit>2</td><td><tit>1</td></tr></table>"
+
+ monkeypatch.setattr(settings.pipeline, "table_image_placeholders", True)
+ monkeypatch.setattr(settings.pipeline, "image_output_dir", str(tmp_path))
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_table", table_request
+ )
+ result = asyncio.run(
+ recognize_pages(
+ [[second, table, first]], [image], "demo.png", asyncio.Semaphore(1)
+ )
+ )
+ assert result[0] == [second, table, first]
+ assert table.content.count("<img ") == 2
+ assert first.generated_role == second.generated_role == TABLE_IMAGE_ROLE
+ assert calls == ["table"]
+ assert not list(tmp_path.iterdir())
+
+
+ "failure", ["missing", "length", "request", "retry_request", "tiny"]
+)
+def test_recognition_fallback_retains_original_full_table(monkeypatch, failure):
+ image, table, first, second = scene()
+ calls = []
+
+ async def table_request(_image, _options=None):
+ calls.append(_image.shape)
+ if failure == "request" or failure == "retry_request" and len(calls) == 2:
+ raise RuntimeError("test failure")
+ if failure in {"length", "retry_request"}:
+ return ModelOutput(
+ "<table><tr><td><tit>1 <tit>2</td></tr></table>", finish_reason="length"
+ )
+ return "<table><tr><td><tit>1</td></tr></table>"
+
+ if failure == "tiny":
+ first.bbox = [20, 20, 25, 25]
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_table", table_request
+ )
+ result = asyncio.run(
+ recognize_block(
+ table,
+ image,
+ asyncio.Semaphore(1),
+ "demo.png",
+ 0,
+ table_images=[first, second],
+ )
+ )
+ assert result.type == BlockType.TABLE
+ assert result.format == ContentFormat.HTML
+ assert result.content.startswith('<img alt="Table" src="data:image/png;base64,')
+ data = result.content.split("base64,")[1].split('"')[0]
+ raster = cv2.imdecode(
+ np.frombuffer(base64.b64decode(data), dtype=np.uint8), cv2.IMREAD_COLOR
+ )
+ np.testing.assert_array_equal(raster, image[10:170, 10:250])
+ assert first.generated_role == second.generated_role == TABLE_IMAGE_ROLE
+ assert len(calls) == ({"tiny": 0, "length": 2, "retry_request": 2}.get(failure, 1))
+
+
[email protected]("provides_ro", [True, False])
[email protected]("table_format", ["html", "markdown"])
[email protected]("full_overlap", [True, False])
+def test_full_document_restores_images_before_overlap_cleanup(
+ monkeypatch, provides_ro, table_format, full_overlap
+):
+ image, table, first, second = scene()
+
+ async def layout(*_):
+ return [[second, table, first]]
+
+ async def order(*_):
+ return [[2, 1, 0]]
+
+ async def table_request(*_):
+ return "<table><tr><td><tit>1 <tit>2</td></tr></table>"
+
+ monkeypatch.setattr(orchestrator, "_decode_document_images", lambda *_: [image])
+ monkeypatch.setattr(orchestrator, "analyze_layouts", layout)
+ monkeypatch.setattr(orchestrator, "resolve_reading_orders", order)
+ monkeypatch.setattr(
+ settings.layout_analyze_model, "provides_reading_order", provides_ro
+ )
+ monkeypatch.setattr(settings.pipeline, "table_image_placeholders", True)
+ monkeypatch.setattr(settings.pipeline, "full_overlap_dedupe", full_overlap)
+ monkeypatch.setattr(settings.oxr_model, "retry_times", 1)
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_table", table_request
+ )
+ output = asyncio.run(
+ orchestrator.process_document(
+ b"input",
+ "demo.png",
+ ["json", "markdown"],
+ element_formats={"table": table_format},
+ )
+ )
+ blocks = output["outputs"]["json"]["pages"][0]["blocks"]
+ assert len(blocks) == 1 and blocks[0]["type"] == "Table"
+ image_marker = "<img " if table_format == "html" else "![](data:image/png;base64,"
+ assert blocks[0]["format"] == table_format
+ assert blocks[0]["content"].count(image_marker) == 2
+ assert output["outputs"]["markdown"].count(image_marker) == 2
+
+
+def test_feature_off_keeps_unmasked_table_request_and_standalone_picture(
+ monkeypatch, tmp_path
+):
+ image, table, first, _ = scene()
+ seen = []
+
+ async def table_request(crop, *_):
+ seen.append(crop.copy())
+ return "<table><tr><td>plain</td></tr></table>"
+
+ monkeypatch.setattr(settings.pipeline, "table_image_placeholders", False)
+ monkeypatch.setattr(settings.pipeline, "image_output_dir", str(tmp_path))
+ monkeypatch.setattr(
+ "oxr.pipeline.recognition.model_client.recognize_table", table_request
+ )
+ result = asyncio.run(
+ recognize_pages([[table, first]], [image], "demo.png", asyncio.Semaphore(1))
+ )
+ np.testing.assert_array_equal(seen[0], image[10:170, 10:250])
+ assert first.generated_role == ""
+ assert first.content.startswith("![](")
+ assert len(result[0]) == 2
diff --git a/tests/unit/test_table_postprocess.py b/tests/unit/test_table_postprocess.py
new file mode 100644
index 0000000..bcb15d3
--- /dev/null
+++ b/tests/unit/test_table_postprocess.py
@@ -0,0 +1,72 @@
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.postprocess.table_postprocess import postprocess_table
+from oxr.utils.table import html_table_to_markdown
+
+
+def _table_block() -> Block:
+ return Block(0, BlockType.TABLE, [0, 0, 10, 10], "", ContentFormat.TEXT)
+
+
+def test_html_table_to_markdown_expands_rowspan_and_colspan():
+ html = """
+ <table>
+ <tr><th rowspan="2">Name</th><th colspan="2">Score</th></tr>
+ <tr><td>Math</td><td>English</td></tr>
+ <tr><td>Ada</td><td>98</td><td>96</td></tr>
+ </table>
+ """
+
+ assert html_table_to_markdown(html) == "\n".join([
+ "| Name | Score | Score |",
+ "| --- | --- | --- |",
+ "| Name | Math | English |",
+ "| Ada | 98 | 96 |",
+ ])
+
+
+def test_html_table_to_markdown_escapes_pipes_and_strips_fences():
+ html = """```html
+ <table><tr><th>A|B</th></tr><tr><td>x|y</td></tr></table>
+ ```"""
+
+ assert html_table_to_markdown(html) == "\n".join([
+ "| A\\|B |",
+ "| --- |",
+ "| x\\|y |",
+ ])
+
+
+def test_html_table_to_markdown_handles_thead_tbody_and_th():
+ html = """
+ <table>
+ <thead>
+ <tr><th>City</th><th>Population</th></tr>
+ </thead>
+ <tbody>
+ <tr><td>Shanghai</td><td>24M</td></tr>
+ <tr><td>Beijing</td><td>21M</td></tr>
+ </tbody>
+ </table>
+ """
+
+ assert html_table_to_markdown(html) == "\n".join([
+ "| City | Population |",
+ "| --- | --- |",
+ "| Shanghai | 24M |",
+ "| Beijing | 21M |",
+ ])
+
+
+def test_html_table_to_markdown_falls_back_to_cleaned_text():
+ assert html_table_to_markdown("<p>not a table</p>") == "not a table"
+
+
+def test_postprocess_table_sets_markdown_format_when_requested():
+ block = postprocess_table(
+ _table_block(),
+ "<table><tr><th>A</th></tr><tr><td>B</td></tr></table>",
+ output_format="markdown",
+ )
+
+ assert block.format == ContentFormat.MARKDOWN
+ assert block.content == "| A |\n| --- |\n| B |"
diff --git a/tests/unit/test_text_postprocess.py b/tests/unit/test_text_postprocess.py
new file mode 100644
index 0000000..500ecc0
--- /dev/null
+++ b/tests/unit/test_text_postprocess.py
@@ -0,0 +1,63 @@
+import asyncio
+
+import numpy as np
+
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.orchestrator import process_document
+from oxr.pipeline.postprocess.text_postprocess import postprocess_text
+
+
+def _text_block() -> Block:
+ return Block(0, BlockType.TEXT, [0, 0, 1, 1], "", ContentFormat.TEXT)
+
+
+def test_text_postprocess_moves_tag_number_outside_inline_formula():
+ block = postprocess_text(_text_block(), "$y=x+1 \\tag{1}$")
+
+ assert block.content == "$y=x+1$ (1)"
+ assert block.format == ContentFormat.TEXT
+
+
+def test_text_postprocess_moves_tag_star_number_outside_inline_formula_without_parentheses():
+ block = postprocess_text(_text_block(), "$y=x+1 \\tag*{1}$")
+
+ assert block.content == "$y=x+1$ 1"
+
+
+def test_text_postprocess_moves_leqno_number_before_inline_formula():
+ block = postprocess_text(_text_block(), "$y=x+1 \\leqno (1)$")
+
+ assert block.content == "(1) $y=x+1$"
+
+
+def test_text_postprocess_preserves_math_ranges_without_numbering():
+ block = postprocess_text(_text_block(), "Keep $ x + 1 $ unchanged")
+
+ assert block.content == "Keep $ x + 1 $ unchanged"
+
+
+def test_process_document_cleans_formula_numbering_from_text_blocks(monkeypatch):
+ async def fake_analyze_layouts(_images, _model_options=None):
+ return [[_text_block()]]
+
+ async def fake_recognize_pages(
+ pages_blocks,
+ _images,
+ _file_name,
+ _semaphore,
+ _model_options=None,
+ _element_formats=None,
+ ):
+ block = pages_blocks[0][0]
+ return [[postprocess_text(block, "$y=x+1 \\tag{8.12}$")]]
+
+ monkeypatch.setattr("oxr.pipeline.orchestrator.cv2.imdecode", lambda *_args: np.zeros((4, 4, 3), dtype=np.uint8))
+ monkeypatch.setattr("oxr.pipeline.orchestrator.analyze_layouts", fake_analyze_layouts)
+ monkeypatch.setattr("oxr.pipeline.orchestrator.recognize_pages", fake_recognize_pages)
+
+ result = asyncio.run(process_document(b"image", "page.png", ["json", "markdown"], keep_header_footer=True))
+ blocks = result["outputs"]["json"]["pages"][0]["blocks"]
+
+ assert blocks[0]["type"] == "Text"
+ assert blocks[0]["content"] == "$y=x+1$ (8.12)"
+ assert result["outputs"]["markdown"] == "$y=x+1$ (8.12)\n"
diff --git a/tests/unit/test_xycut_order.py b/tests/unit/test_xycut_order.py
new file mode 100644
index 0000000..90b062b
--- /dev/null
+++ b/tests/unit/test_xycut_order.py
@@ -0,0 +1,75 @@
+import pytest
+
+from oxr.pipeline._vendor import xycut_plus_plus
+from oxr.pipeline.models import Block, BlockType, ContentFormat
+from oxr.pipeline.xycut_order import xycut_plus_order
+
+
+def _block(index: int, bbox: list[float]) -> Block:
+ return Block(index, BlockType.TEXT, bbox, "", ContentFormat.TEXT)
+
+
+def test_xycut_plus_order_is_order_only_and_returns_exact_permutation():
+ blocks = [
+ _block(0, [0, 0, 40, 40]),
+ _block(1, [50, 0, 90, 40]),
+ _block(2, [0, 50, 40, 90]),
+ _block(3, [50, 50, 90, 90]),
+ ]
+ original_bboxes = [block.bbox[:] for block in blocks]
+
+ order = xycut_plus_order(blocks)
+
+ assert order == [0, 2, 1, 3]
+ assert sorted(order) == list(range(len(blocks)))
+ assert [block.bbox for block in blocks] == original_bboxes
+
+
+def test_xycut_plus_order_rejects_degenerate_bbox():
+ blocks = [
+ _block(0, [0, 0, 0, 10]),
+ _block(1, [0, 20, 10, 30]),
+ ]
+
+ with pytest.raises(ValueError, match="degenerate bbox"):
+ xycut_plus_order(blocks)
+
+
+def test_xycut_plus_order_supports_every_block_type_without_dropping_overlaps():
+ typed_blocks = [
+ Block(
+ index,
+ block_type,
+ [0, index * 20, 100, index * 20 + 10],
+ "",
+ ContentFormat.TEXT,
+ )
+ for index, block_type in enumerate(BlockType)
+ ]
+ overlapping_blocks = [
+ _block(index, [0, 0, 100, 100])
+ for index in range(3)
+ ]
+
+ typed_order = xycut_plus_order(typed_blocks)
+ overlapping_order = xycut_plus_order(overlapping_blocks)
+
+ assert sorted(typed_order) == list(range(len(typed_blocks)))
+ assert sorted(overlapping_order) == [0, 1, 2]
+
+
+def test_xycut_adapter_preserves_vendor_default_overlap_removal():
+ entries = [
+ {
+ "block_bbox": [0, 0, 100, 100],
+ "block_label": "text",
+ "block_content": str(index),
+ "seg_start_flag": False,
+ "seg_end_flag": False,
+ }
+ for index in range(2)
+ ]
+
+ ordered = xycut_plus_plus.get_layout_ordering(entries)
+
+ assert len(ordered) == 1