🎧 If you have to use a Chromebox with GNU/Linux, the sound might not work right away. To get Intel Corporation Sunrise Point-LP HD Audio working, do do the following:
Here is how you can detect if you’ve booted your computer using a UEFI BIOS or a Legacy BIOS. First, install the dmidecode utility from your operating system repository. On Debian, you can:
+
1apt-get install dmidecode
+
dmidecode reports information related to the BIOS under a type 0 entry. A quick way to detect the BIOS mode is:
Human beings, who are almost unique in having the ability to learn from the experience of others, are also remarkable for their apparent disinclination to do so. - Douglas Adams
+
Hacks.Wiki is an experiment to organise quick hacks, notes, bookmarks and tools into an easy-to-build-and-maintain “Digital Garden”.
+
It should take others far less time and effort to do what we’ve already done.
+
You can start by visiting Recent entries. Or start by browsing the Hashtags. There is also a RSS Feed that you can subscribe to. And - 🎊surprise - there is an ActivityPub handle as well; Just follow hacks@hacks.wiki via a Mastodon / Pleroma / Soapbox / Misskey and other instances and tools.
+
Unless otherwise noted, all hacks in this wiki are licensed under CC-BY-4.0.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Migrate from UEFI to (Legacy) BIOS/index.html b/Migrate from UEFI to (Legacy) BIOS/index.html
new file mode 100755
index 0000000..81fbc59
--- /dev/null
+++ b/Migrate from UEFI to (Legacy) BIOS/index.html
@@ -0,0 +1,194 @@
+
+
+
+
+
+
+
+ 🔁 Migrate from UEFI to (Legacy) BIOS | Hacks.Wiki - Today I Learned...
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
If you have installed GNU/Linux with BTRFS as the filesystem, chances are that your OS installer has used sub-volumes for the root, home and other mount points. 🗄️
+
You can verify this by mounting the actual root filesystem device and listing its contents:
+
1# ls -l /mnt/
+2total 0
+3drwxr-xr-x 1 root root 204 Feb 22 13:28 @
+4drwxr-xr-x 1 root root 180 Feb 22 14:29 @cache
+5drwxr-xr-x 1 root root 10 Dec 2 10:52 @home
+6drwxr-xr-x 1 root root 482 Feb 26 00:00 @log
+7drwxr-x--- 1 root root 350 Feb 23 15:40 @root
+8drwxr-xr-x 1 root root 14 Oct 19 07:42 @srv
+9drwxrwxrwt 1 root root 1576 Feb 27 17:18 @tmp
+
Here @, @home, @log etc. are the BTRFS sub-volumes. @ is the OS root sub-volume. You can mount by giving the -osubvol=@ option to the mount command:
+
1# mount -osubvol=@ /dev/dm-0 /mnt/
+ 2# ls -l /mnt/
+ 3total 24
+ 4lrwxrwxrwx 1 root root 7 Feb 1 02:21 bin -> usr/bin
+ 5drwxr-xr-x 1 root root 208 Feb 22 13:30 boot
+ 6drwxr-xr-x 1 root root 8 Oct 20 18:39 dev
+ 7drwxr-xr-x 1 root root 5018 Feb 25 10:56 etc
+ 8drwxr-xr-x 1 root root 0 Dec 2 10:48 home
+ 9lrwxrwxrwx 1 root root 7 Feb 1 02:21 lib -> usr/lib
+10lrwxrwxrwx 1 root root 7 Feb 1 02:21 lib64 -> usr/lib
+11drwxr-xr-x 1 root root 22 Dec 16 13:00 mnt
+12drwxr-xr-x 1 root root 214 Feb 23 15:50 opt
+13drwxr-xr-x 1 root root 0 Dec 2 10:48 proc
+14drwxr-xr-x 1 root root 66 Oct 20 18:47 root
+15 .... .... ....
+
Human beings, who are almost unique in having the ability to learn from the experience of others, are also remarkable for their apparent disinclination to do so. - Douglas Adams
+
Hacks.Wiki is an experiment to organise quick hacks, notes, bookmarks and tools into an easy-to-build-and-maintain “Digital Garden”.
+
It should take others far less time and effort to do what we’ve already done.
+
You can start by visiting Recent entries. Or start by browsing the Hashtags. There is also a RSS Feed that you can subscribe to. And - 🎊surprise - there is an ActivityPub handle as well; Just follow hacks@hacks.wiki via a Mastodon / Pleroma / Soapbox / Misskey and other instances and tools.
+
Unless otherwise noted, all hacks in this wiki are licensed under CC-BY-4.0.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/manifest.json b/manifest.json
new file mode 100755
index 0000000..0292ece
--- /dev/null
+++ b/manifest.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json.schemastore.org/web-manifest-combined.json",
+ "name": "Hacks.Wiki - Today I Learned...",
+ "short_name": "Hacks.Wiki - Today I Learned...",
+ "start_url": "/",
+ "display": "standalone",
+ "icons": [
+ {
+ "src": "public/logo.png",
+ "type": "image/png",
+ "sizes": "any"
+ }
+ ]
+}
diff --git a/public/assets/DubaiW23-Bold.woff b/public/assets/DubaiW23-Bold.woff
new file mode 100755
index 0000000..469a524
Binary files /dev/null and b/public/assets/DubaiW23-Bold.woff differ
diff --git a/public/assets/DubaiW23-Regular.woff b/public/assets/DubaiW23-Regular.woff
new file mode 100755
index 0000000..1a7bc89
Binary files /dev/null and b/public/assets/DubaiW23-Regular.woff differ
diff --git a/public/assets/fa-brands-400.ttf b/public/assets/fa-brands-400.ttf
new file mode 100755
index 0000000..cf6a98f
Binary files /dev/null and b/public/assets/fa-brands-400.ttf differ
diff --git a/public/assets/fa-brands-400.woff2 b/public/assets/fa-brands-400.woff2
new file mode 100755
index 0000000..c740267
Binary files /dev/null and b/public/assets/fa-brands-400.woff2 differ
diff --git a/public/assets/fa-regular-400.ttf b/public/assets/fa-regular-400.ttf
new file mode 100755
index 0000000..9ef8a37
Binary files /dev/null and b/public/assets/fa-regular-400.ttf differ
diff --git a/public/assets/fa-regular-400.woff2 b/public/assets/fa-regular-400.woff2
new file mode 100755
index 0000000..a865b2f
Binary files /dev/null and b/public/assets/fa-regular-400.woff2 differ
diff --git a/public/assets/fa-solid-900.ttf b/public/assets/fa-solid-900.ttf
new file mode 100755
index 0000000..2b96436
Binary files /dev/null and b/public/assets/fa-solid-900.ttf differ
diff --git a/public/assets/fa-solid-900.woff2 b/public/assets/fa-solid-900.woff2
new file mode 100755
index 0000000..021d33f
Binary files /dev/null and b/public/assets/fa-solid-900.woff2 differ
diff --git a/public/assets/inter-all-100-normal.woff b/public/assets/inter-all-100-normal.woff
new file mode 100755
index 0000000..0306d1d
Binary files /dev/null and b/public/assets/inter-all-100-normal.woff differ
diff --git a/public/assets/inter-all-200-normal.woff b/public/assets/inter-all-200-normal.woff
new file mode 100755
index 0000000..9245b8f
Binary files /dev/null and b/public/assets/inter-all-200-normal.woff differ
diff --git a/public/assets/inter-all-300-normal.woff b/public/assets/inter-all-300-normal.woff
new file mode 100755
index 0000000..8b700d7
Binary files /dev/null and b/public/assets/inter-all-300-normal.woff differ
diff --git a/public/assets/inter-all-400-normal.woff b/public/assets/inter-all-400-normal.woff
new file mode 100755
index 0000000..db0f8d1
Binary files /dev/null and b/public/assets/inter-all-400-normal.woff differ
diff --git a/public/assets/inter-all-500-normal.woff b/public/assets/inter-all-500-normal.woff
new file mode 100755
index 0000000..ec2c08d
Binary files /dev/null and b/public/assets/inter-all-500-normal.woff differ
diff --git a/public/assets/inter-all-600-normal.woff b/public/assets/inter-all-600-normal.woff
new file mode 100755
index 0000000..8c99dc8
Binary files /dev/null and b/public/assets/inter-all-600-normal.woff differ
diff --git a/public/assets/inter-all-700-normal.woff b/public/assets/inter-all-700-normal.woff
new file mode 100755
index 0000000..7248f27
Binary files /dev/null and b/public/assets/inter-all-700-normal.woff differ
diff --git a/public/assets/inter-all-800-normal.woff b/public/assets/inter-all-800-normal.woff
new file mode 100755
index 0000000..241bb64
Binary files /dev/null and b/public/assets/inter-all-800-normal.woff differ
diff --git a/public/assets/inter-all-900-normal.woff b/public/assets/inter-all-900-normal.woff
new file mode 100755
index 0000000..cc3405d
Binary files /dev/null and b/public/assets/inter-all-900-normal.woff differ
diff --git a/public/assets/inter-cyrillic-100-normal.woff2 b/public/assets/inter-cyrillic-100-normal.woff2
new file mode 100755
index 0000000..519ef27
Binary files /dev/null and b/public/assets/inter-cyrillic-100-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-200-normal.woff2 b/public/assets/inter-cyrillic-200-normal.woff2
new file mode 100755
index 0000000..d94f792
Binary files /dev/null and b/public/assets/inter-cyrillic-200-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-300-normal.woff2 b/public/assets/inter-cyrillic-300-normal.woff2
new file mode 100755
index 0000000..f98e5b2
Binary files /dev/null and b/public/assets/inter-cyrillic-300-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-400-normal.woff2 b/public/assets/inter-cyrillic-400-normal.woff2
new file mode 100755
index 0000000..c1c5768
Binary files /dev/null and b/public/assets/inter-cyrillic-400-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-500-normal.woff2 b/public/assets/inter-cyrillic-500-normal.woff2
new file mode 100755
index 0000000..d151842
Binary files /dev/null and b/public/assets/inter-cyrillic-500-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-600-normal.woff2 b/public/assets/inter-cyrillic-600-normal.woff2
new file mode 100755
index 0000000..b0f0af5
Binary files /dev/null and b/public/assets/inter-cyrillic-600-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-700-normal.woff2 b/public/assets/inter-cyrillic-700-normal.woff2
new file mode 100755
index 0000000..22a09b0
Binary files /dev/null and b/public/assets/inter-cyrillic-700-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-800-normal.woff2 b/public/assets/inter-cyrillic-800-normal.woff2
new file mode 100755
index 0000000..cad49b6
Binary files /dev/null and b/public/assets/inter-cyrillic-800-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-900-normal.woff2 b/public/assets/inter-cyrillic-900-normal.woff2
new file mode 100755
index 0000000..d1133f5
Binary files /dev/null and b/public/assets/inter-cyrillic-900-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-ext-100-normal.woff2 b/public/assets/inter-cyrillic-ext-100-normal.woff2
new file mode 100755
index 0000000..878765a
Binary files /dev/null and b/public/assets/inter-cyrillic-ext-100-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-ext-200-normal.woff2 b/public/assets/inter-cyrillic-ext-200-normal.woff2
new file mode 100755
index 0000000..eb02003
Binary files /dev/null and b/public/assets/inter-cyrillic-ext-200-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-ext-300-normal.woff2 b/public/assets/inter-cyrillic-ext-300-normal.woff2
new file mode 100755
index 0000000..294c7ff
Binary files /dev/null and b/public/assets/inter-cyrillic-ext-300-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-ext-400-normal.woff2 b/public/assets/inter-cyrillic-ext-400-normal.woff2
new file mode 100755
index 0000000..da834bb
Binary files /dev/null and b/public/assets/inter-cyrillic-ext-400-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-ext-500-normal.woff2 b/public/assets/inter-cyrillic-ext-500-normal.woff2
new file mode 100755
index 0000000..5a1646b
Binary files /dev/null and b/public/assets/inter-cyrillic-ext-500-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-ext-600-normal.woff2 b/public/assets/inter-cyrillic-ext-600-normal.woff2
new file mode 100755
index 0000000..3b4d7f4
Binary files /dev/null and b/public/assets/inter-cyrillic-ext-600-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-ext-700-normal.woff2 b/public/assets/inter-cyrillic-ext-700-normal.woff2
new file mode 100755
index 0000000..7e52d98
Binary files /dev/null and b/public/assets/inter-cyrillic-ext-700-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-ext-800-normal.woff2 b/public/assets/inter-cyrillic-ext-800-normal.woff2
new file mode 100755
index 0000000..f9a1a8c
Binary files /dev/null and b/public/assets/inter-cyrillic-ext-800-normal.woff2 differ
diff --git a/public/assets/inter-cyrillic-ext-900-normal.woff2 b/public/assets/inter-cyrillic-ext-900-normal.woff2
new file mode 100755
index 0000000..160f0ff
Binary files /dev/null and b/public/assets/inter-cyrillic-ext-900-normal.woff2 differ
diff --git a/public/assets/inter-greek-100-normal.woff2 b/public/assets/inter-greek-100-normal.woff2
new file mode 100755
index 0000000..bbff286
Binary files /dev/null and b/public/assets/inter-greek-100-normal.woff2 differ
diff --git a/public/assets/inter-greek-200-normal.woff2 b/public/assets/inter-greek-200-normal.woff2
new file mode 100755
index 0000000..8041bcb
Binary files /dev/null and b/public/assets/inter-greek-200-normal.woff2 differ
diff --git a/public/assets/inter-greek-300-normal.woff2 b/public/assets/inter-greek-300-normal.woff2
new file mode 100755
index 0000000..e96490f
Binary files /dev/null and b/public/assets/inter-greek-300-normal.woff2 differ
diff --git a/public/assets/inter-greek-400-normal.woff2 b/public/assets/inter-greek-400-normal.woff2
new file mode 100755
index 0000000..143a941
Binary files /dev/null and b/public/assets/inter-greek-400-normal.woff2 differ
diff --git a/public/assets/inter-greek-500-normal.woff2 b/public/assets/inter-greek-500-normal.woff2
new file mode 100755
index 0000000..5c98638
Binary files /dev/null and b/public/assets/inter-greek-500-normal.woff2 differ
diff --git a/public/assets/inter-greek-600-normal.woff2 b/public/assets/inter-greek-600-normal.woff2
new file mode 100755
index 0000000..f4f0a5e
Binary files /dev/null and b/public/assets/inter-greek-600-normal.woff2 differ
diff --git a/public/assets/inter-greek-700-normal.woff2 b/public/assets/inter-greek-700-normal.woff2
new file mode 100755
index 0000000..140147e
Binary files /dev/null and b/public/assets/inter-greek-700-normal.woff2 differ
diff --git a/public/assets/inter-greek-800-normal.woff2 b/public/assets/inter-greek-800-normal.woff2
new file mode 100755
index 0000000..544d583
Binary files /dev/null and b/public/assets/inter-greek-800-normal.woff2 differ
diff --git a/public/assets/inter-greek-900-normal.woff2 b/public/assets/inter-greek-900-normal.woff2
new file mode 100755
index 0000000..ab3f1c0
Binary files /dev/null and b/public/assets/inter-greek-900-normal.woff2 differ
diff --git a/public/assets/inter-greek-ext-100-normal.woff2 b/public/assets/inter-greek-ext-100-normal.woff2
new file mode 100755
index 0000000..4f023ac
Binary files /dev/null and b/public/assets/inter-greek-ext-100-normal.woff2 differ
diff --git a/public/assets/inter-greek-ext-200-normal.woff2 b/public/assets/inter-greek-ext-200-normal.woff2
new file mode 100755
index 0000000..8fa4e47
Binary files /dev/null and b/public/assets/inter-greek-ext-200-normal.woff2 differ
diff --git a/public/assets/inter-greek-ext-300-normal.woff2 b/public/assets/inter-greek-ext-300-normal.woff2
new file mode 100755
index 0000000..97e45aa
Binary files /dev/null and b/public/assets/inter-greek-ext-300-normal.woff2 differ
diff --git a/public/assets/inter-greek-ext-400-normal.woff2 b/public/assets/inter-greek-ext-400-normal.woff2
new file mode 100755
index 0000000..5f4ae92
Binary files /dev/null and b/public/assets/inter-greek-ext-400-normal.woff2 differ
diff --git a/public/assets/inter-greek-ext-500-normal.woff2 b/public/assets/inter-greek-ext-500-normal.woff2
new file mode 100755
index 0000000..aec20f6
Binary files /dev/null and b/public/assets/inter-greek-ext-500-normal.woff2 differ
diff --git a/public/assets/inter-greek-ext-600-normal.woff2 b/public/assets/inter-greek-ext-600-normal.woff2
new file mode 100755
index 0000000..0fee707
Binary files /dev/null and b/public/assets/inter-greek-ext-600-normal.woff2 differ
diff --git a/public/assets/inter-greek-ext-700-normal.woff2 b/public/assets/inter-greek-ext-700-normal.woff2
new file mode 100755
index 0000000..3a44ec3
Binary files /dev/null and b/public/assets/inter-greek-ext-700-normal.woff2 differ
diff --git a/public/assets/inter-greek-ext-800-normal.woff2 b/public/assets/inter-greek-ext-800-normal.woff2
new file mode 100755
index 0000000..3d281d0
Binary files /dev/null and b/public/assets/inter-greek-ext-800-normal.woff2 differ
diff --git a/public/assets/inter-greek-ext-900-normal.woff2 b/public/assets/inter-greek-ext-900-normal.woff2
new file mode 100755
index 0000000..c23b86f
Binary files /dev/null and b/public/assets/inter-greek-ext-900-normal.woff2 differ
diff --git a/public/assets/inter-latin-100-normal.woff2 b/public/assets/inter-latin-100-normal.woff2
new file mode 100755
index 0000000..1ef2357
Binary files /dev/null and b/public/assets/inter-latin-100-normal.woff2 differ
diff --git a/public/assets/inter-latin-200-normal.woff2 b/public/assets/inter-latin-200-normal.woff2
new file mode 100755
index 0000000..ca591ae
Binary files /dev/null and b/public/assets/inter-latin-200-normal.woff2 differ
diff --git a/public/assets/inter-latin-300-normal.woff2 b/public/assets/inter-latin-300-normal.woff2
new file mode 100755
index 0000000..e085aa8
Binary files /dev/null and b/public/assets/inter-latin-300-normal.woff2 differ
diff --git a/public/assets/inter-latin-400-normal.woff2 b/public/assets/inter-latin-400-normal.woff2
new file mode 100755
index 0000000..c659f5e
Binary files /dev/null and b/public/assets/inter-latin-400-normal.woff2 differ
diff --git a/public/assets/inter-latin-500-normal.woff2 b/public/assets/inter-latin-500-normal.woff2
new file mode 100755
index 0000000..6fc94ad
Binary files /dev/null and b/public/assets/inter-latin-500-normal.woff2 differ
diff --git a/public/assets/inter-latin-600-normal.woff2 b/public/assets/inter-latin-600-normal.woff2
new file mode 100755
index 0000000..bc76d10
Binary files /dev/null and b/public/assets/inter-latin-600-normal.woff2 differ
diff --git a/public/assets/inter-latin-700-normal.woff2 b/public/assets/inter-latin-700-normal.woff2
new file mode 100755
index 0000000..8fcc432
Binary files /dev/null and b/public/assets/inter-latin-700-normal.woff2 differ
diff --git a/public/assets/inter-latin-800-normal.woff2 b/public/assets/inter-latin-800-normal.woff2
new file mode 100755
index 0000000..27db054
Binary files /dev/null and b/public/assets/inter-latin-800-normal.woff2 differ
diff --git a/public/assets/inter-latin-900-normal.woff2 b/public/assets/inter-latin-900-normal.woff2
new file mode 100755
index 0000000..b1c208a
Binary files /dev/null and b/public/assets/inter-latin-900-normal.woff2 differ
diff --git a/public/assets/inter-latin-ext-100-normal.woff2 b/public/assets/inter-latin-ext-100-normal.woff2
new file mode 100755
index 0000000..9982f5f
Binary files /dev/null and b/public/assets/inter-latin-ext-100-normal.woff2 differ
diff --git a/public/assets/inter-latin-ext-200-normal.woff2 b/public/assets/inter-latin-ext-200-normal.woff2
new file mode 100755
index 0000000..a822063
Binary files /dev/null and b/public/assets/inter-latin-ext-200-normal.woff2 differ
diff --git a/public/assets/inter-latin-ext-300-normal.woff2 b/public/assets/inter-latin-ext-300-normal.woff2
new file mode 100755
index 0000000..25be677
Binary files /dev/null and b/public/assets/inter-latin-ext-300-normal.woff2 differ
diff --git a/public/assets/inter-latin-ext-400-normal.woff2 b/public/assets/inter-latin-ext-400-normal.woff2
new file mode 100755
index 0000000..b0d0894
Binary files /dev/null and b/public/assets/inter-latin-ext-400-normal.woff2 differ
diff --git a/public/assets/inter-latin-ext-500-normal.woff2 b/public/assets/inter-latin-ext-500-normal.woff2
new file mode 100755
index 0000000..e787291
Binary files /dev/null and b/public/assets/inter-latin-ext-500-normal.woff2 differ
diff --git a/public/assets/inter-latin-ext-600-normal.woff2 b/public/assets/inter-latin-ext-600-normal.woff2
new file mode 100755
index 0000000..8ff1de2
Binary files /dev/null and b/public/assets/inter-latin-ext-600-normal.woff2 differ
diff --git a/public/assets/inter-latin-ext-700-normal.woff2 b/public/assets/inter-latin-ext-700-normal.woff2
new file mode 100755
index 0000000..d8c5665
Binary files /dev/null and b/public/assets/inter-latin-ext-700-normal.woff2 differ
diff --git a/public/assets/inter-latin-ext-800-normal.woff2 b/public/assets/inter-latin-ext-800-normal.woff2
new file mode 100755
index 0000000..1a2cf49
Binary files /dev/null and b/public/assets/inter-latin-ext-800-normal.woff2 differ
diff --git a/public/assets/inter-latin-ext-900-normal.woff2 b/public/assets/inter-latin-ext-900-normal.woff2
new file mode 100755
index 0000000..2d12b58
Binary files /dev/null and b/public/assets/inter-latin-ext-900-normal.woff2 differ
diff --git a/public/assets/inter-vietnamese-100-normal.woff2 b/public/assets/inter-vietnamese-100-normal.woff2
new file mode 100755
index 0000000..1e01e43
Binary files /dev/null and b/public/assets/inter-vietnamese-100-normal.woff2 differ
diff --git a/public/assets/inter-vietnamese-200-normal.woff2 b/public/assets/inter-vietnamese-200-normal.woff2
new file mode 100755
index 0000000..49bf2d6
Binary files /dev/null and b/public/assets/inter-vietnamese-200-normal.woff2 differ
diff --git a/public/assets/inter-vietnamese-300-normal.woff2 b/public/assets/inter-vietnamese-300-normal.woff2
new file mode 100755
index 0000000..c75e79a
Binary files /dev/null and b/public/assets/inter-vietnamese-300-normal.woff2 differ
diff --git a/public/assets/inter-vietnamese-400-normal.woff2 b/public/assets/inter-vietnamese-400-normal.woff2
new file mode 100755
index 0000000..b9cb104
Binary files /dev/null and b/public/assets/inter-vietnamese-400-normal.woff2 differ
diff --git a/public/assets/inter-vietnamese-500-normal.woff2 b/public/assets/inter-vietnamese-500-normal.woff2
new file mode 100755
index 0000000..73c7d0f
Binary files /dev/null and b/public/assets/inter-vietnamese-500-normal.woff2 differ
diff --git a/public/assets/inter-vietnamese-600-normal.woff2 b/public/assets/inter-vietnamese-600-normal.woff2
new file mode 100755
index 0000000..0f59ce6
Binary files /dev/null and b/public/assets/inter-vietnamese-600-normal.woff2 differ
diff --git a/public/assets/inter-vietnamese-700-normal.woff2 b/public/assets/inter-vietnamese-700-normal.woff2
new file mode 100755
index 0000000..a9a5314
Binary files /dev/null and b/public/assets/inter-vietnamese-700-normal.woff2 differ
diff --git a/public/assets/inter-vietnamese-800-normal.woff2 b/public/assets/inter-vietnamese-800-normal.woff2
new file mode 100755
index 0000000..56b1f46
Binary files /dev/null and b/public/assets/inter-vietnamese-800-normal.woff2 differ
diff --git a/public/assets/inter-vietnamese-900-normal.woff2 b/public/assets/inter-vietnamese-900-normal.woff2
new file mode 100755
index 0000000..27eadde
Binary files /dev/null and b/public/assets/inter-vietnamese-900-normal.woff2 differ
diff --git a/public/js/@codemirror/autocomplete.js b/public/js/@codemirror/autocomplete.js
new file mode 100755
index 0000000..6221ba0
--- /dev/null
+++ b/public/js/@codemirror/autocomplete.js
@@ -0,0 +1 @@
+import{Annotation,EditorSelection,codePointAt,codePointSize,fromCodePoint,Facet,combineConfig,StateEffect,StateField,Prec,Text,MapMode,RangeValue,RangeSet,CharCategory}from"@codemirror/state";import{logException,Direction,showTooltip,EditorView,ViewPlugin,getTooltip,Decoration,WidgetType,keymap}from"@codemirror/view";import{syntaxTree,indentUnit}from"@codemirror/language";class CompletionContext{constructor(state,pos,explicit){this.state=state;this.pos=pos;this.explicit=explicit;this.abortListeners=[]}tokenBefore(types){let token=syntaxTree(this.state).resolveInner(this.pos,-1);while(token&&types.indexOf(token.name)<0)token=token.parent;return token?{from:token.from,to:this.pos,text:this.state.sliceDoc(token.from,this.pos),type:token.type}:null}matchBefore(expr){let line=this.state.doc.lineAt(this.pos);let start=Math.max(line.from,this.pos-250);let str=line.text.slice(start-line.from,this.pos-line.from);let found=str.search(ensureAnchor(expr,false));return found<0?null:{from:start+found,to:this.pos,text:str.slice(found)}}get aborted(){return this.abortListeners==null}addEventListener(type,listener){if(type=="abort"&&this.abortListeners)this.abortListeners.push(listener)}}function toSet(chars){let flat=Object.keys(chars).join("");let words=/\w/.test(flat);if(words)flat=flat.replace(/\w/g,"");return`[${words?"\\w":""}${flat.replace(/[^\w\s]/g,"\\$&")}]`}function prefixMatch(options){let first=Object.create(null),rest=Object.create(null);for(let{label}of options){first[label[0]]=true;for(let i=1;itypeof o=="string"?{label:o}:o);let[validFor,match]=options.every(o=>/^\w+$/.test(o.label))?[/\w*$/,/\w+$/]:prefixMatch(options);return context=>{let token=context.matchBefore(match);return token||context.explicit?{from:token?token.from:context.pos,options:options,validFor:validFor}:null}}function ifIn(nodes,source){return context=>{for(let pos=syntaxTree(context.state).resolveInner(context.pos,-1);pos;pos=pos.parent)if(nodes.indexOf(pos.name)>-1)return source(context);return null}}function ifNotIn(nodes,source){return context=>{for(let pos=syntaxTree(context.state).resolveInner(context.pos,-1);pos;pos=pos.parent)if(nodes.indexOf(pos.name)>-1)return null;return source(context)}}class Option{constructor(completion,source,match){this.completion=completion;this.source=source;this.match=match}}function cur(state){return state.selection.main.head}function ensureAnchor(expr,start){var _a;let{source}=expr;let addStart=start&&source[0]!="^",addEnd=source[source.length-1]!="$";if(!addStart&&!addEnd)return expr;return new RegExp(`${addStart?"^":""}(?:${source})${addEnd?"$":""}`,(_a=expr.flags)!==null&&_a!==void 0?_a:expr.ignoreCase?"i":"")}const pickedCompletion=Annotation.define();function insertCompletionText(state,text,from,to){return Object.assign(Object.assign({},state.changeByRange(range=>{if(range==state.selection.main)return{changes:{from:from,to:to,insert:text},range:EditorSelection.cursor(from+text.length)};let len=to-from;if(!range.empty||len&&state.sliceDoc(range.from-len,range.from)!=state.sliceDoc(from,to))return{range:range};return{changes:{from:range.from-len,to:range.from,insert:text},range:EditorSelection.cursor(range.from-len+text.length)}})),{userEvent:"input.complete"})}function applyCompletion(view,option){const apply=option.completion.apply||option.completion.label;let result=option.source;if(typeof apply=="string")view.dispatch(insertCompletionText(view.state,apply,result.from,result.to));else apply(view,option.completion,result.from,result.to)}const SourceCache=new WeakMap;function asSource(source){if(!Array.isArray(source))return source;let known=SourceCache.get(source);if(!known)SourceCache.set(source,known=completeFromList(source));return known}class FuzzyMatcher{constructor(pattern){this.pattern=pattern;this.chars=[];this.folded=[];this.any=[];this.precise=[];this.byWord=[];for(let p=0;p=48&&next<=57||next>=97&&next<=122?2:next>=65&&next<=90?1:0:(ch=fromCodePoint(next))!=ch.toLowerCase()?1:ch!=ch.toUpperCase()?2:0;if(!i||type==1&&hasLower||prevType==0&&type!=0){if(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=true))byWord[byWordTo++]=i;else if(byWord.length)wordAdjacent=false}prevType=type;i+=codePointSize(next)}if(byWordTo==len&&byWord[0]==0&&wordAdjacent)return this.result(-100+(byWordFolded?-200:0),byWord,word);if(adjacentTo==len&&adjacentStart==0)return[-200-word.length,0,adjacentEnd];if(direct>-1)return[-700-word.length,direct,direct+this.pattern.length];if(adjacentTo==len)return[-200+-700-word.length,adjacentStart,adjacentEnd];if(byWordTo==len)return this.result(-100+(byWordFolded?-200:0)+-700+(wordAdjacent?0:-1100),byWord,word);return chars.length==2?null:this.result((any[0]?-700:0)+-200+-1100,any,word)}result(score,positions,word){let result=[score-word.length],i=1;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);if(i>1&&result[i-1]==pos)result[i-1]=to;else{result[i++]=pos;result[i++]=to}}return result}}const completionConfig=Facet.define({combine(configs){return combineConfig(configs,{activateOnTyping:true,selectOnOpen:true,override:null,closeOnBlur:true,maxRenderedOptions:100,defaultKeymap:true,optionClass:()=>"",aboveCursor:false,icons:true,addToOptions:[],compareCompletions:(a,b)=>a.label.localeCompare(b.label),interactionDelay:75},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)})}});function joinClass(a,b){return a?b?a+" "+b:a:b}function optionContent(config){let content=config.addToOptions.slice();if(config.icons)content.push({render(completion){let icon=document.createElement("div");icon.classList.add("cm-completionIcon");if(completion.type)icon.classList.add(...completion.type.split(/\s+/g).map(cls=>"cm-completionIcon-"+cls));icon.setAttribute("aria-hidden","true");return icon},position:20});content.push({render(completion,_s,match){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let{label}=completion,off=0;for(let j=1;joff)labelElt.appendChild(document.createTextNode(label.slice(off,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to)));span.className="cm-completionMatchedText";off=to}if(offa.position-b.position).map(a=>a.render)}function rangeAroundSelected(total,selected,max){if(total<=max)return{from:0,to:total};if(selected<0)selected=0;if(selected<=total>>1){let off=Math.floor(selected/max);return{from:off*max,to:(off+1)*max}}let off=Math.floor((total-selected)/max);return{from:total-(off+1)*max,to:total-off*max}}class CompletionTooltip{constructor(view,stateField){this.view=view;this.stateField=stateField;this.info=null;this.placeInfo={read:()=>this.measureInfo(),write:pos=>this.positionInfo(pos),key:this};let cState=view.state.field(stateField);let{options,selected}=cState.open;let config=view.state.facet(completionConfig);this.optionContent=optionContent(config);this.optionClass=config.optionClass;this.range=rangeAroundSelected(options.length,selected,config.maxRenderedOptions);this.dom=document.createElement("div");this.dom.className="cm-tooltip-autocomplete";this.dom.addEventListener("mousedown",e=>{for(let dom=e.target,match;dom&&dom!=this.dom;dom=dom.parentNode){if(dom.nodeName=="LI"&&(match=/-(\d+)$/.exec(dom.id))&&+match[1]{if(this.info)this.view.requestMeasure(this.placeInfo)})}mount(){this.updateSel()}update(update){if(update.state.field(this.stateField)!=update.startState.field(this.stateField))this.updateSel()}positioned(){if(this.info)this.view.requestMeasure(this.placeInfo)}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if(open.selected>-1&&open.selected=this.range.to){this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions);this.list.remove();this.list=this.dom.appendChild(this.createListBox(open.options,cState.id,this.range));this.list.addEventListener("scroll",()=>{if(this.info)this.view.requestMeasure(this.placeInfo)})}if(this.updateSelectedOption(open.selected)){if(this.info){this.info.remove();this.info=null}let{completion}=open.options[open.selected];let{info}=completion;if(!info)return;let infoResult=typeof info==="string"?document.createTextNode(info):info(completion);if(!infoResult)return;if("then"in infoResult){infoResult.then(node=>{if(node&&this.view.state.field(this.stateField,false)==cState)this.addInfoPane(node)}).catch(e=>logException(this.view.state,e,"completion info"))}else{this.addInfoPane(infoResult)}}}addInfoPane(content){let dom=this.info=document.createElement("div");dom.className="cm-tooltip cm-completionInfo";dom.appendChild(content);this.dom.appendChild(dom);this.view.requestMeasure(this.placeInfo)}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++){if(i==selected){if(!opt.hasAttribute("aria-selected")){opt.setAttribute("aria-selected","true");set=opt}}else{if(opt.hasAttribute("aria-selected"))opt.removeAttribute("aria-selected")}}if(set)scrollIntoView(this.list,set);return set}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let win=this.dom.ownerDocument.defaultView||window;let listRect=this.dom.getBoundingClientRect();let infoRect=this.info.getBoundingClientRect();let selRect=sel.getBoundingClientRect();if(selRect.top>Math.min(win.innerHeight,listRect.bottom)-10||selRect.bottom=infoRect.height||spaceBelow>listRect.top)top=selRect.bottom-listRect.top+"px";else bottom=listRect.bottom-selRect.top+"px"}return{top:top,bottom:bottom,maxWidth:maxWidth,class:narrow?rtl?"left-narrow":"right-narrow":left?"left":"right"}}positionInfo(pos){if(this.info){if(pos){this.info.style.top=pos.top;this.info.style.bottom=pos.bottom;this.info.style.maxWidth=pos.maxWidth;this.info.className="cm-tooltip cm-completionInfo cm-completionInfo-"+pos.class}else{this.info.style.top="-1e6px"}}}createListBox(options,id,range){const ul=document.createElement("ul");ul.id=id;ul.setAttribute("role","listbox");ul.setAttribute("aria-expanded","true");ul.setAttribute("aria-label",this.view.state.phrase("Completions"));for(let i=range.from;inew CompletionTooltip(view,stateField)}function scrollIntoView(container,element){let parent=container.getBoundingClientRect();let self=element.getBoundingClientRect();if(self.topparent.bottom)container.scrollTop+=self.bottom-parent.bottom}function score(option){return(option.boost||0)*100+(option.apply?10:0)+(option.info?5:0)+(option.type?1:0)}function sortOptions(active,state){let options=[],i=0;for(let a of active)if(a.hasResult()){if(a.result.filter===false){let getMatch=a.result.getMatch;for(let option of a.result.options){let match=[1e9-i++];if(getMatch)for(let n of getMatch(option))match.push(n);options.push(new Option(option,a,match))}}else{let matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to)),match;for(let option of a.result.options)if(match=matcher.match(option.label)){if(option.boost!=null)match[0]+=option.boost;options.push(new Option(option,a,match))}}}let result=[],prev=null;let compare=state.facet(completionConfig).compareCompletions;for(let opt of options.sort((a,b)=>b.match[0]-a.match[0]||compare(a.completion,b.completion))){if(!prev||prev.label!=opt.completion.label||prev.detail!=opt.completion.detail||prev.type!=null&&opt.completion.type!=null&&prev.type!=opt.completion.type||prev.apply!=opt.completion.apply)result.push(opt);else if(score(opt.completion)>score(prev))result[result.length-1]=opt;prev=opt.completion}return result}class CompletionDialog{constructor(options,attrs,tooltip,timestamp,selected){this.options=options;this.attrs=attrs;this.tooltip=tooltip;this.timestamp=timestamp;this.selected=selected}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new CompletionDialog(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected)}static build(active,state,id,prev,conf){let options=sortOptions(active,state);if(!options.length)return null;let selected=state.facet(completionConfig).selectOnOpen?0:-1;if(prev&&prev.selected!=selected&&prev.selected!=-1){let selectedValue=prev.options[prev.selected].completion;for(let i=0;ib.hasResult()?Math.min(a,b.from):a,1e8),create:completionTooltip(completionState),above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected)}map(changes){return new CompletionDialog(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected)}}class CompletionState{constructor(active,id,open){this.active=active;this.id=id;this.open=open}static start(){return new CompletionState(none,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(tr){let{state}=tr,conf=state.facet(completionConfig);let sources=conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource);let active=sources.map(source=>{let value=this.active.find(s=>s.source==source)||new ActiveSource(source,this.active.some(a=>a.state!=0)?1:0);return value.update(tr,conf)});if(active.length==this.active.length&&active.every((a,i)=>a==this.active[i]))active=this.active;let open=tr.selection||active.some(a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to))||!sameResults(active,this.active)?CompletionDialog.build(active,state,this.id,this.open,conf):this.open&&tr.docChanged?this.open.map(tr.changes):this.open;if(!open&&active.every(a=>a.state!=1)&&active.some(a=>a.hasResult()))active=active.map(a=>a.hasResult()?new ActiveSource(a.source,0):a);for(let effect of tr.effects)if(effect.is(setSelectedEffect))open=open&&open.setSelected(effect.value,this.id);return active==this.active&&open==this.open?this:new CompletionState(active,this.id,open)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:baseAttrs}}function sameResults(a,b){if(a==b)return true;for(let iA=0,iB=0;;){while(iA-1)result["aria-activedescendant"]=id+"-"+selected;return result}const none=[];function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null}class ActiveSource{constructor(source,state,explicitPos=-1){this.source=source;this.state=state;this.explicitPos=explicitPos}hasResult(){return false}update(tr,conf){let event=getUserEvent(tr),value=this;if(event)value=value.handleUserEvent(tr,event,conf);else if(tr.docChanged)value=value.handleChange(tr);else if(tr.selection&&value.state!=0)value=new ActiveSource(value.source,0);for(let effect of tr.effects){if(effect.is(startCompletionEffect))value=new ActiveSource(value.source,1,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new ActiveSource(value.source,0);else if(effect.is(setActiveEffect))for(let active of effect.value)if(active.source==value.source)value=active}return value}handleUserEvent(tr,type,conf){return type=="delete"||!conf.activateOnTyping?this.map(tr.changes):new ActiveSource(this.source,1)}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new ActiveSource(this.source,0):this.map(tr.changes)}map(changes){return changes.empty||this.explicitPos<0?this:new ActiveSource(this.source,this.state,changes.mapPos(this.explicitPos))}}class ActiveResult extends ActiveSource{constructor(source,explicitPos,result,from,to){super(source,2,explicitPos);this.result=result;this.from=from;this.to=to}hasResult(){return true}handleUserEvent(tr,type,conf){var _a;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1);let pos=cur(tr.state);if((this.explicitPos<0?pos<=from:posto||type=="delete"&&cur(tr.startState)==this.from)return new ActiveSource(this.source,type=="input"&&conf.activateOnTyping?1:0);let explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos),updated;if(checkValid(this.result.validFor,tr.state,from,to))return new ActiveResult(this.source,explicitPos,this.result,from,to);if(this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0))))return new ActiveResult(this.source,explicitPos,updated,updated.from,(_a=updated.to)!==null&&_a!==void 0?_a:cur(tr.state));return new ActiveSource(this.source,1,explicitPos)}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0):this.map(tr.changes)}map(mapping){return mapping.empty?this:new ActiveResult(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1))}}function checkValid(validFor,state,from,to){if(!validFor)return false;let text=state.sliceDoc(from,to);return typeof validFor=="function"?validFor(text,from,to,state):ensureAnchor(validFor,true).test(text)}const startCompletionEffect=StateEffect.define();const closeCompletionEffect=StateEffect.define();const setActiveEffect=StateEffect.define({map(sources,mapping){return sources.map(s=>s.map(mapping))}});const setSelectedEffect=StateEffect.define();const completionState=StateField.define({create(){return CompletionState.start()},update(value,tr){return value.update(tr)},provide:f=>[showTooltip.from(f,val=>val.tooltip),EditorView.contentAttributes.from(f,state=>state.attrs)]});function moveCompletionSelection(forward,by="option"){return view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.open||Date.now()-cState.open.timestamp-1?cState.open.selected+step*(forward?1:-1):forward?0:length-1;if(selected<0)selected=by=="page"?0:length-1;else if(selected>=length)selected=by=="page"?length-1:0;view.dispatch({effects:setSelectedEffect.of(selected)});return true}}const acceptCompletion=view=>{let cState=view.state.field(completionState,false);if(view.state.readOnly||!cState||!cState.open||cState.open.selected<0||Date.now()-cState.open.timestamp{let cState=view.state.field(completionState,false);if(!cState)return false;view.dispatch({effects:startCompletionEffect.of(true)});return true};const closeCompletion=view=>{let cState=view.state.field(completionState,false);if(!cState||!cState.active.some(a=>a.state!=0))return false;view.dispatch({effects:closeCompletionEffect.of(null)});return true};class RunningQuery{constructor(active,context){this.active=active;this.context=context;this.time=Date.now();this.updates=[];this.done=undefined}}const DebounceTime=50,MaxUpdateCount=50,MinAbortTime=1e3;const completionPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view;this.debounceUpdate=-1;this.running=[];this.debounceAccept=-1;this.composing=0;for(let active of view.state.field(completionState).active)if(active.state==1)this.startQuery(active)}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some(tr=>{return(tr.selection||tr.docChanged)&&!getUserEvent(tr)});for(let i=0;iMaxUpdateCount&&Date.now()-query.time>MinAbortTime){for(let handler of query.context.abortListeners){try{handler()}catch(e){logException(this.view.state,e)}}query.context.abortListeners=null;this.running.splice(i--,1)}else{query.updates.push(...update.transactions)}}if(this.debounceUpdate>-1)clearTimeout(this.debounceUpdate);this.debounceUpdate=cState.active.some(a=>a.state==1&&!this.running.some(q=>q.active.source==a.source))?setTimeout(()=>this.startUpdate(),DebounceTime):-1;if(this.composing!=0)for(let tr of update.transactions){if(getUserEvent(tr)=="input")this.composing=2;else if(this.composing==2&&tr.selection)this.composing=3}}startUpdate(){this.debounceUpdate=-1;let{state}=this.view,cState=state.field(completionState);for(let active of cState.active){if(active.state==1&&!this.running.some(r=>r.active.source==active.source))this.startQuery(active)}}startQuery(active){let{state}=this.view,pos=cur(state);let context=new CompletionContext(state,pos,active.explicitPos==pos);let pending=new RunningQuery(active,context);this.running.push(pending);Promise.resolve(active.source(context)).then(result=>{if(!pending.context.aborted){pending.done=result||null;this.scheduleAccept()}},err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)});logException(this.view.state,err)})}scheduleAccept(){if(this.running.every(q=>q.done!==undefined))this.accept();else if(this.debounceAccept<0)this.debounceAccept=setTimeout(()=>this.accept(),DebounceTime)}accept(){var _a;if(this.debounceAccept>-1)clearTimeout(this.debounceAccept);this.debounceAccept=-1;let updated=[];let conf=this.view.state.facet(completionConfig);for(let i=0;ia.source==query.active.source);if(current&¤t.state==1){if(query.done==null){let active=new ActiveSource(query.active.source,0);for(let tr of query.updates)active=active.update(tr,conf);if(active.state!=1)updated.push(active)}else{this.startQuery(current)}}}if(updated.length)this.view.dispatch({effects:setActiveEffect.of(updated)})}},{eventHandlers:{blur(){let state=this.view.state.field(completionState,false);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur)this.view.dispatch({effects:closeCompletionEffect.of(null)})},compositionstart(){this.composing=1},compositionend(){if(this.composing==3){setTimeout(()=>this.view.dispatch({effects:startCompletionEffect.of(false)}),20)}this.composing=0}}});const baseTheme=EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",listStyle:"none",margin:0,padding:0,"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer",padding:"1px 3px",lineHeight:1.2}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:`${400}px`,boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:`${30}px`},".cm-completionInfo.cm-completionInfo-right-narrow":{left:`${30}px`},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class FieldPos{constructor(field,line,from,to){this.field=field;this.line=line;this.from=from;this.to=to}}class FieldRange{constructor(field,from,to){this.field=field;this.from=from;this.to=to}map(changes){let from=changes.mapPos(this.from,-1,MapMode.TrackDel);let to=changes.mapPos(this.to,1,MapMode.TrackDel);return from==null||to==null?null:new FieldRange(this.field,from,to)}}class Snippet{constructor(lines,fieldPositions){this.lines=lines;this.fieldPositions=fieldPositions}instantiate(state,pos){let text=[],lineStart=[pos];let lineObj=state.doc.lineAt(pos),baseIndent=/^\s*/.exec(lineObj.text)[0];for(let line of this.lines){if(text.length){let indent=baseIndent,tabs=/^\t*/.exec(line)[0].length;for(let i=0;inew FieldRange(pos.field,lineStart[pos.line]+pos.from,lineStart[pos.line]+pos.to));return{text:text,ranges:ranges}}static parse(template){let fields=[];let lines=[],positions=[],m;for(let line of template.split(/\r\n?|\n/)){while(m=/[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(line)){let seq=m[1]?+m[1]:null,name=m[2]||m[3]||"",found=-1;for(let i=0;i=found)pos.field++}positions.push(new FieldPos(found,lines.length,m.index,m.index+name.length));line=line.slice(0,m.index)+name+line.slice(m.index+m[0].length)}for(let esc;esc=/([$#])\\{/.exec(line);){line=line.slice(0,esc.index)+esc[1]+"{"+line.slice(esc.index+esc[0].length);for(let pos of positions)if(pos.line==lines.length&&pos.from>esc.index){pos.from--;pos.to--}}lines.push(line)}return new Snippet(lines,positions)}}let fieldMarker=Decoration.widget({widget:new class extends WidgetType{toDOM(){let span=document.createElement("span");span.className="cm-snippetFieldPosition";return span}ignoreEvent(){return false}}});let fieldRange=Decoration.mark({class:"cm-snippetField"});class ActiveSnippet{constructor(ranges,active){this.ranges=ranges;this.active=active;this.deco=Decoration.set(ranges.map(r=>(r.from==r.to?fieldMarker:fieldRange).range(r.from,r.to)))}map(changes){let ranges=[];for(let r of this.ranges){let mapped=r.map(changes);if(!mapped)return null;ranges.push(mapped)}return new ActiveSnippet(ranges,this.active)}selectionInsideField(sel){return sel.ranges.every(range=>this.ranges.some(r=>r.field==this.active&&r.from<=range.from&&r.to>=range.to))}}const setActive=StateEffect.define({map(value,changes){return value&&value.map(changes)}});const moveToField=StateEffect.define();const snippetState=StateField.define({create(){return null},update(value,tr){for(let effect of tr.effects){if(effect.is(setActive))return effect.value;if(effect.is(moveToField)&&value)return new ActiveSnippet(value.ranges,effect.value)}if(value&&tr.docChanged)value=value.map(tr.changes);if(value&&tr.selection&&!value.selectionInsideField(tr.selection))value=null;return value},provide:f=>EditorView.decorations.from(f,val=>val?val.deco:Decoration.none)});function fieldSelection(ranges,field){return EditorSelection.create(ranges.filter(r=>r.field==field).map(r=>EditorSelection.range(r.from,r.to)))}function snippet(template){let snippet=Snippet.parse(template);return(editor,_completion,from,to)=>{let{text,ranges}=snippet.instantiate(editor.state,from);let spec={changes:{from:from,to:to,insert:Text.of(text)},scrollIntoView:true};if(ranges.length)spec.selection=fieldSelection(ranges,0);if(ranges.length>1){let active=new ActiveSnippet(ranges,0);let effects=spec.effects=[setActive.of(active)];if(editor.state.field(snippetState,false)===undefined)effects.push(StateEffect.appendConfig.of([snippetState,addSnippetKeymap,snippetPointerHandler,baseTheme]))}editor.dispatch(editor.state.update(spec))}}function moveField(dir){return({state,dispatch})=>{let active=state.field(snippetState,false);if(!active||dir<0&&active.active==0)return false;let next=active.active+dir,last=dir>0&&!active.ranges.some(r=>r.field==next+dir);dispatch(state.update({selection:fieldSelection(active.ranges,next),effects:setActive.of(last?null:new ActiveSnippet(active.ranges,next))}));return true}}const clearSnippet=({state,dispatch})=>{let active=state.field(snippetState,false);if(!active)return false;dispatch(state.update({effects:setActive.of(null)}));return true};const nextSnippetField=moveField(1);const prevSnippetField=moveField(-1);const defaultSnippetKeymap=[{key:"Tab",run:nextSnippetField,shift:prevSnippetField},{key:"Escape",run:clearSnippet}];const snippetKeymap=Facet.define({combine(maps){return maps.length?maps[0]:defaultSnippetKeymap}});const addSnippetKeymap=Prec.highest(keymap.compute([snippetKeymap],state=>state.facet(snippetKeymap)));function snippetCompletion(template,completion){return Object.assign(Object.assign({},completion),{apply:snippet(template)})}const snippetPointerHandler=EditorView.domEventHandlers({mousedown(event,view){let active=view.state.field(snippetState,false),pos;if(!active||(pos=view.posAtCoords({x:event.clientX,y:event.clientY}))==null)return false;let match=active.ranges.find(r=>r.from<=pos&&r.to>=pos);if(!match||match.field==active.active)return false;view.dispatch({selection:fieldSelection(active.ranges,match.field),effects:setActive.of(active.ranges.some(r=>r.field>match.field)?new ActiveSnippet(active.ranges,match.field):null)});return true}});function wordRE(wordChars){let escaped=wordChars.replace(/[\\[.+*?(){|^$]/g,"\\$&");try{return new RegExp(`[\\p{Alphabetic}\\p{Number}_${escaped}]+`,"ug")}catch(_a){return new RegExp(`[\w${escaped}]`,"g")}}function mapRE(re,f){return new RegExp(f(re.source),re.unicode?"u":"")}const wordCaches=Object.create(null);function wordCache(wordChars){return wordCaches[wordChars]||(wordCaches[wordChars]=new WeakMap)}function storeWords(doc,wordRE,result,seen,ignoreAt){for(let lines=doc.iterLines(),pos=0;!lines.next().done;){let{value}=lines,m;wordRE.lastIndex=0;while(m=wordRE.exec(value)){if(!seen[m[0]]&&pos+m.index!=ignoreAt){result.push({type:"text",label:m[0]});seen[m[0]]=true;if(result.length>=2e3)return}}pos+=value.length+1}}function collectWords(doc,cache,wordRE,to,ignoreAt){let big=doc.length>=1e3;let cached=big&&cache.get(doc);if(cached)return cached;let result=[],seen=Object.create(null);if(doc.children){let pos=0;for(let ch of doc.children){if(ch.length>=1e3){for(let c of collectWords(ch,cache,wordRE,to-pos,ignoreAt-pos)){if(!seen[c.label]){seen[c.label]=true;result.push(c)}}}else{storeWords(ch,wordRE,result,seen,ignoreAt-pos)}pos+=ch.length+1}}else{storeWords(doc,wordRE,result,seen,ignoreAt)}if(big&&result.length<2e3)cache.set(doc,result);return result}const completeAnyWord=context=>{let wordChars=context.state.languageDataAt("wordChars",context.pos).join("");let re=wordRE(wordChars);let token=context.matchBefore(mapRE(re,s=>s+"$"));if(!token&&!context.explicit)return null;let from=token?token.from:context.pos;let options=collectWords(context.state.doc,wordCache(wordChars),re,5e4,from);return{from:from,options:options,validFor:mapRE(re,s=>"^"+s)}};const defaults={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]};const closeBracketEffect=StateEffect.define({map(value,mapping){let mapped=mapping.mapPos(value,-1,MapMode.TrackAfter);return mapped==null?undefined:mapped}});const skipBracketEffect=StateEffect.define({map(value,mapping){return mapping.mapPos(value)}});const closedBracket=new class extends RangeValue{};closedBracket.startSide=1;closedBracket.endSide=-1;const bracketState=StateField.define({create(){return RangeSet.empty},update(value,tr){if(tr.selection){let lineStart=tr.state.doc.lineAt(tr.selection.main.head).from;let prevLineStart=tr.startState.doc.lineAt(tr.startState.selection.main.head).from;if(lineStart!=tr.changes.mapPos(prevLineStart,-1))value=RangeSet.empty}value=value.map(tr.changes);for(let effect of tr.effects){if(effect.is(closeBracketEffect))value=value.update({add:[closedBracket.range(effect.value,effect.value+1)]});else if(effect.is(skipBracketEffect))value=value.update({filter:from=>from!=effect.value})}return value}});function closeBrackets(){return[inputHandler,bracketState]}const definedClosing="()[]{}<>";function closing(ch){for(let i=0;i{if((android?view.composing:view.compositionStarted)||view.state.readOnly)return false;let sel=view.state.selection.main;if(insert.length>2||insert.length==2&&codePointSize(codePointAt(insert,0))==1||from!=sel.from||to!=sel.to)return false;let tr=insertBracket(view.state,insert);if(!tr)return false;view.dispatch(tr);return true});const deleteBracketPair=({state,dispatch})=>{if(state.readOnly)return false;let conf=config(state,state.selection.main.head);let tokens=conf.brackets||defaults.brackets;let dont=null,changes=state.changeByRange(range=>{if(range.empty){let before=prevChar(state.doc,range.head);for(let token of tokens){if(token==before&&nextChar(state.doc,range.head)==closing(codePointAt(token,0)))return{changes:{from:range.head-token.length,to:range.head+token.length},range:EditorSelection.cursor(range.head-token.length)}}}return{range:dont=range}});if(!dont)dispatch(state.update(changes,{scrollIntoView:true,userEvent:"delete.backward"}));return!dont};const closeBracketsKeymap=[{key:"Backspace",run:deleteBracketPair}];function insertBracket(state,bracket){let conf=config(state,state.selection.main.head);let tokens=conf.brackets||defaults.brackets;for(let tok of tokens){let closed=closing(codePointAt(tok,0));if(bracket==tok)return closed==tok?handleSame(state,tok,tokens.indexOf(tok+tok+tok)>-1,conf):handleOpen(state,tok,closed,conf.before||defaults.before);if(bracket==closed&&closedBracketAt(state,state.selection.main.from))return handleClose(state,tok,closed)}return null}function closedBracketAt(state,pos){let found=false;state.field(bracketState).between(0,state.doc.length,from=>{if(from==pos)found=true});return found}function nextChar(doc,pos){let next=doc.sliceString(pos,pos+2);return next.slice(0,codePointSize(codePointAt(next,0)))}function prevChar(doc,pos){let prev=doc.sliceString(pos-2,pos);return codePointSize(codePointAt(prev,0))==prev.length?prev:prev.slice(1)}function handleOpen(state,open,close,closeBefore){let dont=null,changes=state.changeByRange(range=>{if(!range.empty)return{changes:[{insert:open,from:range.from},{insert:close,from:range.to}],effects:closeBracketEffect.of(range.to+open.length),range:EditorSelection.range(range.anchor+open.length,range.head+open.length)};let next=nextChar(state.doc,range.head);if(!next||/\s/.test(next)||closeBefore.indexOf(next)>-1)return{changes:{insert:open+close,from:range.head},effects:closeBracketEffect.of(range.head+open.length),range:EditorSelection.cursor(range.head+open.length)};return{range:dont=range}});return dont?null:state.update(changes,{scrollIntoView:true,userEvent:"input.type"})}function handleClose(state,_open,close){let dont=null,moved=state.selection.ranges.map(range=>{if(range.empty&&nextChar(state.doc,range.head)==close)return EditorSelection.cursor(range.head+close.length);return dont=range});return dont?null:state.update({selection:EditorSelection.create(moved,state.selection.mainIndex),scrollIntoView:true,effects:state.selection.ranges.map(({from})=>skipBracketEffect.of(from))})}function handleSame(state,token,allowTriple,config){let stringPrefixes=config.stringPrefixes||defaults.stringPrefixes;let dont=null,changes=state.changeByRange(range=>{if(!range.empty)return{changes:[{insert:token,from:range.from},{insert:token,from:range.to}],effects:closeBracketEffect.of(range.to+token.length),range:EditorSelection.range(range.anchor+token.length,range.head+token.length)};let pos=range.head,next=nextChar(state.doc,pos),start;if(next==token){if(nodeStart(state,pos)){return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)}}else if(closedBracketAt(state,pos)){let isTriple=allowTriple&&state.sliceDoc(pos,pos+token.length*3)==token+token+token;return{range:EditorSelection.cursor(pos+token.length*(isTriple?3:1)),effects:skipBracketEffect.of(pos)}}}else if(allowTriple&&state.sliceDoc(pos-2*token.length,pos)==token+token&&(start=canStartStringAt(state,pos-2*token.length,stringPrefixes))>-1&&nodeStart(state,start)){return{changes:{insert:token+token+token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)}}else if(state.charCategorizer(pos)(next)!=CharCategory.Word){if(canStartStringAt(state,pos,stringPrefixes)>-1&&!probablyInString(state,pos,token,stringPrefixes))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)}}return{range:dont=range}});return dont?null:state.update(changes,{scrollIntoView:true,userEvent:"input.type"})}function nodeStart(state,pos){let tree=syntaxTree(state).resolveInner(pos+1);return tree.parent&&tree.from==pos}function probablyInString(state,pos,quoteToken,prefixes){let node=syntaxTree(state).resolveInner(pos,-1);let maxPrefix=prefixes.reduce((m,p)=>Math.max(m,p.length),0);for(let i=0;i<5;i++){let start=state.sliceDoc(node.from,Math.min(node.to,node.from+quoteToken.length+maxPrefix));let quotePos=start.indexOf(quoteToken);if(!quotePos||quotePos>-1&&prefixes.indexOf(start.slice(0,quotePos))>-1){let first=node.firstChild;while(first&&first.from==node.from&&first.to-first.from>quoteToken.length+quotePos){if(state.sliceDoc(first.to-quoteToken.length,first.to)==quoteToken)return false;first=first.firstChild}return true}let parent=node.to==pos&&node.parent;if(!parent)break;node=parent}return false}function canStartStringAt(state,pos,prefixes){let charCat=state.charCategorizer(pos);if(charCat(state.sliceDoc(pos-1,pos))!=CharCategory.Word)return pos;for(let prefix of prefixes){let start=pos-prefix.length;if(state.sliceDoc(start,pos)==prefix&&charCat(state.sliceDoc(start-1,start))!=CharCategory.Word)return start}return-1}function autocompletion(config={}){return[completionState,completionConfig.of(config),completionPlugin,completionKeymapExt,baseTheme]}const completionKeymap=[{key:"Ctrl-Space",run:startCompletion},{key:"Escape",run:closeCompletion},{key:"ArrowDown",run:moveCompletionSelection(true)},{key:"ArrowUp",run:moveCompletionSelection(false)},{key:"PageDown",run:moveCompletionSelection(true,"page")},{key:"PageUp",run:moveCompletionSelection(false,"page")},{key:"Enter",run:acceptCompletion}];const completionKeymapExt=Prec.highest(keymap.computeN([completionConfig],state=>state.facet(completionConfig).defaultKeymap?[completionKeymap]:[]));function completionStatus(state){let cState=state.field(completionState,false);return cState&&cState.active.some(a=>a.state==1)?"pending":cState&&cState.active.some(a=>a.state!=0)?"active":null}const completionArrayCache=new WeakMap;function currentCompletions(state){var _a;let open=(_a=state.field(completionState,false))===null||_a===void 0?void 0:_a.open;if(!open)return[];let completions=completionArrayCache.get(open.options);if(!completions)completionArrayCache.set(open.options,completions=open.options.map(o=>o.completion));return completions}function selectedCompletion(state){var _a;let open=(_a=state.field(completionState,false))===null||_a===void 0?void 0:_a.open;return open&&open.selected>=0?open.options[open.selected].completion:null}function selectedCompletionIndex(state){var _a;let open=(_a=state.field(completionState,false))===null||_a===void 0?void 0:_a.open;return open&&open.selected>=0?open.selected:null}function setSelectedCompletion(index){return setSelectedEffect.of(index)}export{CompletionContext,acceptCompletion,autocompletion,clearSnippet,closeBrackets,closeBracketsKeymap,closeCompletion,completeAnyWord,completeFromList,completionKeymap,completionStatus,currentCompletions,deleteBracketPair,ifIn,ifNotIn,insertBracket,insertCompletionText,moveCompletionSelection,nextSnippetField,pickedCompletion,prevSnippetField,selectedCompletion,selectedCompletionIndex,setSelectedCompletion,snippet,snippetCompletion,snippetKeymap,startCompletion};
\ No newline at end of file
diff --git a/public/js/@codemirror/commands.js b/public/js/@codemirror/commands.js
new file mode 100755
index 0000000..3c33684
--- /dev/null
+++ b/public/js/@codemirror/commands.js
@@ -0,0 +1 @@
+import{Annotation,Facet,combineConfig,StateField,EditorSelection,Transaction,ChangeSet,ChangeDesc,StateEffect,Text,findClusterBreak,countColumn,CharCategory}from"@codemirror/state";import{EditorView,Direction}from"@codemirror/view";import{IndentContext,getIndentation,indentString,indentUnit,getIndentUnit,matchBrackets,syntaxTree}from"@codemirror/language";import{NodeProp}from"@lezer/common";const toggleComment=target=>{let config=getConfig(target.state);return config.line?toggleLineComment(target):config.block?toggleBlockCommentByLine(target):false};function command(f,option){return({state,dispatch})=>{if(state.readOnly)return false;let tr=f(option,state);if(!tr)return false;dispatch(state.update(tr));return true}}const toggleLineComment=command(changeLineComment,0);const lineComment=command(changeLineComment,1);const lineUncomment=command(changeLineComment,2);const toggleBlockComment=command(changeBlockComment,0);const blockComment=command(changeBlockComment,1);const blockUncomment=command(changeBlockComment,2);const toggleBlockCommentByLine=command((o,s)=>changeBlockComment(o,s,selectedLineRanges(s)),0);function getConfig(state,pos=state.selection.main.head){let data=state.languageDataAt("commentTokens",pos);return data.length?data[0]:{}}const SearchMargin=50;function findBlockComment(state,{open,close},from,to){let textBefore=state.sliceDoc(from-SearchMargin,from);let textAfter=state.sliceDoc(to,to+SearchMargin);let spaceBefore=/\s*$/.exec(textBefore)[0].length,spaceAfter=/^\s*/.exec(textAfter)[0].length;let beforeOff=textBefore.length-spaceBefore;if(textBefore.slice(beforeOff-open.length,beforeOff)==open&&textAfter.slice(spaceAfter,spaceAfter+close.length)==close){return{open:{pos:from-spaceBefore,margin:spaceBefore&&1},close:{pos:to+spaceAfter,margin:spaceAfter&&1}}}let startText,endText;if(to-from<=2*SearchMargin){startText=endText=state.sliceDoc(from,to)}else{startText=state.sliceDoc(from,from+SearchMargin);endText=state.sliceDoc(to-SearchMargin,to)}let startSpace=/^\s*/.exec(startText)[0].length,endSpace=/\s*$/.exec(endText)[0].length;let endOff=endText.length-endSpace-close.length;if(startText.slice(startSpace,startSpace+open.length)==open&&endText.slice(endOff,endOff+close.length)==close){return{open:{pos:from+startSpace+open.length,margin:/\s/.test(startText.charAt(startSpace+open.length))?1:0},close:{pos:to-endSpace-close.length,margin:/\s/.test(endText.charAt(endOff-1))?1:0}}}return null}function selectedLineRanges(state){let ranges=[];for(let r of state.selection.ranges){let fromLine=state.doc.lineAt(r.from);let toLine=r.to<=fromLine.to?fromLine:state.doc.lineAt(r.to);let last=ranges.length-1;if(last>=0&&ranges[last].to>fromLine.from)ranges[last].to=toLine.to;else ranges.push({from:fromLine.from,to:toLine.to})}return ranges}function changeBlockComment(option,state,ranges=state.selection.ranges){let tokens=ranges.map(r=>getConfig(state,r.from).block);if(!tokens.every(c=>c))return null;let comments=ranges.map((r,i)=>findBlockComment(state,tokens[i],r.from,r.to));if(option!=2&&!comments.every(c=>c)){return{changes:state.changes(ranges.map((range,i)=>{if(comments[i])return[];return[{from:range.from,insert:tokens[i].open+" "},{from:range.to,insert:" "+tokens[i].close}]}))}}else if(option!=1&&comments.some(c=>c)){let changes=[];for(let i=0,comment;iprevLine&&(from==to||to>line.from)){prevLine=line.from;let token=getConfig(state,pos).line;if(!token)continue;let indent=/^\s*/.exec(line.text)[0].length;let empty=indent==line.length;let comment=line.text.slice(indent,indent+token.length)==token?indent:-1;if(indentl.comment<0&&(!l.empty||l.single))){let changes=[];for(let{line,token,indent,empty,single}of lines)if(single||!empty)changes.push({from:line.from+indent,insert:token+" "});let changeSet=state.changes(changes);return{changes:changeSet,selection:state.selection.map(changeSet,1)}}else if(option!=1&&lines.some(l=>l.comment>=0)){let changes=[];for(let{line,comment,token}of lines)if(comment>=0){let from=line.from+comment,to=from+token.length;if(line.text[to-line.from]==" ")to++;changes.push({from:from,to:to})}return{changes:changes}}return null}const fromHistory=Annotation.define();const isolateHistory=Annotation.define();const invertedEffects=Facet.define();const historyConfig=Facet.define({combine(configs){return combineConfig(configs,{minDepth:100,newGroupDelay:500},{minDepth:Math.max,newGroupDelay:Math.min})}});function changeEnd(changes){let end=0;changes.iterChangedRanges((_,to)=>end=to);return end}const historyField_=StateField.define({create(){return HistoryState.empty},update(state,tr){let config=tr.state.facet(historyConfig);let fromHist=tr.annotation(fromHistory);if(fromHist){let selection=tr.docChanged?EditorSelection.single(changeEnd(tr.changes)):undefined;let item=HistEvent.fromTransaction(tr,selection),from=fromHist.side;let other=from==0?state.undone:state.done;if(item)other=updateBranch(other,other.length,config.minDepth,item);else other=addSelection(other,tr.startState.selection);return new HistoryState(from==0?fromHist.rest:other,from==0?other:fromHist.rest)}let isolate=tr.annotation(isolateHistory);if(isolate=="full"||isolate=="before")state=state.isolate();if(tr.annotation(Transaction.addToHistory)===false)return!tr.changes.empty?state.addMapping(tr.changes.desc):state;let event=HistEvent.fromTransaction(tr);let time=tr.annotation(Transaction.time),userEvent=tr.annotation(Transaction.userEvent);if(event)state=state.addChanges(event,time,userEvent,config.newGroupDelay,config.minDepth);else if(tr.selection)state=state.addSelection(tr.startState.selection,time,userEvent,config.newGroupDelay);if(isolate=="full"||isolate=="after")state=state.isolate();return state},toJSON(value){return{done:value.done.map(e=>e.toJSON()),undone:value.undone.map(e=>e.toJSON())}},fromJSON(json){return new HistoryState(json.done.map(HistEvent.fromJSON),json.undone.map(HistEvent.fromJSON))}});function history(config={}){return[historyField_,historyConfig.of(config),EditorView.domEventHandlers({beforeinput(e,view){let command=e.inputType=="historyUndo"?undo:e.inputType=="historyRedo"?redo:null;if(!command)return false;e.preventDefault();return command(view)}})]}const historyField=historyField_;function cmd(side,selection){return function({state,dispatch}){if(!selection&&state.readOnly)return false;let historyState=state.field(historyField_,false);if(!historyState)return false;let tr=historyState.pop(side,state,selection);if(!tr)return false;dispatch(tr);return true}}const undo=cmd(0,false);const redo=cmd(1,false);const undoSelection=cmd(0,true);const redoSelection=cmd(1,true);function depth(side){return function(state){let histState=state.field(historyField_,false);if(!histState)return 0;let branch=side==0?histState.done:histState.undone;return branch.length-(branch.length&&!branch[0].changes?1:0)}}const undoDepth=depth(0);const redoDepth=depth(1);class HistEvent{constructor(changes,effects,mapped,startSelection,selectionsAfter){this.changes=changes;this.effects=effects;this.mapped=mapped;this.startSelection=startSelection;this.selectionsAfter=selectionsAfter}setSelAfter(after){return new HistEvent(this.changes,this.effects,this.mapped,this.startSelection,after)}toJSON(){var _a,_b,_c;return{changes:(_a=this.changes)===null||_a===void 0?void 0:_a.toJSON(),mapped:(_b=this.mapped)===null||_b===void 0?void 0:_b.toJSON(),startSelection:(_c=this.startSelection)===null||_c===void 0?void 0:_c.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(json){return new HistEvent(json.changes&&ChangeSet.fromJSON(json.changes),[],json.mapped&&ChangeDesc.fromJSON(json.mapped),json.startSelection&&EditorSelection.fromJSON(json.startSelection),json.selectionsAfter.map(EditorSelection.fromJSON))}static fromTransaction(tr,selection){let effects=none;for(let invert of tr.startState.facet(invertedEffects)){let result=invert(tr);if(result.length)effects=effects.concat(result)}if(!effects.length&&tr.changes.empty)return null;return new HistEvent(tr.changes.invert(tr.startState.doc),effects,undefined,selection||tr.startState.selection,none)}static selection(selections){return new HistEvent(undefined,none,undefined,undefined,selections)}}function updateBranch(branch,to,maxLen,newEvent){let start=to+1>maxLen+20?to-maxLen-1:0;let newBranch=branch.slice(start,to);newBranch.push(newEvent);return newBranch}function isAdjacent(a,b){let ranges=[],isAdjacent=false;a.iterChangedRanges((f,t)=>ranges.push(f,t));b.iterChangedRanges((_f,_t,f,t)=>{for(let i=0;i=from&&f<=to)isAdjacent=true}});return isAdjacent}function eqSelectionShape(a,b){return a.ranges.length==b.ranges.length&&a.ranges.filter((r,i)=>r.empty!=b.ranges[i].empty).length===0}function conc(a,b){return!a.length?b:!b.length?a:a.concat(b)}const none=[];const MaxSelectionsPerEvent=200;function addSelection(branch,selection){if(!branch.length){return[HistEvent.selection([selection])]}else{let lastEvent=branch[branch.length-1];let sels=lastEvent.selectionsAfter.slice(Math.max(0,lastEvent.selectionsAfter.length-MaxSelectionsPerEvent));if(sels.length&&sels[sels.length-1].eq(selection))return branch;sels.push(selection);return updateBranch(branch,branch.length-1,1e9,lastEvent.setSelAfter(sels))}}function popSelection(branch){let last=branch[branch.length-1];let newBranch=branch.slice();newBranch[branch.length-1]=last.setSelAfter(last.selectionsAfter.slice(0,last.selectionsAfter.length-1));return newBranch}function addMappingToBranch(branch,mapping){if(!branch.length)return branch;let length=branch.length,selections=none;while(length){let event=mapEvent(branch[length-1],mapping,selections);if(event.changes&&!event.changes.empty||event.effects.length){let result=branch.slice(0,length);result[length-1]=event;return result}else{mapping=event.mapped;length--;selections=event.selectionsAfter}}return selections.length?[HistEvent.selection(selections)]:none}function mapEvent(event,mapping,extraSelections){let selections=conc(event.selectionsAfter.length?event.selectionsAfter.map(s=>s.map(mapping)):none,extraSelections);if(!event.changes)return HistEvent.selection(selections);let mappedChanges=event.changes.map(mapping),before=mapping.mapDesc(event.changes,true);let fullMapping=event.mapped?event.mapped.composeDesc(before):before;return new HistEvent(mappedChanges,StateEffect.mapEffects(event.effects,mapping),fullMapping,event.startSelection.map(before),selections)}const joinableUserEvent=/^(input\.type|delete)($|\.)/;class HistoryState{constructor(done,undone,prevTime=0,prevUserEvent=undefined){this.done=done;this.undone=undone;this.prevTime=prevTime;this.prevUserEvent=prevUserEvent}isolate(){return this.prevTime?new HistoryState(this.done,this.undone):this}addChanges(event,time,userEvent,newGroupDelay,maxLen){let done=this.done,lastEvent=done[done.length-1];if(lastEvent&&lastEvent.changes&&!lastEvent.changes.empty&&event.changes&&(!userEvent||joinableUserEvent.test(userEvent))&&(!lastEvent.selectionsAfter.length&&time-this.prevTime0&&time-this.prevTimerange.empty?view.moveByChar(range,forward):rangeEnd(range,forward))}function ltrAtCursor(view){return view.textDirectionAt(view.state.selection.main.head)==Direction.LTR}const cursorCharLeft=view=>cursorByChar(view,!ltrAtCursor(view));const cursorCharRight=view=>cursorByChar(view,ltrAtCursor(view));const cursorCharForward=view=>cursorByChar(view,true);const cursorCharBackward=view=>cursorByChar(view,false);function cursorByGroup(view,forward){return moveSel(view,range=>range.empty?view.moveByGroup(range,forward):rangeEnd(range,forward))}const cursorGroupLeft=view=>cursorByGroup(view,!ltrAtCursor(view));const cursorGroupRight=view=>cursorByGroup(view,ltrAtCursor(view));const cursorGroupForward=view=>cursorByGroup(view,true);const cursorGroupBackward=view=>cursorByGroup(view,false);function moveBySubword(view,range,forward){let categorize=view.state.charCategorizer(range.from);return view.moveByChar(range,forward,start=>{let cat=CharCategory.Space,pos=range.from;let done=false,sawUpper=false,sawLower=false;let step=next=>{if(done)return false;pos+=forward?next.length:-next.length;let nextCat=categorize(next),ahead;if(cat==CharCategory.Space)cat=nextCat;if(cat!=nextCat)return false;if(cat==CharCategory.Word){if(next.toLowerCase()==next){if(!forward&&sawUpper)return false;sawLower=true}else if(sawLower){if(forward)return false;done=true}else{if(sawUpper&&forward&&categorize(ahead=view.state.sliceDoc(pos,pos+1))==CharCategory.Word&&ahead.toLowerCase()==ahead)return false;sawUpper=true}}return true};step(start);return step})}function cursorBySubword(view,forward){return moveSel(view,range=>range.empty?moveBySubword(view,range,forward):rangeEnd(range,forward))}const cursorSubwordForward=view=>cursorBySubword(view,true);const cursorSubwordBackward=view=>cursorBySubword(view,false);function interestingNode(state,node,bracketProp){if(node.type.prop(bracketProp))return true;let len=node.to-node.from;return len&&(len>2||/[^\s,.;:]/.test(state.sliceDoc(node.from,node.to)))||node.firstChild}function moveBySyntax(state,start,forward){let pos=syntaxTree(state).resolveInner(start.head);let bracketProp=forward?NodeProp.closedBy:NodeProp.openedBy;for(let at=start.head;;){let next=forward?pos.childAfter(at):pos.childBefore(at);if(!next)break;if(interestingNode(state,next,bracketProp))pos=next;else at=forward?next.to:next.from}let bracket=pos.type.prop(bracketProp),match,newPos;if(bracket&&(match=forward?matchBrackets(state,pos.from,1):matchBrackets(state,pos.to,-1))&&match.matched)newPos=forward?match.end.to:match.end.from;else newPos=forward?pos.to:pos.from;return EditorSelection.cursor(newPos,forward?-1:1)}const cursorSyntaxLeft=view=>moveSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view)));const cursorSyntaxRight=view=>moveSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view)));function cursorByLine(view,forward){return moveSel(view,range=>{if(!range.empty)return rangeEnd(range,forward);let moved=view.moveVertically(range,forward);return moved.head!=range.head?moved:view.moveToLineBoundary(range,forward)})}const cursorLineUp=view=>cursorByLine(view,false);const cursorLineDown=view=>cursorByLine(view,true);function pageHeight(view){return Math.max(view.defaultLineHeight,Math.min(view.dom.clientHeight,innerHeight)-5)}function cursorByPage(view,forward){let{state}=view,selection=updateSel(state.selection,range=>{return range.empty?view.moveVertically(range,forward,pageHeight(view)):rangeEnd(range,forward)});if(selection.eq(state.selection))return false;let startPos=view.coordsAtPos(state.selection.main.head);let scrollRect=view.scrollDOM.getBoundingClientRect();let effect;if(startPos&&startPos.top>scrollRect.top&&startPos.bottomcursorByPage(view,false);const cursorPageDown=view=>cursorByPage(view,true);function moveByLineBoundary(view,start,forward){let line=view.lineBlockAt(start.head),moved=view.moveToLineBoundary(start,forward);if(moved.head==start.head&&moved.head!=(forward?line.to:line.from))moved=view.moveToLineBoundary(start,forward,false);if(!forward&&moved.head==line.from&&line.length){let space=/^\s*/.exec(view.state.sliceDoc(line.from,Math.min(line.from+100,line.to)))[0].length;if(space&&start.head!=line.from+space)moved=EditorSelection.cursor(line.from+space)}return moved}const cursorLineBoundaryForward=view=>moveSel(view,range=>moveByLineBoundary(view,range,true));const cursorLineBoundaryBackward=view=>moveSel(view,range=>moveByLineBoundary(view,range,false));const cursorLineBoundaryLeft=view=>moveSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view)));const cursorLineBoundaryRight=view=>moveSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view)));const cursorLineStart=view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from,1));const cursorLineEnd=view=>moveSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to,-1));function toMatchingBracket(state,dispatch,extend){let found=false,selection=updateSel(state.selection,range=>{let matching=matchBrackets(state,range.head,-1)||matchBrackets(state,range.head,1)||range.head>0&&matchBrackets(state,range.head-1,1)||range.headtoMatchingBracket(state,dispatch,false);const selectMatchingBracket=({state,dispatch})=>toMatchingBracket(state,dispatch,true);function extendSel(view,how){let selection=updateSel(view.state.selection,range=>{let head=how(range);return EditorSelection.range(range.anchor,head.head,head.goalColumn)});if(selection.eq(view.state.selection))return false;view.dispatch(setSel(view.state,selection));return true}function selectByChar(view,forward){return extendSel(view,range=>view.moveByChar(range,forward))}const selectCharLeft=view=>selectByChar(view,!ltrAtCursor(view));const selectCharRight=view=>selectByChar(view,ltrAtCursor(view));const selectCharForward=view=>selectByChar(view,true);const selectCharBackward=view=>selectByChar(view,false);function selectByGroup(view,forward){return extendSel(view,range=>view.moveByGroup(range,forward))}const selectGroupLeft=view=>selectByGroup(view,!ltrAtCursor(view));const selectGroupRight=view=>selectByGroup(view,ltrAtCursor(view));const selectGroupForward=view=>selectByGroup(view,true);const selectGroupBackward=view=>selectByGroup(view,false);function selectBySubword(view,forward){return extendSel(view,range=>moveBySubword(view,range,forward))}const selectSubwordForward=view=>selectBySubword(view,true);const selectSubwordBackward=view=>selectBySubword(view,false);const selectSyntaxLeft=view=>extendSel(view,range=>moveBySyntax(view.state,range,!ltrAtCursor(view)));const selectSyntaxRight=view=>extendSel(view,range=>moveBySyntax(view.state,range,ltrAtCursor(view)));function selectByLine(view,forward){return extendSel(view,range=>view.moveVertically(range,forward))}const selectLineUp=view=>selectByLine(view,false);const selectLineDown=view=>selectByLine(view,true);function selectByPage(view,forward){return extendSel(view,range=>view.moveVertically(range,forward,pageHeight(view)))}const selectPageUp=view=>selectByPage(view,false);const selectPageDown=view=>selectByPage(view,true);const selectLineBoundaryForward=view=>extendSel(view,range=>moveByLineBoundary(view,range,true));const selectLineBoundaryBackward=view=>extendSel(view,range=>moveByLineBoundary(view,range,false));const selectLineBoundaryLeft=view=>extendSel(view,range=>moveByLineBoundary(view,range,!ltrAtCursor(view)));const selectLineBoundaryRight=view=>extendSel(view,range=>moveByLineBoundary(view,range,ltrAtCursor(view)));const selectLineStart=view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).from));const selectLineEnd=view=>extendSel(view,range=>EditorSelection.cursor(view.lineBlockAt(range.head).to));const cursorDocStart=({state,dispatch})=>{dispatch(setSel(state,{anchor:0}));return true};const cursorDocEnd=({state,dispatch})=>{dispatch(setSel(state,{anchor:state.doc.length}));return true};const selectDocStart=({state,dispatch})=>{dispatch(setSel(state,{anchor:state.selection.main.anchor,head:0}));return true};const selectDocEnd=({state,dispatch})=>{dispatch(setSel(state,{anchor:state.selection.main.anchor,head:state.doc.length}));return true};const selectAll=({state,dispatch})=>{dispatch(state.update({selection:{anchor:0,head:state.doc.length},userEvent:"select"}));return true};const selectLine=({state,dispatch})=>{let ranges=selectedLineBlocks(state).map(({from,to})=>EditorSelection.range(from,Math.min(to+1,state.doc.length)));dispatch(state.update({selection:EditorSelection.create(ranges),userEvent:"select"}));return true};const selectParentSyntax=({state,dispatch})=>{let selection=updateSel(state.selection,range=>{var _a;let context=syntaxTree(state).resolveInner(range.head,1);while(!(context.from=range.to||context.to>range.to&&context.from<=range.from||!((_a=context.parent)===null||_a===void 0?void 0:_a.parent)))context=context.parent;return EditorSelection.range(context.to,context.from)});dispatch(setSel(state,selection));return true};const simplifySelection=({state,dispatch})=>{let cur=state.selection,selection=null;if(cur.ranges.length>1)selection=EditorSelection.create([cur.main]);else if(!cur.main.empty)selection=EditorSelection.create([EditorSelection.cursor(cur.main.head)]);if(!selection)return false;dispatch(setSel(state,selection));return true};function deleteBy(target,by){if(target.state.readOnly)return false;let event="delete.selection",{state}=target;let changes=state.changeByRange(range=>{let{from,to}=range;if(from==to){let towards=by(from);if(towardsfrom){event="delete.forward";towards=skipAtomic(target,towards,true)}from=Math.min(from,towards);to=Math.max(to,towards)}else{from=skipAtomic(target,from,false);to=skipAtomic(target,to,true)}return from==to?{range:range}:{changes:{from:from,to:to},range:EditorSelection.cursor(from)}});if(changes.changes.empty)return false;target.dispatch(state.update(changes,{scrollIntoView:true,userEvent:event,effects:event=="delete.selection"?EditorView.announce.of(state.phrase("Selection deleted")):undefined}));return true}function skipAtomic(target,pos,forward){if(target instanceof EditorView)for(let ranges of target.state.facet(EditorView.atomicRanges).map(f=>f(target)))ranges.between(pos,pos,(from,to)=>{if(frompos)pos=forward?to:from});return pos}const deleteByChar=(target,forward)=>deleteBy(target,pos=>{let{state}=target,line=state.doc.lineAt(pos),before,targetPos;if(!forward&&pos>line.from&&posdeleteByChar(view,false);const deleteCharForward=view=>deleteByChar(view,true);const deleteByGroup=(target,forward)=>deleteBy(target,start=>{let pos=start,{state}=target,line=state.doc.lineAt(pos);let categorize=state.charCategorizer(pos);for(let cat=null;;){if(pos==(forward?line.to:line.from)){if(pos==start&&line.number!=(forward?state.doc.lines:1))pos+=forward?1:-1;break}let next=findClusterBreak(line.text,pos-line.from,forward)+line.from;let nextChar=line.text.slice(Math.min(pos,next)-line.from,Math.max(pos,next)-line.from);let nextCat=categorize(nextChar);if(cat!=null&&nextCat!=cat)break;if(nextChar!=" "||pos!=start)cat=nextCat;pos=next}return pos});const deleteGroupBackward=target=>deleteByGroup(target,false);const deleteGroupForward=target=>deleteByGroup(target,true);const deleteToLineEnd=view=>deleteBy(view,pos=>{let lineEnd=view.lineBlockAt(pos).to;return posdeleteBy(view,pos=>{let lineStart=view.lineBlockAt(pos).from;return pos>lineStart?lineStart:Math.max(0,pos-1)});const deleteTrailingWhitespace=({state,dispatch})=>{if(state.readOnly)return false;let changes=[];for(let pos=0,prev="",iter=state.doc.iter();;){iter.next();if(iter.lineBreak||iter.done){let trailing=prev.search(/\s+$/);if(trailing>-1)changes.push({from:pos-(prev.length-trailing),to:pos});if(iter.done)break;prev=""}else{prev=iter.value}pos+=iter.value.length}if(!changes.length)return false;dispatch(state.update({changes:changes,userEvent:"delete"}));return true};const splitLine=({state,dispatch})=>{if(state.readOnly)return false;let changes=state.changeByRange(range=>{return{changes:{from:range.from,to:range.to,insert:Text.of(["",""])},range:EditorSelection.cursor(range.from)}});dispatch(state.update(changes,{scrollIntoView:true,userEvent:"input"}));return true};const transposeChars=({state,dispatch})=>{if(state.readOnly)return false;let changes=state.changeByRange(range=>{if(!range.empty||range.from==0||range.from==state.doc.length)return{range:range};let pos=range.from,line=state.doc.lineAt(pos);let from=pos==line.from?pos-1:findClusterBreak(line.text,pos-line.from,false)+line.from;let to=pos==line.to?pos+1:findClusterBreak(line.text,pos-line.from,true)+line.from;return{changes:{from:from,to:to,insert:state.doc.slice(pos,to).append(state.doc.slice(from,pos))},range:EditorSelection.cursor(to)}});if(changes.changes.empty)return false;dispatch(state.update(changes,{scrollIntoView:true,userEvent:"move.character"}));return true};function selectedLineBlocks(state){let blocks=[],upto=-1;for(let range of state.selection.ranges){let startLine=state.doc.lineAt(range.from),endLine=state.doc.lineAt(range.to);if(!range.empty&&range.to==endLine.from)endLine=state.doc.lineAt(range.to-1);if(upto>=startLine.number){let prev=blocks[blocks.length-1];prev.to=endLine.to;prev.ranges.push(range)}else{blocks.push({from:startLine.from,to:endLine.to,ranges:[range]})}upto=endLine.number+1}return blocks}function moveLine(state,dispatch,forward){if(state.readOnly)return false;let changes=[],ranges=[];for(let block of selectedLineBlocks(state)){if(forward?block.to==state.doc.length:block.from==0)continue;let nextLine=state.doc.lineAt(forward?block.to+1:block.from-1);let size=nextLine.length+1;if(forward){changes.push({from:block.to,to:nextLine.to},{from:block.from,insert:nextLine.text+state.lineBreak});for(let r of block.ranges)ranges.push(EditorSelection.range(Math.min(state.doc.length,r.anchor+size),Math.min(state.doc.length,r.head+size)))}else{changes.push({from:nextLine.from,to:block.from},{from:block.to,insert:state.lineBreak+nextLine.text});for(let r of block.ranges)ranges.push(EditorSelection.range(r.anchor-size,r.head-size))}}if(!changes.length)return false;dispatch(state.update({changes:changes,scrollIntoView:true,selection:EditorSelection.create(ranges,state.selection.mainIndex),userEvent:"move.line"}));return true}const moveLineUp=({state,dispatch})=>moveLine(state,dispatch,false);const moveLineDown=({state,dispatch})=>moveLine(state,dispatch,true);function copyLine(state,dispatch,forward){if(state.readOnly)return false;let changes=[];for(let block of selectedLineBlocks(state)){if(forward)changes.push({from:block.from,insert:state.doc.slice(block.from,block.to)+state.lineBreak});else changes.push({from:block.to,insert:state.lineBreak+state.doc.slice(block.from,block.to)})}dispatch(state.update({changes:changes,scrollIntoView:true,userEvent:"input.copyline"}));return true}const copyLineUp=({state,dispatch})=>copyLine(state,dispatch,false);const copyLineDown=({state,dispatch})=>copyLine(state,dispatch,true);const deleteLine=view=>{if(view.state.readOnly)return false;let{state}=view,changes=state.changes(selectedLineBlocks(state).map(({from,to})=>{if(from>0)from--;else if(toview.moveVertically(range,true)).map(changes);view.dispatch({changes:changes,selection:selection,scrollIntoView:true,userEvent:"delete.line"});return true};const insertNewline=({state,dispatch})=>{dispatch(state.update(state.replaceSelection(state.lineBreak),{scrollIntoView:true,userEvent:"input"}));return true};function isBetweenBrackets(state,pos){if(/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos-1,pos+1)))return{from:pos,to:pos};let context=syntaxTree(state).resolveInner(pos);let before=context.childBefore(pos),after=context.childAfter(pos),closedBy;if(before&&after&&before.to<=pos&&after.from>=pos&&(closedBy=before.type.prop(NodeProp.closedBy))&&closedBy.indexOf(after.name)>-1&&state.doc.lineAt(before.to).from==state.doc.lineAt(after.from).from)return{from:before.to,to:after.from};return null}const insertNewlineAndIndent=newlineAndIndent(false);const insertBlankLine=newlineAndIndent(true);function newlineAndIndent(atEof){return({state,dispatch})=>{if(state.readOnly)return false;let changes=state.changeByRange(range=>{let{from,to}=range,line=state.doc.lineAt(from);let explode=!atEof&&from==to&&isBetweenBrackets(state,from);if(atEof)from=to=(to<=line.to?line:state.doc.lineAt(to)).to;let cx=new IndentContext(state,{simulateBreak:from,simulateDoubleBreak:!!explode});let indent=getIndentation(cx,from);if(indent==null)indent=/^\s*/.exec(state.doc.lineAt(from).text)[0].length;while(toline.from&&from{let changes=[];for(let pos=range.from;pos<=range.to;){let line=state.doc.lineAt(pos);if(line.number>atLine&&(range.empty||range.to>line.from)){f(line,changes,range);atLine=line.number}pos=line.to+1}let changeSet=state.changes(changes);return{changes:changes,range:EditorSelection.range(changeSet.mapPos(range.anchor,1),changeSet.mapPos(range.head,1))}})}const indentSelection=({state,dispatch})=>{if(state.readOnly)return false;let updated=Object.create(null);let context=new IndentContext(state,{overrideIndentation:start=>{let found=updated[start];return found==null?-1:found}});let changes=changeBySelectedLine(state,(line,changes,range)=>{let indent=getIndentation(context,line.from);if(indent==null)return;if(!/\S/.test(line.text))indent=0;let cur=/^\s*/.exec(line.text)[0];let norm=indentString(state,indent);if(cur!=norm||range.from{if(state.readOnly)return false;dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{changes.push({from:line.from,insert:state.facet(indentUnit)})}),{userEvent:"input.indent"}));return true};const indentLess=({state,dispatch})=>{if(state.readOnly)return false;dispatch(state.update(changeBySelectedLine(state,(line,changes)=>{let space=/^\s*/.exec(line.text)[0];if(!space)return;let col=countColumn(space,state.tabSize),keep=0;let insert=indentString(state,Math.max(0,col-getIndentUnit(state)));while(keep{if(state.selection.ranges.some(r=>!r.empty))return indentMore({state:state,dispatch:dispatch});dispatch(state.update(state.replaceSelection("\t"),{scrollIntoView:true,userEvent:"input"}));return true};const emacsStyleKeymap=[{key:"Ctrl-b",run:cursorCharLeft,shift:selectCharLeft,preventDefault:true},{key:"Ctrl-f",run:cursorCharRight,shift:selectCharRight},{key:"Ctrl-p",run:cursorLineUp,shift:selectLineUp},{key:"Ctrl-n",run:cursorLineDown,shift:selectLineDown},{key:"Ctrl-a",run:cursorLineStart,shift:selectLineStart},{key:"Ctrl-e",run:cursorLineEnd,shift:selectLineEnd},{key:"Ctrl-d",run:deleteCharForward},{key:"Ctrl-h",run:deleteCharBackward},{key:"Ctrl-k",run:deleteToLineEnd},{key:"Ctrl-Alt-h",run:deleteGroupBackward},{key:"Ctrl-o",run:splitLine},{key:"Ctrl-t",run:transposeChars},{key:"Ctrl-v",run:cursorPageDown}];const standardKeymap=[{key:"ArrowLeft",run:cursorCharLeft,shift:selectCharLeft,preventDefault:true},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:cursorGroupLeft,shift:selectGroupLeft,preventDefault:true},{mac:"Cmd-ArrowLeft",run:cursorLineBoundaryLeft,shift:selectLineBoundaryLeft,preventDefault:true},{key:"ArrowRight",run:cursorCharRight,shift:selectCharRight,preventDefault:true},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:cursorGroupRight,shift:selectGroupRight,preventDefault:true},{mac:"Cmd-ArrowRight",run:cursorLineBoundaryRight,shift:selectLineBoundaryRight,preventDefault:true},{key:"ArrowUp",run:cursorLineUp,shift:selectLineUp,preventDefault:true},{mac:"Cmd-ArrowUp",run:cursorDocStart,shift:selectDocStart},{mac:"Ctrl-ArrowUp",run:cursorPageUp,shift:selectPageUp},{key:"ArrowDown",run:cursorLineDown,shift:selectLineDown,preventDefault:true},{mac:"Cmd-ArrowDown",run:cursorDocEnd,shift:selectDocEnd},{mac:"Ctrl-ArrowDown",run:cursorPageDown,shift:selectPageDown},{key:"PageUp",run:cursorPageUp,shift:selectPageUp},{key:"PageDown",run:cursorPageDown,shift:selectPageDown},{key:"Home",run:cursorLineBoundaryBackward,shift:selectLineBoundaryBackward,preventDefault:true},{key:"Mod-Home",run:cursorDocStart,shift:selectDocStart},{key:"End",run:cursorLineBoundaryForward,shift:selectLineBoundaryForward,preventDefault:true},{key:"Mod-End",run:cursorDocEnd,shift:selectDocEnd},{key:"Enter",run:insertNewlineAndIndent},{key:"Mod-a",run:selectAll},{key:"Backspace",run:deleteCharBackward,shift:deleteCharBackward},{key:"Delete",run:deleteCharForward},{key:"Mod-Backspace",mac:"Alt-Backspace",run:deleteGroupBackward},{key:"Mod-Delete",mac:"Alt-Delete",run:deleteGroupForward},{mac:"Mod-Backspace",run:deleteToLineStart},{mac:"Mod-Delete",run:deleteToLineEnd}].concat(emacsStyleKeymap.map(b=>({mac:b.key,run:b.run,shift:b.shift})));const defaultKeymap=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:cursorSyntaxLeft,shift:selectSyntaxLeft},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:cursorSyntaxRight,shift:selectSyntaxRight},{key:"Alt-ArrowUp",run:moveLineUp},{key:"Shift-Alt-ArrowUp",run:copyLineUp},{key:"Alt-ArrowDown",run:moveLineDown},{key:"Shift-Alt-ArrowDown",run:copyLineDown},{key:"Escape",run:simplifySelection},{key:"Mod-Enter",run:insertBlankLine},{key:"Alt-l",mac:"Ctrl-l",run:selectLine},{key:"Mod-i",run:selectParentSyntax,preventDefault:true},{key:"Mod-[",run:indentLess},{key:"Mod-]",run:indentMore},{key:"Mod-Alt-\\",run:indentSelection},{key:"Shift-Mod-k",run:deleteLine},{key:"Shift-Mod-\\",run:cursorMatchingBracket},{key:"Mod-/",run:toggleComment},{key:"Alt-A",run:toggleBlockComment}].concat(standardKeymap);const indentWithTab={key:"Tab",run:indentMore,shift:indentLess};export{blockComment,blockUncomment,copyLineDown,copyLineUp,cursorCharBackward,cursorCharForward,cursorCharLeft,cursorCharRight,cursorDocEnd,cursorDocStart,cursorGroupBackward,cursorGroupForward,cursorGroupLeft,cursorGroupRight,cursorLineBoundaryBackward,cursorLineBoundaryForward,cursorLineBoundaryLeft,cursorLineBoundaryRight,cursorLineDown,cursorLineEnd,cursorLineStart,cursorLineUp,cursorMatchingBracket,cursorPageDown,cursorPageUp,cursorSubwordBackward,cursorSubwordForward,cursorSyntaxLeft,cursorSyntaxRight,defaultKeymap,deleteCharBackward,deleteCharForward,deleteGroupBackward,deleteGroupForward,deleteLine,deleteToLineEnd,deleteToLineStart,deleteTrailingWhitespace,emacsStyleKeymap,history,historyField,historyKeymap,indentLess,indentMore,indentSelection,indentWithTab,insertBlankLine,insertNewline,insertNewlineAndIndent,insertTab,invertedEffects,isolateHistory,lineComment,lineUncomment,moveLineDown,moveLineUp,redo,redoDepth,redoSelection,selectAll,selectCharBackward,selectCharForward,selectCharLeft,selectCharRight,selectDocEnd,selectDocStart,selectGroupBackward,selectGroupForward,selectGroupLeft,selectGroupRight,selectLine,selectLineBoundaryBackward,selectLineBoundaryForward,selectLineBoundaryLeft,selectLineBoundaryRight,selectLineDown,selectLineEnd,selectLineStart,selectLineUp,selectMatchingBracket,selectPageDown,selectPageUp,selectParentSyntax,selectSubwordBackward,selectSubwordForward,selectSyntaxLeft,selectSyntaxRight,simplifySelection,splitLine,standardKeymap,toggleBlockComment,toggleBlockCommentByLine,toggleComment,toggleLineComment,transposeChars,undo,undoDepth,undoSelection};
\ No newline at end of file
diff --git a/public/js/@codemirror/lang-css.js b/public/js/@codemirror/lang-css.js
new file mode 100755
index 0000000..5960ab8
--- /dev/null
+++ b/public/js/@codemirror/lang-css.js
@@ -0,0 +1 @@
+import{parser}from"@lezer/css";import{syntaxTree,LRLanguage,indentNodeProp,continuedIndent,foldNodeProp,foldInside,LanguageSupport}from"@codemirror/language";let _properties=null;function properties(){if(!_properties&&typeof document=="object"&&document.body){let names=[];for(let prop in document.body.style){if(!/[A-Z]|^-|^(item|length)$/.test(prop))names.push(prop)}_properties=names.sort().map(name=>({type:"property",label:name}))}return _properties||[]}const pseudoClasses=["active","after","any-link","autofill","backdrop","before","checked","cue","default","defined","disabled","empty","enabled","file-selector-button","first","first-child","first-letter","first-line","first-of-type","focus","focus-visible","focus-within","fullscreen","has","host","host-context","hover","in-range","indeterminate","invalid","is","lang","last-child","last-of-type","left","link","marker","modal","not","nth-child","nth-last-child","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","part","placeholder","placeholder-shown","read-only","read-write","required","right","root","scope","selection","slotted","target","target-text","valid","visited","where"].map(name=>({type:"class",label:name}));const values=["above","absolute","activeborder","additive","activecaption","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","antialiased","appworkspace","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic-abegede-gez","ethiopic-halehame-aa-er","ethiopic-halehame-gez","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","graytext","grid","groove","hand","hard-light","help","hidden","hide","higher","highlight","highlighttext","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","justify","keep-all","landscape","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-hexadecimal","lower-latin","lower-norwegian","lowercase","ltr","luminosity","manipulation","match","matrix","matrix3d","medium","menu","menutext","message-box","middle","min-intrinsic","mix","monospace","move","multiple","multiple_mask_images","multiply","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","opacity","open-quote","optimizeLegibility","optimizeSpeed","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","text","text-bottom","text-top","textarea","textfield","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","to","top","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-latin","uppercase","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"].map(name=>({type:"keyword",label:name})).concat(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].map(name=>({type:"constant",label:name})));const tags=["a","abbr","address","article","aside","b","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","dd","del","details","dfn","dialog","div","dl","dt","em","figcaption","figure","footer","form","header","hgroup","h1","h2","h3","h4","h5","h6","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","main","meter","nav","ol","output","p","pre","ruby","section","select","small","source","span","strong","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","tr","u","ul"].map(name=>({type:"type",label:name}));const identifier=/^[\w-]*/;const cssCompletionSource=context=>{let{state,pos}=context,node=syntaxTree(state).resolveInner(pos,-1);if(node.name=="PropertyName")return{from:node.from,options:properties(),validFor:identifier};if(node.name=="ValueName")return{from:node.from,options:values,validFor:identifier};if(node.name=="PseudoClassName")return{from:node.from,options:pseudoClasses,validFor:identifier};if(node.name=="TagName"){for(let{parent}=node;parent;parent=parent.parent)if(parent.name=="Block")return{from:node.from,options:properties(),validFor:identifier};return{from:node.from,options:tags,validFor:identifier}}if(!context.explicit)return null;let above=node.resolve(pos),before=above.childBefore(pos);if(before&&before.name==":"&&above.name=="PseudoClassSelector")return{from:pos,options:pseudoClasses,validFor:identifier};if(before&&before.name==":"&&above.name=="Declaration"||above.name=="ArgList")return{from:pos,options:values,validFor:identifier};if(above.name=="Block")return{from:pos,options:properties(),validFor:identifier};return null};const cssLanguage=LRLanguage.define({name:"css",parser:parser.configure({props:[indentNodeProp.add({Declaration:continuedIndent()}),foldNodeProp.add({Block:foldInside})]}),languageData:{commentTokens:{block:{open:"/*",close:"*/"}},indentOnInput:/^\s*\}$/,wordChars:"-"}});function css(){return new LanguageSupport(cssLanguage,cssLanguage.data.of({autocomplete:cssCompletionSource}))}export{css,cssCompletionSource,cssLanguage};
\ No newline at end of file
diff --git a/public/js/@codemirror/lang-html.js b/public/js/@codemirror/lang-html.js
new file mode 100755
index 0000000..cc5717e
--- /dev/null
+++ b/public/js/@codemirror/lang-html.js
@@ -0,0 +1 @@
+import{parser,configureNesting}from"@lezer/html";import{cssLanguage,css}from"@codemirror/lang-css";import{javascriptLanguage,javascript}from"@codemirror/lang-javascript";import{EditorView}from"@codemirror/view";import{EditorSelection}from"@codemirror/state";import{syntaxTree,LRLanguage,indentNodeProp,foldNodeProp,LanguageSupport}from"@codemirror/language";const Targets=["_blank","_self","_top","_parent"];const Charsets=["ascii","utf-8","utf-16","latin1","latin1"];const Methods=["get","post","put","delete"];const Encs=["application/x-www-form-urlencoded","multipart/form-data","text/plain"];const Bool=["true","false"];const S={};const Tags={a:{attrs:{href:null,ping:null,type:null,media:null,target:Targets,hreflang:null}},abbr:S,address:S,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:S,aside:S,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:S,base:{attrs:{href:null,target:Targets}},bdi:S,bdo:S,blockquote:{attrs:{cite:null}},body:S,br:S,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Encs,formmethod:Methods,formnovalidate:["novalidate"],formtarget:Targets,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:S,center:S,cite:S,code:S,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:S,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:S,div:S,dl:S,dt:S,em:S,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:S,figure:S,footer:S,form:{attrs:{action:null,name:null,"accept-charset":Charsets,autocomplete:["on","off"],enctype:Encs,method:Methods,novalidate:["novalidate"],target:Targets}},h1:S,h2:S,h3:S,h4:S,h5:S,h6:S,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:S,hgroup:S,hr:S,html:{attrs:{manifest:null}},i:S,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:Encs,formmethod:Methods,formnovalidate:["novalidate"],formtarget:Targets,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:S,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:S,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:S,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:Charsets,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:S,noscript:S,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:S,param:{attrs:{name:null,value:null}},pre:S,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:S,rt:S,ruby:S,samp:S,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:Charsets}},section:S,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:S,source:{attrs:{src:null,type:null,media:null}},span:S,strong:S,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:S,summary:S,sup:S,table:S,tbody:S,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:S,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:S,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:S,time:{attrs:{datetime:null}},title:S,tr:S,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:S,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:S};const GlobalAttrs={accesskey:null,class:null,contenteditable:Bool,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:Bool,autocorrect:Bool,autocapitalize:Bool,style:null,tabindex:null,title:null,translate:["yes","no"],onclick:null,rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":Bool,"aria-autocomplete":["inline","list","both","none"],"aria-busy":Bool,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":Bool,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":Bool,"aria-hidden":Bool,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":Bool,"aria-multiselectable":Bool,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":Bool,"aria-relevant":null,"aria-required":Bool,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null};class Schema{constructor(extraTags,extraAttrs){this.tags=Object.assign(Object.assign({},Tags),extraTags);this.globalAttrs=Object.assign(Object.assign({},GlobalAttrs),extraAttrs);this.allTags=Object.keys(this.tags);this.globalAttrNames=Object.keys(this.globalAttrs)}}Schema.default=new Schema;function elementName(doc,tree,max=doc.length){if(!tree)return"";let tag=tree.firstChild;let name=tag&&tag.getChild("TagName");return name?doc.sliceString(name.from,Math.min(name.to,max)):""}function findParentElement(tree,skip=false){for(let cur=tree.parent;cur;cur=cur.parent)if(cur.name=="Element"){if(skip)skip=false;else return cur}return null}function allowedChildren(doc,tree,schema){let parentInfo=schema.tags[elementName(doc,findParentElement(tree,true))];return(parentInfo===null||parentInfo===void 0?void 0:parentInfo.children)||schema.allTags}function openTags(doc,tree){let open=[];for(let parent=tree;parent=findParentElement(parent);){let tagName=elementName(doc,parent);if(tagName&&parent.lastChild.name=="CloseTag")break;if(tagName&&open.indexOf(tagName)<0&&(tree.name=="EndTag"||tree.from>=parent.firstChild.to))open.push(tagName)}return open}const identifier=/^[:\-\.\w\u00b7-\uffff]*$/;function completeTag(state,schema,tree,from,to){let end=/\s*>/.test(state.sliceDoc(to,to+5))?"":">";return{from:from,to:to,options:allowedChildren(state.doc,tree,schema).map(tagName=>({label:tagName,type:"type"})).concat(openTags(state.doc,tree).map((tag,i)=>({label:"/"+tag,apply:"/"+tag+end,type:"type",boost:99-i}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function completeCloseTag(state,tree,from,to){let end=/\s*>/.test(state.sliceDoc(to,to+5))?"":">";return{from:from,to:to,options:openTags(state.doc,tree).map((tag,i)=>({label:tag,apply:tag+end,type:"type",boost:99-i})),validFor:identifier}}function completeStartTag(state,schema,tree,pos){let options=[],level=0;for(let tagName of allowedChildren(state.doc,tree,schema))options.push({label:"<"+tagName,type:"type"});for(let open of openTags(state.doc,tree))options.push({label:""+open+">",type:"type",boost:99-level++});return{from:pos,to:pos,options:options,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function completeAttrName(state,schema,tree,from,to){let elt=findParentElement(tree),info=elt?schema.tags[elementName(state.doc,elt)]:null;let names=info&&info.attrs?Object.keys(info.attrs).concat(schema.globalAttrNames):schema.globalAttrNames;return{from:from,to:to,options:names.map(attrName=>({label:attrName,type:"property"})),validFor:identifier}}function completeAttrValue(state,schema,tree,from,to){var _a;let nameNode=(_a=tree.parent)===null||_a===void 0?void 0:_a.getChild("AttributeName");let options=[],token=undefined;if(nameNode){let attrName=state.sliceDoc(nameNode.from,nameNode.to);let attrs=schema.globalAttrs[attrName];if(!attrs){let elt=findParentElement(tree),info=elt?schema.tags[elementName(state.doc,elt)]:null;attrs=(info===null||info===void 0?void 0:info.attrs)&&info.attrs[attrName]}if(attrs){let base=state.sliceDoc(from,to).toLowerCase(),quoteStart='"',quoteEnd='"';if(/^['"]/.test(base)){token=base[0]=='"'?/^[^"]*$/:/^[^']*$/;quoteStart="";quoteEnd=state.sliceDoc(to,to+1)==base[0]?"":base[0];base=base.slice(1);from++}else{token=/^[^\s<>='"]*$/}for(let value of attrs)options.push({label:value,apply:quoteStart+value+quoteEnd,type:"constant"})}}return{from:from,to:to,options:options,validFor:token}}function htmlCompletionFor(schema,context){let{state,pos}=context,around=syntaxTree(state).resolveInner(pos),tree=around.resolve(pos,-1);for(let scan=pos,before;around==tree&&(before=tree.childBefore(scan));){let last=before.lastChild;if(!last||!last.type.isError||last.fromhtmlCompletionFor(schema,context)}const htmlLanguage=LRLanguage.define({name:"html",parser:parser.configure({props:[indentNodeProp.add({Element(context){let after=/^(\s*)(<\/)?/.exec(context.textAfter);if(context.node.to<=context.pos+after[0].length)return context.continue();return context.lineIndent(context.node.from)+(after[2]?0:context.unit)},"OpenTag CloseTag SelfClosingTag"(context){return context.column(context.node.from)+context.unit},Document(context){if(context.pos+/\s*/.exec(context.textAfter)[0].length{if(view.composing||view.state.readOnly||from!=to||text!=">"&&text!="/"||!htmlLanguage.isActiveAt(view.state,from,-1))return false;let{state}=view;let changes=state.changeByRange(range=>{var _a,_b,_c;let{head}=range,around=syntaxTree(state).resolveInner(head,-1),name;if(around.name=="TagName"||around.name=="StartTag")around=around.parent;if(text==">"&&around.name=="OpenTag"){if(((_b=(_a=around.parent)===null||_a===void 0?void 0:_a.lastChild)===null||_b===void 0?void 0:_b.name)!="CloseTag"&&(name=elementName(state.doc,around.parent,head))){let hasRightBracket=view.state.doc.sliceString(head,head+1)===">";let insert=`${hasRightBracket?"":">"}${name}>`;return{range:EditorSelection.cursor(head+1),changes:{from:head+(hasRightBracket?1:0),insert:insert}}}}else if(text=="/"&&around.name=="OpenTag"){let empty=around.parent,base=empty===null||empty===void 0?void 0:empty.parent;if(empty.from==head-1&&((_c=base.lastChild)===null||_c===void 0?void 0:_c.name)!="CloseTag"&&(name=elementName(state.doc,base,head))){let hasRightBracket=view.state.doc.sliceString(head,head+1)===">";let insert=`/${name}${hasRightBracket?"":">"}`;let pos=head+insert.length+(hasRightBracket?1:0);return{range:EditorSelection.cursor(pos),changes:{from:head,insert:insert}}}}return{range:range}});if(changes.changes.empty)return false;view.dispatch(changes,{userEvent:"input.type",scrollIntoView:true});return true});export{autoCloseTags,html,htmlCompletionSource,htmlCompletionSourceWith,htmlLanguage};
\ No newline at end of file
diff --git a/public/js/@codemirror/lang-javascript.js b/public/js/@codemirror/lang-javascript.js
new file mode 100755
index 0000000..34f627f
--- /dev/null
+++ b/public/js/@codemirror/lang-javascript.js
@@ -0,0 +1 @@
+import{parser}from"@lezer/javascript";import{syntaxTree,LRLanguage,indentNodeProp,continuedIndent,flatIndent,delimitedIndent,foldNodeProp,foldInside,LanguageSupport}from"@codemirror/language";import{EditorSelection}from"@codemirror/state";import{EditorView}from"@codemirror/view";import{snippetCompletion,ifNotIn,completeFromList}from"@codemirror/autocomplete";import{NodeWeakMap,IterMode}from"@lezer/common";const snippets=[snippetCompletion("function ${name}(${params}) {\n\t${}\n}",{label:"function",detail:"definition",type:"keyword"}),snippetCompletion("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n\t${}\n}",{label:"for",detail:"loop",type:"keyword"}),snippetCompletion("for (let ${name} of ${collection}) {\n\t${}\n}",{label:"for",detail:"of loop",type:"keyword"}),snippetCompletion("do {\n\t${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),snippetCompletion("while (${}) {\n\t${}\n}",{label:"while",detail:"loop",type:"keyword"}),snippetCompletion("try {\n\t${}\n} catch (${error}) {\n\t${}\n}",{label:"try",detail:"/ catch block",type:"keyword"}),snippetCompletion("if (${}) {\n\t${}\n}",{label:"if",detail:"block",type:"keyword"}),snippetCompletion("if (${}) {\n\t${}\n} else {\n\t${}\n}",{label:"if",detail:"/ else block",type:"keyword"}),snippetCompletion("class ${name} {\n\tconstructor(${params}) {\n\t\t${}\n\t}\n}",{label:"class",detail:"definition",type:"keyword"}),snippetCompletion('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),snippetCompletion('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})];const cache=new NodeWeakMap;const ScopeNodes=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function defID(type){return(node,def)=>{let id=node.node.getChild("VariableDefinition");if(id)def(id,type);return true}}const functionContext=["FunctionDeclaration"];const gatherCompletions={FunctionDeclaration:defID("function"),ClassDeclaration:defID("class"),ClassExpression:()=>true,EnumDeclaration:defID("constant"),TypeAliasDeclaration:defID("type"),NamespaceDeclaration:defID("namespace"),VariableDefinition(node,def){if(!node.matchContext(functionContext))def(node,"variable")},TypeDefinition(node,def){def(node,"type")},__proto__:null};function getScope(doc,node){let cached=cache.get(node);if(cached)return cached;let completions=[],top=true;function def(node,type){let name=doc.sliceString(node.from,node.to);completions.push({label:name,type:type})}node.cursor(IterMode.IncludeAnonymous).iterate(node=>{if(top){top=false}else if(node.name){let gather=gatherCompletions[node.name];if(gather&&gather(node,def)||ScopeNodes.has(node.name))return false}else if(node.to-node.from>8192){for(let c of getScope(doc,node.node))completions.push(c);return false}});cache.set(node,completions);return completions}const Identifier=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/;const dontComplete=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName"];function localCompletionSource(context){let inner=syntaxTree(context.state).resolveInner(context.pos,-1);if(dontComplete.indexOf(inner.name)>-1)return null;let isWord=inner.name=="VariableName"||inner.to-inner.from<20&&Identifier.test(context.state.sliceDoc(inner.from,inner.to));if(!isWord&&!context.explicit)return null;let options=[];for(let pos=inner;pos;pos=pos.parent){if(ScopeNodes.has(pos.name))options=options.concat(getScope(context.state.doc,pos))}return{options:options,from:isWord?inner.from:context.pos,validFor:Identifier}}function pathFor(read,member,name){var _a;let path=[];for(;;){let obj=member.firstChild,prop;if((obj===null||obj===void 0?void 0:obj.name)=="VariableName"){path.push(read(obj));return{path:path.reverse(),name:name}}else if((obj===null||obj===void 0?void 0:obj.name)=="MemberExpression"&&((_a=prop=obj.lastChild)===null||_a===void 0?void 0:_a.name)=="PropertyName"){path.push(read(prop));member=obj}else{return null}}}function completionPath(context){let read=node=>context.state.doc.sliceString(node.from,node.to);let inner=syntaxTree(context.state).resolveInner(context.pos,-1);if(inner.name=="PropertyName"){return pathFor(read,inner.parent,read(inner))}else if(dontComplete.indexOf(inner.name)>-1){return null}else if(inner.name=="VariableName"||inner.to-inner.from<20&&Identifier.test(read(inner))){return{path:[],name:read(inner)}}else if((inner.name=="."||inner.name=="?.")&&inner.parent.name=="MemberExpression"){return pathFor(read,inner.parent,"")}else if(inner.name=="MemberExpression"){return pathFor(read,inner,"")}else{return context.explicit?{path:[],name:""}:null}}function enumeratePropertyCompletions(obj,top){let options=[],seen=new Set;for(let depth=0;;depth++){for(let name of(Object.getOwnPropertyNames||Object.keys)(obj)){if(seen.has(name))continue;seen.add(name);let value;try{value=obj[name]}catch(_){continue}options.push({label:name,type:typeof value=="function"?/^[A-Z]/.test(name)?"class":top?"function":"method":top?"variable":"property",boost:-depth})}let next=Object.getPrototypeOf(obj);if(!next)return options;obj=next}}function scopeCompletionSource(scope){let cache=new Map;return context=>{let path=completionPath(context);if(!path)return null;let target=scope;for(let step of path.path){target=target[step];if(!target)return null}let options=cache.get(target);if(!options)cache.set(target,options=enumeratePropertyCompletions(target,!path.path.length));return{from:context.pos-path.name.length,options:options,validFor:Identifier}}}const javascriptLanguage=LRLanguage.define({name:"javascript",parser:parser.configure({props:[indentNodeProp.add({IfStatement:continuedIndent({except:/^\s*({|else\b)/}),TryStatement:continuedIndent({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:flatIndent,SwitchBody:context=>{let after=context.textAfter,closed=/^\s*\}/.test(after),isCase=/^\s*(case|default)\b/.test(after);return context.baseIndent+(closed?0:isCase?1:2)*context.unit},Block:delimitedIndent({closing:"}"}),ArrowFunction:cx=>cx.baseIndent+cx.unit,"TemplateString BlockComment":()=>null,"Statement Property":continuedIndent({except:/^{/}),JSXElement(context){let closed=/^\s*<\//.test(context.textAfter);return context.lineIndent(context.node.from)+(closed?0:context.unit)},JSXEscape(context){let closed=/\s*\}/.test(context.textAfter);return context.lineIndent(context.node.from)+(closed?0:context.unit)},"JSXOpenTag JSXSelfClosingTag"(context){return context.column(context.node.from)+context.unit}}),foldNodeProp.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression":foldInside,BlockComment(tree){return{from:tree.from+2,to:tree.to-2}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}});const typescriptLanguage=javascriptLanguage.configure({dialect:"ts"},"typescript");const jsxLanguage=javascriptLanguage.configure({dialect:"jsx"});const tsxLanguage=javascriptLanguage.configure({dialect:"jsx ts"},"typescript");const keywords="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(kw=>({label:kw,type:"keyword"}));function javascript(config={}){let lang=config.jsx?config.typescript?tsxLanguage:jsxLanguage:config.typescript?typescriptLanguage:javascriptLanguage;return new LanguageSupport(lang,[javascriptLanguage.data.of({autocomplete:ifNotIn(dontComplete,completeFromList(snippets.concat(keywords)))}),javascriptLanguage.data.of({autocomplete:localCompletionSource}),config.jsx?autoCloseTags:[]])}function elementName(doc,tree,max=doc.length){if(!tree)return"";let name=tree.getChild("JSXIdentifier");return name?doc.sliceString(name.from,Math.min(name.to,max)):""}const android=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent);const autoCloseTags=EditorView.inputHandler.of((view,from,to,text)=>{if((android?view.composing:view.compositionStarted)||view.state.readOnly||from!=to||text!=">"&&text!="/"||!javascriptLanguage.isActiveAt(view.state,from,-1))return false;let{state}=view;let changes=state.changeByRange(range=>{var _a,_b,_c;let{head}=range,around=syntaxTree(state).resolveInner(head,-1),name;if(around.name=="JSXStartTag")around=around.parent;if(text==">"&&around.name=="JSXFragmentTag"){return{range:EditorSelection.cursor(head+1),changes:{from:head,insert:`><>`}}}else if(text==">"&&around.name=="JSXIdentifier"){if(((_b=(_a=around.parent)===null||_a===void 0?void 0:_a.lastChild)===null||_b===void 0?void 0:_b.name)!="JSXEndTag"&&(name=elementName(state.doc,around.parent,head)))return{range:EditorSelection.cursor(head+1),changes:{from:head,insert:`>${name}>`}}}else if(text=="/"&&around.name=="JSXFragmentTag"){let empty=around.parent,base=empty===null||empty===void 0?void 0:empty.parent;if(empty.from==head-1&&((_c=base.lastChild)===null||_c===void 0?void 0:_c.name)!="JSXEndTag"&&(name=elementName(state.doc,base===null||base===void 0?void 0:base.firstChild,head))){let insert=`/${name}>`;return{range:EditorSelection.cursor(head+insert.length),changes:{from:head,insert:insert}}}}return{range:range}});if(changes.changes.empty)return false;view.dispatch(changes,{userEvent:"input.type",scrollIntoView:true});return true});function esLint(eslint,config){if(!config){config={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:true,node:true,es6:true,es2015:true,es2017:true,es2020:true},rules:{}};eslint.getRules().forEach((desc,name)=>{if(desc.meta.docs.recommended)config.rules[name]=2})}return view=>{let{state}=view,found=[];for(let{from,to}of javascriptLanguage.findRegions(state)){let fromLine=state.doc.lineAt(from),offset={line:fromLine.number-1,col:from-fromLine.from,pos:from};for(let d of eslint.verify(state.sliceDoc(from,to),config))found.push(translateDiagnostic(d,state.doc,offset))}return found}}function mapPos(line,col,doc,offset){return doc.line(line+offset.line).from+col+(line==1?offset.col-1:-1)}function translateDiagnostic(input,doc,offset){let start=mapPos(input.line,input.column,doc,offset);let result={from:start,to:input.endLine!=null&&input.endColumn!=1?mapPos(input.endLine,input.endColumn,doc,offset):start,message:input.message,source:input.ruleId?"eslint:"+input.ruleId:"eslint",severity:input.severity==1?"warning":"error"};if(input.fix){let{range,text}=input.fix,from=range[0]+offset.pos-start,to=range[1]+offset.pos-start;result.actions=[{name:"fix",apply(view,start){view.dispatch({changes:{from:start+from,to:start+to,insert:text},scrollIntoView:true})}}]}return result}export{autoCloseTags,completionPath,esLint,javascript,javascriptLanguage,jsxLanguage,localCompletionSource,scopeCompletionSource,snippets,tsxLanguage,typescriptLanguage};
\ No newline at end of file
diff --git a/public/js/@codemirror/lang-markdown.js b/public/js/@codemirror/lang-markdown.js
new file mode 100755
index 0000000..074bdf8
--- /dev/null
+++ b/public/js/@codemirror/lang-markdown.js
@@ -0,0 +1 @@
+import{EditorSelection,Prec}from"@codemirror/state";import{keymap}from"@codemirror/view";import{defineLanguageFacet,foldNodeProp,indentNodeProp,languageDataProp,Language,LanguageDescription,ParseContext,syntaxTree,LanguageSupport}from"@codemirror/language";import{parser,GFM,Subscript,Superscript,Emoji,MarkdownParser,parseCode}from"@lezer/markdown";import{html}from"@codemirror/lang-html";const data=defineLanguageFacet({block:{open:"\x3c!--",close:"--\x3e"}});const commonmark=parser.configure({props:[foldNodeProp.add(type=>{if(!type.is("Block")||type.is("Document"))return undefined;return(tree,state)=>({from:state.doc.lineAt(tree.from).to,to:tree.to})}),indentNodeProp.add({Document:()=>null}),languageDataProp.add({Document:data})]});function mkLang(parser){return new Language(data,parser,[],"markdown")}const commonmarkLanguage=mkLang(commonmark);const extended=commonmark.configure([GFM,Subscript,Superscript,Emoji]);const markdownLanguage=mkLang(extended);function getCodeParser(languages,defaultLanguage){return info=>{if(info&&languages){let found=null;info=/\S*/.exec(info)[0];if(typeof languages=="function")found=languages(info);else found=LanguageDescription.matchLanguageName(languages,info,true);if(found instanceof LanguageDescription)return found.support?found.support.language.parser:ParseContext.getSkippingParser(found.load());else if(found)return found.parser}return defaultLanguage?defaultLanguage.parser:null}}class Context{constructor(node,from,to,spaceBefore,spaceAfter,type,item){this.node=node;this.from=from;this.to=to;this.spaceBefore=spaceBefore;this.spaceAfter=spaceAfter;this.type=type;this.item=item}blank(maxWidth,trailing=true){let result=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(maxWidth!=null){while(result.length0;i--)result+=" ";return result+(trailing?this.spaceAfter:"")}}marker(doc,add){let number=this.node.name=="OrderedList"?String(+itemNumber(this.item,doc)[2]+add):"";return this.spaceBefore+number+this.type+this.spaceAfter}}function getContext(node,doc){let nodes=[];for(let cur=node;cur&&cur.name!="Document";cur=cur.parent){if(cur.name=="ListItem"||cur.name=="Blockquote"||cur.name=="FencedCode")nodes.push(cur)}let context=[];for(let i=nodes.length-1;i>=0;i--){let node=nodes[i],match;let line=doc.lineAt(node.from),startPos=node.from-line.from;if(node.name=="FencedCode"){context.push(new Context(node,startPos,startPos,"","","",null))}else if(node.name=="Blockquote"&&(match=/^[ \t]*>( ?)/.exec(line.text.slice(startPos)))){context.push(new Context(node,startPos,startPos+match[0].length,"",match[1],">",null))}else if(node.name=="ListItem"&&node.parent.name=="OrderedList"&&(match=/^([ \t]*)\d+([.)])([ \t]*)/.exec(line.text.slice(startPos)))){let after=match[3],len=match[0].length;if(after.length>=4){after=after.slice(0,after.length-4);len-=4}context.push(new Context(node.parent,startPos,startPos+len,match[1],after,match[2],node))}else if(node.name=="ListItem"&&node.parent.name=="BulletList"&&(match=/^([ \t]*)([-+*])([ \t]{1,4}\[[ xX]\])?([ \t]+)/.exec(line.text.slice(startPos)))){let after=match[4],len=match[0].length;if(after.length>4){after=after.slice(0,after.length-4);len-=4}let type=match[2];if(match[3])type+=match[3].replace(/[xX]/," ");context.push(new Context(node.parent,startPos,startPos+len,match[1],after,type,node))}}return context}function itemNumber(item,doc){return/^(\s*)(\d+)(?=[.)])/.exec(doc.sliceString(item.from,item.from+10))}function renumberList(after,doc,changes,offset=0){for(let prev=-1,node=after;;){if(node.name=="ListItem"){let m=itemNumber(node,doc);let number=+m[2];if(prev>=0){if(number!=prev+1)return;changes.push({from:node.from+m[1].length,to:node.from+m[0].length,insert:String(prev+2+offset)})}prev=number}let next=node.nextSibling;if(!next)break;node=next}}const insertNewlineContinueMarkup=({state,dispatch})=>{let tree=syntaxTree(state),{doc}=state;let dont=null,changes=state.changeByRange(range=>{if(!range.empty||!markdownLanguage.isActiveAt(state,range.from))return dont={range:range};let pos=range.from,line=doc.lineAt(pos);let context=getContext(tree.resolveInner(pos,-1),doc);while(context.length&&context[context.length-1].from>pos-line.from)context.pop();if(!context.length)return dont={range:range};let inner=context[context.length-1];if(inner.to-inner.spaceAfter.length>pos-line.from)return dont={range:range};let emptyLine=pos>=inner.to-inner.spaceAfter.length&&!/\S/.test(line.text.slice(inner.to));if(inner.item&&emptyLine){if(inner.node.firstChild.to>=pos||line.from>0&&!/[^\s>]/.test(doc.lineAt(line.from-1).text)){let next=context.length>1?context[context.length-2]:null;let delTo,insert="";if(next&&next.item){delTo=line.from+next.from;insert=next.marker(doc,1)}else{delTo=line.from+(next?next.to:0)}let changes=[{from:delTo,to:pos,insert:insert}];if(inner.node.name=="OrderedList")renumberList(inner.item,doc,changes,-2);if(next&&next.node.name=="OrderedList")renumberList(next.item,doc,changes);return{range:EditorSelection.cursor(delTo+insert.length),changes:changes}}else{let insert="";for(let i=0,pos=0,e=context.length-2;i<=e;i++){insert+=context[i].blank(i\s*$/.exec(prevLine.text);if(quoted&"ed.index==inner.from){let changes=state.changes([{from:prevLine.from+quoted.index,to:prevLine.to},{from:line.from+inner.from,to:line.to}]);return{range:range.map(changes),changes:changes}}}let changes=[];if(inner.node.name=="OrderedList")renumberList(inner.item,doc,changes);let insert=state.lineBreak;let continued=inner.item&&inner.item.from]*/.exec(line.text)[0].length>=inner.to){for(let i=0,pos=0,e=context.length-1;i<=e;i++){insert+=i==e&&!continued?context[i].marker(doc,1):context[i].blank(iline.from&&/\s/.test(line.text.charAt(from-line.from-1)))from--;changes.push({from:from,to:pos,insert:insert});return{range:EditorSelection.cursor(from+insert.length),changes:changes}});if(dont)return false;dispatch(state.update(changes,{scrollIntoView:true,userEvent:"input"}));return true};function isMark(node){return node.name=="QuoteMark"||node.name=="ListMark"}function contextNodeForDelete(tree,pos){let node=tree.resolveInner(pos,-1),scan=pos;if(isMark(node)){scan=node.from;node=node.parent}for(let prev;prev=node.childBefore(scan);){if(isMark(prev)){scan=prev.from}else if(prev.name=="OrderedList"||prev.name=="BulletList"){node=prev.lastChild;scan=node.to}else{break}}return node}const deleteMarkupBackward=({state,dispatch})=>{let tree=syntaxTree(state);let dont=null,changes=state.changeByRange(range=>{let pos=range.from,{doc}=state;if(range.empty&&markdownLanguage.isActiveAt(state,range.from)){let line=doc.lineAt(pos);let context=getContext(contextNodeForDelete(tree,pos),doc);if(context.length){let inner=context[context.length-1];let spaceEnd=inner.to-inner.spaceAfter.length+(inner.spaceAfter?1:0);if(pos-line.from>spaceEnd&&!/\S/.test(line.text.slice(spaceEnd,pos-line.from)))return{range:EditorSelection.cursor(line.from+spaceEnd),changes:{from:line.from+spaceEnd,to:pos}};if(pos-line.from==spaceEnd){let start=line.from+inner.from;if(inner.item&&inner.node.fromm.sql({dialect:m[dialectName]}))}const languages=[LanguageDescription.of({name:"C",extensions:["c","h","ino"],load(){return import("@codemirror/lang-cpp").then(m=>m.cpp())}}),LanguageDescription.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return import("@codemirror/lang-cpp").then(m=>m.cpp())}}),LanguageDescription.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return sql("Cassandra")}}),LanguageDescription.of({name:"CSS",extensions:["css"],load(){return import("@codemirror/lang-css").then(m=>m.css())}}),LanguageDescription.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return import("@codemirror/lang-html").then(m=>m.html())}}),LanguageDescription.of({name:"Java",extensions:["java"],load(){return import("@codemirror/lang-java").then(m=>m.java())}}),LanguageDescription.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return import("@codemirror/lang-javascript").then(m=>m.javascript())}}),LanguageDescription.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return import("@codemirror/lang-json").then(m=>m.json())}}),LanguageDescription.of({name:"JSX",extensions:["jsx"],load(){return import("@codemirror/lang-javascript").then(m=>m.javascript({jsx:true}))}}),LanguageDescription.of({name:"MariaDB SQL",load(){return sql("MariaSQL")}}),LanguageDescription.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return import("@codemirror/lang-markdown").then(m=>m.markdown())}}),LanguageDescription.of({name:"MS SQL",load(){return sql("MSSQL")}}),LanguageDescription.of({name:"MySQL",load(){return sql("MySQL")}}),LanguageDescription.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return import("@codemirror/lang-php").then(m=>m.php())}}),LanguageDescription.of({name:"PLSQL",extensions:["pls"],load(){return sql("PLSQL")}}),LanguageDescription.of({name:"PostgreSQL",load(){return sql("PostgreSQL")}}),LanguageDescription.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return import("@codemirror/lang-python").then(m=>m.python())}}),LanguageDescription.of({name:"Rust",extensions:["rs"],load(){return import("@codemirror/lang-rust").then(m=>m.rust())}}),LanguageDescription.of({name:"SQL",extensions:["sql"],load(){return sql("StandardSQL")}}),LanguageDescription.of({name:"SQLite",load(){return sql("SQLite")}}),LanguageDescription.of({name:"TSX",extensions:["tsx"],load(){return import("@codemirror/lang-javascript").then(m=>m.javascript({jsx:true,typescript:true}))}}),LanguageDescription.of({name:"TypeScript",alias:["ts"],extensions:["ts"],load(){return import("@codemirror/lang-javascript").then(m=>m.javascript({typescript:true}))}}),LanguageDescription.of({name:"WebAssembly",extensions:["wat","wast"],load(){return import("@codemirror/lang-wast").then(m=>m.wast())}}),LanguageDescription.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return import("@codemirror/lang-xml").then(m=>m.xml())}}),LanguageDescription.of({name:"APL",extensions:["dyalog","apl"],load(){return import("@codemirror/legacy-modes/mode/apl").then(m=>legacy(m.apl))}}),LanguageDescription.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return import("@codemirror/legacy-modes/mode/asciiarmor").then(m=>legacy(m.asciiArmor))}}),LanguageDescription.of({name:"ASN.1",extensions:["asn","asn1"],load(){return import("@codemirror/legacy-modes/mode/asn1").then(m=>legacy(m.asn1({})))}}),LanguageDescription.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return import("@codemirror/legacy-modes/mode/asterisk").then(m=>legacy(m.asterisk))}}),LanguageDescription.of({name:"Brainfuck",extensions:["b","bf"],load(){return import("@codemirror/legacy-modes/mode/brainfuck").then(m=>legacy(m.brainfuck))}}),LanguageDescription.of({name:"Cobol",extensions:["cob","cpy"],load(){return import("@codemirror/legacy-modes/mode/cobol").then(m=>legacy(m.cobol))}}),LanguageDescription.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return import("@codemirror/legacy-modes/mode/clike").then(m=>legacy(m.csharp))}}),LanguageDescription.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return import("@codemirror/legacy-modes/mode/clojure").then(m=>legacy(m.clojure))}}),LanguageDescription.of({name:"ClojureScript",extensions:["cljs"],load(){return import("@codemirror/legacy-modes/mode/clojure").then(m=>legacy(m.clojure))}}),LanguageDescription.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return import("@codemirror/legacy-modes/mode/css").then(m=>legacy(m.gss))}}),LanguageDescription.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return import("@codemirror/legacy-modes/mode/cmake").then(m=>legacy(m.cmake))}}),LanguageDescription.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return import("@codemirror/legacy-modes/mode/coffeescript").then(m=>legacy(m.coffeeScript))}}),LanguageDescription.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return import("@codemirror/legacy-modes/mode/commonlisp").then(m=>legacy(m.commonLisp))}}),LanguageDescription.of({name:"Cypher",extensions:["cyp","cypher"],load(){return import("@codemirror/legacy-modes/mode/cypher").then(m=>legacy(m.cypher))}}),LanguageDescription.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return import("@codemirror/legacy-modes/mode/python").then(m=>legacy(m.cython))}}),LanguageDescription.of({name:"Crystal",extensions:["cr"],load(){return import("@codemirror/legacy-modes/mode/crystal").then(m=>legacy(m.crystal))}}),LanguageDescription.of({name:"D",extensions:["d"],load(){return import("@codemirror/legacy-modes/mode/d").then(m=>legacy(m.d))}}),LanguageDescription.of({name:"Dart",extensions:["dart"],load(){return import("@codemirror/legacy-modes/mode/clike").then(m=>legacy(m.dart))}}),LanguageDescription.of({name:"diff",extensions:["diff","patch"],load(){return import("@codemirror/legacy-modes/mode/diff").then(m=>legacy(m.diff))}}),LanguageDescription.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return import("@codemirror/legacy-modes/mode/dockerfile").then(m=>legacy(m.dockerFile))}}),LanguageDescription.of({name:"DTD",extensions:["dtd"],load(){return import("@codemirror/legacy-modes/mode/dtd").then(m=>legacy(m.dtd))}}),LanguageDescription.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return import("@codemirror/legacy-modes/mode/dylan").then(m=>legacy(m.dylan))}}),LanguageDescription.of({name:"EBNF",load(){return import("@codemirror/legacy-modes/mode/ebnf").then(m=>legacy(m.ebnf))}}),LanguageDescription.of({name:"ECL",extensions:["ecl"],load(){return import("@codemirror/legacy-modes/mode/ecl").then(m=>legacy(m.ecl))}}),LanguageDescription.of({name:"edn",extensions:["edn"],load(){return import("@codemirror/legacy-modes/mode/clojure").then(m=>legacy(m.clojure))}}),LanguageDescription.of({name:"Eiffel",extensions:["e"],load(){return import("@codemirror/legacy-modes/mode/eiffel").then(m=>legacy(m.eiffel))}}),LanguageDescription.of({name:"Elm",extensions:["elm"],load(){return import("@codemirror/legacy-modes/mode/elm").then(m=>legacy(m.elm))}}),LanguageDescription.of({name:"Erlang",extensions:["erl"],load(){return import("@codemirror/legacy-modes/mode/erlang").then(m=>legacy(m.erlang))}}),LanguageDescription.of({name:"Esper",load(){return import("@codemirror/legacy-modes/mode/sql").then(m=>legacy(m.esper))}}),LanguageDescription.of({name:"Factor",extensions:["factor"],load(){return import("@codemirror/legacy-modes/mode/factor").then(m=>legacy(m.factor))}}),LanguageDescription.of({name:"FCL",load(){return import("@codemirror/legacy-modes/mode/fcl").then(m=>legacy(m.fcl))}}),LanguageDescription.of({name:"Forth",extensions:["forth","fth","4th"],load(){return import("@codemirror/legacy-modes/mode/forth").then(m=>legacy(m.forth))}}),LanguageDescription.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return import("@codemirror/legacy-modes/mode/fortran").then(m=>legacy(m.fortran))}}),LanguageDescription.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return import("@codemirror/legacy-modes/mode/mllike").then(m=>legacy(m.fSharp))}}),LanguageDescription.of({name:"Gas",extensions:["s"],load(){return import("@codemirror/legacy-modes/mode/gas").then(m=>legacy(m.gas))}}),LanguageDescription.of({name:"Gherkin",extensions:["feature"],load(){return import("@codemirror/legacy-modes/mode/gherkin").then(m=>legacy(m.gherkin))}}),LanguageDescription.of({name:"Go",extensions:["go"],load(){return import("@codemirror/legacy-modes/mode/go").then(m=>legacy(m.go))}}),LanguageDescription.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return import("@codemirror/legacy-modes/mode/groovy").then(m=>legacy(m.groovy))}}),LanguageDescription.of({name:"Haskell",extensions:["hs"],load(){return import("@codemirror/legacy-modes/mode/haskell").then(m=>legacy(m.haskell))}}),LanguageDescription.of({name:"Haxe",extensions:["hx"],load(){return import("@codemirror/legacy-modes/mode/haxe").then(m=>legacy(m.haxe))}}),LanguageDescription.of({name:"HXML",extensions:["hxml"],load(){return import("@codemirror/legacy-modes/mode/haxe").then(m=>legacy(m.hxml))}}),LanguageDescription.of({name:"HTTP",load(){return import("@codemirror/legacy-modes/mode/http").then(m=>legacy(m.http))}}),LanguageDescription.of({name:"IDL",extensions:["pro"],load(){return import("@codemirror/legacy-modes/mode/idl").then(m=>legacy(m.idl))}}),LanguageDescription.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return import("@codemirror/legacy-modes/mode/javascript").then(m=>legacy(m.jsonld))}}),LanguageDescription.of({name:"Jinja2",extensions:["j2","jinja","jinja2"],load(){return import("@codemirror/legacy-modes/mode/jinja2").then(m=>legacy(m.jinja2))}}),LanguageDescription.of({name:"Julia",extensions:["jl"],load(){return import("@codemirror/legacy-modes/mode/julia").then(m=>legacy(m.julia))}}),LanguageDescription.of({name:"Kotlin",extensions:["kt"],load(){return import("@codemirror/legacy-modes/mode/clike").then(m=>legacy(m.kotlin))}}),LanguageDescription.of({name:"LESS",extensions:["less"],load(){return import("@codemirror/legacy-modes/mode/css").then(m=>legacy(m.less))}}),LanguageDescription.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return import("@codemirror/legacy-modes/mode/livescript").then(m=>legacy(m.liveScript))}}),LanguageDescription.of({name:"Lua",extensions:["lua"],load(){return import("@codemirror/legacy-modes/mode/lua").then(m=>legacy(m.lua))}}),LanguageDescription.of({name:"mIRC",extensions:["mrc"],load(){return import("@codemirror/legacy-modes/mode/mirc").then(m=>legacy(m.mirc))}}),LanguageDescription.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return import("@codemirror/legacy-modes/mode/mathematica").then(m=>legacy(m.mathematica))}}),LanguageDescription.of({name:"Modelica",extensions:["mo"],load(){return import("@codemirror/legacy-modes/mode/modelica").then(m=>legacy(m.modelica))}}),LanguageDescription.of({name:"MUMPS",extensions:["mps"],load(){return import("@codemirror/legacy-modes/mode/mumps").then(m=>legacy(m.mumps))}}),LanguageDescription.of({name:"Mbox",extensions:["mbox"],load(){return import("@codemirror/legacy-modes/mode/mbox").then(m=>legacy(m.mbox))}}),LanguageDescription.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return import("@codemirror/legacy-modes/mode/nginx").then(m=>legacy(m.nginx))}}),LanguageDescription.of({name:"NSIS",extensions:["nsh","nsi"],load(){return import("@codemirror/legacy-modes/mode/nsis").then(m=>legacy(m.nsis))}}),LanguageDescription.of({name:"NTriples",extensions:["nt","nq"],load(){return import("@codemirror/legacy-modes/mode/ntriples").then(m=>legacy(m.ntriples))}}),LanguageDescription.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return import("@codemirror/legacy-modes/mode/clike").then(m=>legacy(m.objectiveC))}}),LanguageDescription.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return import("@codemirror/legacy-modes/mode/clike").then(m=>legacy(m.objectiveCpp))}}),LanguageDescription.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return import("@codemirror/legacy-modes/mode/mllike").then(m=>legacy(m.oCaml))}}),LanguageDescription.of({name:"Octave",extensions:["m"],load(){return import("@codemirror/legacy-modes/mode/octave").then(m=>legacy(m.octave))}}),LanguageDescription.of({name:"Oz",extensions:["oz"],load(){return import("@codemirror/legacy-modes/mode/oz").then(m=>legacy(m.oz))}}),LanguageDescription.of({name:"Pascal",extensions:["p","pas"],load(){return import("@codemirror/legacy-modes/mode/pascal").then(m=>legacy(m.pascal))}}),LanguageDescription.of({name:"Perl",extensions:["pl","pm"],load(){return import("@codemirror/legacy-modes/mode/perl").then(m=>legacy(m.perl))}}),LanguageDescription.of({name:"Pig",extensions:["pig"],load(){return import("@codemirror/legacy-modes/mode/pig").then(m=>legacy(m.pig))}}),LanguageDescription.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return import("@codemirror/legacy-modes/mode/powershell").then(m=>legacy(m.powerShell))}}),LanguageDescription.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return import("@codemirror/legacy-modes/mode/properties").then(m=>legacy(m.properties))}}),LanguageDescription.of({name:"ProtoBuf",extensions:["proto"],load(){return import("@codemirror/legacy-modes/mode/protobuf").then(m=>legacy(m.protobuf))}}),LanguageDescription.of({name:"Puppet",extensions:["pp"],load(){return import("@codemirror/legacy-modes/mode/puppet").then(m=>legacy(m.puppet))}}),LanguageDescription.of({name:"Q",extensions:["q"],load(){return import("@codemirror/legacy-modes/mode/q").then(m=>legacy(m.q))}}),LanguageDescription.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return import("@codemirror/legacy-modes/mode/r").then(m=>legacy(m.r))}}),LanguageDescription.of({name:"RPM Changes",load(){return import("@codemirror/legacy-modes/mode/rpm").then(m=>legacy(m.rpmChanges))}}),LanguageDescription.of({name:"RPM Spec",extensions:["spec"],load(){return import("@codemirror/legacy-modes/mode/rpm").then(m=>legacy(m.rpmSpec))}}),LanguageDescription.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],load(){return import("@codemirror/legacy-modes/mode/ruby").then(m=>legacy(m.ruby))}}),LanguageDescription.of({name:"SAS",extensions:["sas"],load(){return import("@codemirror/legacy-modes/mode/sas").then(m=>legacy(m.sas))}}),LanguageDescription.of({name:"Sass",extensions:["sass"],load(){return import("@codemirror/legacy-modes/mode/sass").then(m=>legacy(m.sass))}}),LanguageDescription.of({name:"Scala",extensions:["scala"],load(){return import("@codemirror/legacy-modes/mode/clike").then(m=>legacy(m.scala))}}),LanguageDescription.of({name:"Scheme",extensions:["scm","ss"],load(){return import("@codemirror/legacy-modes/mode/scheme").then(m=>legacy(m.scheme))}}),LanguageDescription.of({name:"SCSS",extensions:["scss"],load(){return import("@codemirror/legacy-modes/mode/css").then(m=>legacy(m.sCSS))}}),LanguageDescription.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return import("@codemirror/legacy-modes/mode/shell").then(m=>legacy(m.shell))}}),LanguageDescription.of({name:"Sieve",extensions:["siv","sieve"],load(){return import("@codemirror/legacy-modes/mode/sieve").then(m=>legacy(m.sieve))}}),LanguageDescription.of({name:"Smalltalk",extensions:["st"],load(){return import("@codemirror/legacy-modes/mode/smalltalk").then(m=>legacy(m.smalltalk))}}),LanguageDescription.of({name:"Solr",load(){return import("@codemirror/legacy-modes/mode/solr").then(m=>legacy(m.solr))}}),LanguageDescription.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return import("@codemirror/legacy-modes/mode/mllike").then(m=>legacy(m.sml))}}),LanguageDescription.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return import("@codemirror/legacy-modes/mode/sparql").then(m=>legacy(m.sparql))}}),LanguageDescription.of({name:"Spreadsheet",alias:["excel","formula"],load(){return import("@codemirror/legacy-modes/mode/spreadsheet").then(m=>legacy(m.spreadsheet))}}),LanguageDescription.of({name:"Squirrel",extensions:["nut"],load(){return import("@codemirror/legacy-modes/mode/clike").then(m=>legacy(m.squirrel))}}),LanguageDescription.of({name:"Stylus",extensions:["styl"],load(){return import("@codemirror/legacy-modes/mode/stylus").then(m=>legacy(m.stylus))}}),LanguageDescription.of({name:"Swift",extensions:["swift"],load(){return import("@codemirror/legacy-modes/mode/swift").then(m=>legacy(m.swift))}}),LanguageDescription.of({name:"sTeX",load(){return import("@codemirror/legacy-modes/mode/stex").then(m=>legacy(m.stex))}}),LanguageDescription.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return import("@codemirror/legacy-modes/mode/stex").then(m=>legacy(m.stex))}}),LanguageDescription.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return import("@codemirror/legacy-modes/mode/verilog").then(m=>legacy(m.verilog))}}),LanguageDescription.of({name:"Tcl",extensions:["tcl"],load(){return import("@codemirror/legacy-modes/mode/tcl").then(m=>legacy(m.tcl))}}),LanguageDescription.of({name:"Textile",extensions:["textile"],load(){return import("@codemirror/legacy-modes/mode/textile").then(m=>legacy(m.textile))}}),LanguageDescription.of({name:"TiddlyWiki",load(){return import("@codemirror/legacy-modes/mode/tiddlywiki").then(m=>legacy(m.tiddlyWiki))}}),LanguageDescription.of({name:"Tiki wiki",load(){return import("@codemirror/legacy-modes/mode/tiki").then(m=>legacy(m.tiki))}}),LanguageDescription.of({name:"TOML",extensions:["toml"],load(){return import("@codemirror/legacy-modes/mode/toml").then(m=>legacy(m.toml))}}),LanguageDescription.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return import("@codemirror/legacy-modes/mode/troff").then(m=>legacy(m.troff))}}),LanguageDescription.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return import("@codemirror/legacy-modes/mode/ttcn").then(m=>legacy(m.ttcn))}}),LanguageDescription.of({name:"TTCN_CFG",extensions:["cfg"],load(){return import("@codemirror/legacy-modes/mode/ttcn-cfg").then(m=>legacy(m.ttcnCfg))}}),LanguageDescription.of({name:"Turtle",extensions:["ttl"],load(){return import("@codemirror/legacy-modes/mode/turtle").then(m=>legacy(m.turtle))}}),LanguageDescription.of({name:"Web IDL",extensions:["webidl"],load(){return import("@codemirror/legacy-modes/mode/webidl").then(m=>legacy(m.webIDL))}}),LanguageDescription.of({name:"VB.NET",extensions:["vb"],load(){return import("@codemirror/legacy-modes/mode/vb").then(m=>legacy(m.vb))}}),LanguageDescription.of({name:"VBScript",extensions:["vbs"],load(){return import("@codemirror/legacy-modes/mode/vbscript").then(m=>legacy(m.vbScript))}}),LanguageDescription.of({name:"Velocity",extensions:["vtl"],load(){return import("@codemirror/legacy-modes/mode/velocity").then(m=>legacy(m.velocity))}}),LanguageDescription.of({name:"Verilog",extensions:["v"],load(){return import("@codemirror/legacy-modes/mode/verilog").then(m=>legacy(m.verilog))}}),LanguageDescription.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return import("@codemirror/legacy-modes/mode/vhdl").then(m=>legacy(m.vhdl))}}),LanguageDescription.of({name:"XQuery",extensions:["xy","xquery"],load(){return import("@codemirror/legacy-modes/mode/xquery").then(m=>legacy(m.xQuery))}}),LanguageDescription.of({name:"Yacas",extensions:["ys"],load(){return import("@codemirror/legacy-modes/mode/yacas").then(m=>legacy(m.yacas))}}),LanguageDescription.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return import("@codemirror/legacy-modes/mode/yaml").then(m=>legacy(m.yaml))}}),LanguageDescription.of({name:"Z80",extensions:["z80"],load(){return import("@codemirror/legacy-modes/mode/z80").then(m=>legacy(m.z80))}}),LanguageDescription.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return import("@codemirror/legacy-modes/mode/mscgen").then(m=>legacy(m.mscgen))}}),LanguageDescription.of({name:"Xù",extensions:["xu"],load(){return import("@codemirror/legacy-modes/mode/mscgen").then(m=>legacy(m.xu))}}),LanguageDescription.of({name:"MsGenny",extensions:["msgenny"],load(){return import("@codemirror/legacy-modes/mode/mscgen").then(m=>legacy(m.msgenny))}})];export{languages};
\ No newline at end of file
diff --git a/public/js/@codemirror/language.js b/public/js/@codemirror/language.js
new file mode 100755
index 0000000..cbc09ca
--- /dev/null
+++ b/public/js/@codemirror/language.js
@@ -0,0 +1 @@
+import{NodeProp,Tree,IterMode,TreeFragment,Parser,NodeType,NodeSet}from"@lezer/common";import{StateEffect,StateField,Facet,EditorState,countColumn,combineConfig,RangeSet,RangeSetBuilder,Prec}from"@codemirror/state";import{ViewPlugin,logException,EditorView,Decoration,WidgetType,gutter,GutterMarker}from"@codemirror/view";import{tags,tagHighlighter,highlightTree,styleTags}from"@lezer/highlight";import{StyleModule}from"style-mod";var _a;const languageDataProp=new NodeProp;function defineLanguageFacet(baseData){return Facet.define({combine:baseData?values=>values.concat(baseData):undefined})}class Language{constructor(data,parser,extraExtensions=[],name=""){this.data=data;this.name=name;if(!EditorState.prototype.hasOwnProperty("tree"))Object.defineProperty(EditorState.prototype,"tree",{get(){return syntaxTree(this)}});this.parser=parser;this.extension=[language.of(this),EditorState.languageData.of((state,pos,side)=>state.facet(languageDataFacetAt(state,pos,side)))].concat(extraExtensions)}isActiveAt(state,pos,side=-1){return languageDataFacetAt(state,pos,side)==this.data}findRegions(state){let lang=state.facet(language);if((lang===null||lang===void 0?void 0:lang.data)==this.data)return[{from:0,to:state.doc.length}];if(!lang||!lang.allowsNesting)return[];let result=[];let explore=(tree,from)=>{if(tree.prop(languageDataProp)==this.data){result.push({from:from,to:from+tree.length});return}let mount=tree.prop(NodeProp.mounted);if(mount){if(mount.tree.prop(languageDataProp)==this.data){if(mount.overlay)for(let r of mount.overlay)result.push({from:r.from+from,to:r.to+from});else result.push({from:from,to:from+tree.length});return}else if(mount.overlay){let size=result.length;explore(mount.tree,mount.overlay[0].from+from);if(result.length>size)return}}for(let i=0;itype.isTop?data:undefined)]}),spec.name)}configure(options,name){return new LRLanguage(this.data,this.parser.configure(options),name||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function syntaxTree(state){let field=state.field(Language.state,false);return field?field.tree:Tree.empty}function ensureSyntaxTree(state,upto,timeout=50){var _a;let parse=(_a=state.field(Language.state,false))===null||_a===void 0?void 0:_a.context;return!parse?null:parse.isDone(upto)||parse.work(timeout,upto)?parse.tree:null}function syntaxTreeAvailable(state,upto=state.doc.length){var _a;return((_a=state.field(Language.state,false))===null||_a===void 0?void 0:_a.context.isDone(upto))||false}function forceParsing(view,upto=view.viewport.to,timeout=100){let success=ensureSyntaxTree(view.state,upto,timeout);if(success!=syntaxTree(view.state))view.dispatch({});return!!success}function syntaxParserRunning(view){var _a;return((_a=view.plugin(parseWorker))===null||_a===void 0?void 0:_a.isWorking())||false}class DocInput{constructor(doc,length=doc.length){this.doc=doc;this.length=length;this.cursorPos=0;this.string="";this.cursor=doc.iter()}syncTo(pos){this.string=this.cursor.next(pos-this.cursorPos).value;this.cursorPos=pos+this.string.length;return this.cursorPos-this.string.length}chunk(pos){this.syncTo(pos);return this.string}get lineChunks(){return true}read(from,to){let stringStart=this.cursorPos-this.string.length;if(from=this.cursorPos)return this.doc.sliceString(from,to);else return this.string.slice(from-stringStart,to-stringStart)}}let currentContext=null;class ParseContext{constructor(parser,state,fragments=[],tree,treeLen,viewport,skipped,scheduleOn){this.parser=parser;this.state=state;this.fragments=fragments;this.tree=tree;this.treeLen=treeLen;this.viewport=viewport;this.skipped=skipped;this.scheduleOn=scheduleOn;this.parse=null;this.tempSkipped=[]}static create(parser,state,viewport){return new ParseContext(parser,state,[],Tree.empty,0,viewport,[],null)}startParse(){return this.parser.startParse(new DocInput(this.state.doc),this.fragments)}work(until,upto){if(upto!=null&&upto>=this.state.doc.length)upto=undefined;if(this.tree!=Tree.empty&&this.isDone(upto!==null&&upto!==void 0?upto:this.state.doc.length)){this.takeTree();return true}return this.withContext(()=>{var _a;if(typeof until=="number"){let endTime=Date.now()+until;until=()=>Date.now()>endTime}if(!this.parse)this.parse=this.startParse();if(upto!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>upto)&&upto=this.treeLen){if(this.parse.stoppedAt==null||this.parse.stoppedAt>pos)this.parse.stopAt(pos);this.withContext(()=>{while(!(tree=this.parse.advance())){}});this.treeLen=pos;this.tree=tree;this.fragments=this.withoutTempSkipped(TreeFragment.addTree(this.tree,this.fragments,true));this.parse=null}}withContext(f){let prev=currentContext;currentContext=this;try{return f()}finally{currentContext=prev}}withoutTempSkipped(fragments){for(let r;r=this.tempSkipped.pop();)fragments=cutFragments(fragments,r.from,r.to);return fragments}changes(changes,newState){let{fragments,tree,treeLen,viewport,skipped}=this;this.takeTree();if(!changes.empty){let ranges=[];changes.iterChangedRanges((fromA,toA,fromB,toB)=>ranges.push({fromA:fromA,toA:toA,fromB:fromB,toB:toB}));fragments=TreeFragment.applyChanges(fragments,ranges);tree=Tree.empty;treeLen=0;viewport={from:changes.mapPos(viewport.from,-1),to:changes.mapPos(viewport.to,1)};if(this.skipped.length){skipped=[];for(let r of this.skipped){let from=changes.mapPos(r.from,1),to=changes.mapPos(r.to,-1);if(fromviewport.from){this.fragments=cutFragments(this.fragments,from,to);this.skipped.splice(i--,1)}}if(this.skipped.length>=startLen)return false;this.reset();return true}reset(){if(this.parse){this.takeTree();this.parse=null}}skipUntilInView(from,to){this.skipped.push({from:from,to:to})}static getSkippingParser(until){return new class extends Parser{createParse(input,fragments,ranges){let from=ranges[0].from,to=ranges[ranges.length-1].to;let parser={parsedPos:from,advance(){let cx=currentContext;if(cx){for(let r of ranges)cx.tempSkipped.push(r);if(until)cx.scheduleOn=cx.scheduleOn?Promise.all([cx.scheduleOn,until]):until}this.parsedPos=to;return new Tree(NodeType.none,[],[],to-from)},stoppedAt:null,stopAt(){}};return parser}}}isDone(upto){upto=Math.min(upto,this.state.doc.length);let frags=this.fragments;return this.treeLen>=upto&&frags.length&&frags[0].from==0&&frags[0].to>=upto}static get(){return currentContext}}function cutFragments(fragments,from,to){return TreeFragment.applyChanges(fragments,[{fromA:from,toA:to,fromB:from,toB:to}])}class LanguageState{constructor(context){this.context=context;this.tree=context.tree}apply(tr){if(!tr.docChanged&&this.tree==this.context.tree)return this;let newCx=this.context.changes(tr.changes,tr.state);let upto=this.context.treeLen==tr.startState.doc.length?undefined:Math.max(tr.changes.mapPos(this.context.treeLen),newCx.viewport.to);if(!newCx.work(20,upto))newCx.takeTree();return new LanguageState(newCx)}static init(state){let vpTo=Math.min(3e3,state.doc.length);let parseState=ParseContext.create(state.facet(language).parser,state,{from:0,to:vpTo});if(!parseState.work(20,vpTo))parseState.takeTree();return new LanguageState(parseState)}}Language.state=StateField.define({create:LanguageState.init,update(value,tr){for(let e of tr.effects)if(e.is(Language.setState))return e.value;if(tr.startState.facet(language)!=tr.state.facet(language))return LanguageState.init(tr.state);return value.apply(tr)}});let requestIdle=callback=>{let timeout=setTimeout(()=>callback(),500);return()=>clearTimeout(timeout)};if(typeof requestIdleCallback!="undefined")requestIdle=callback=>{let idle=-1,timeout=setTimeout(()=>{idle=requestIdleCallback(callback,{timeout:500-100})},100);return()=>idle<0?clearTimeout(timeout):cancelIdleCallback(idle)};const isInputPending=typeof navigator!="undefined"&&((_a=navigator.scheduling)===null||_a===void 0?void 0:_a.isInputPending)?()=>navigator.scheduling.isInputPending():null;const parseWorker=ViewPlugin.fromClass(class ParseWorker{constructor(view){this.view=view;this.working=null;this.workScheduled=0;this.chunkEnd=-1;this.chunkBudget=-1;this.work=this.work.bind(this);this.scheduleWork()}update(update){let cx=this.view.state.field(Language.state).context;if(cx.updateViewport(update.view.viewport)||this.view.viewport.to>cx.treeLen)this.scheduleWork();if(update.docChanged){if(this.view.hasFocus)this.chunkBudget+=50;this.scheduleWork()}this.checkAsyncSchedule(cx)}scheduleWork(){if(this.working)return;let{state}=this.view,field=state.field(Language.state);if(field.tree!=field.context.tree||!field.context.isDone(state.doc.length))this.working=requestIdle(this.work)}work(deadline){this.working=null;let now=Date.now();if(this.chunkEndvpTo+1e3;let done=field.context.work(()=>{return isInputPending&&isInputPending()||Date.now()>endTime},vpTo+(viewportFirst?0:1e5));this.chunkBudget-=Date.now()-now;if(done||this.chunkBudget<=0){field.context.takeTree();this.view.dispatch({effects:Language.setState.of(new LanguageState(field.context))})}if(this.chunkBudget>0&&!(done&&!viewportFirst))this.scheduleWork();this.checkAsyncSchedule(field.context)}checkAsyncSchedule(cx){if(cx.scheduleOn){this.workScheduled++;cx.scheduleOn.then(()=>this.scheduleWork()).catch(err=>logException(this.view.state,err)).then(()=>this.workScheduled--);cx.scheduleOn=null}}destroy(){if(this.working)this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}});const language=Facet.define({combine(languages){return languages.length?languages[0]:null},enables:language=>[Language.state,parseWorker,EditorView.contentAttributes.compute([language],state=>{let lang=state.facet(language);return lang&&lang.name?{"data-language":lang.name}:{}})]});class LanguageSupport{constructor(language,support=[]){this.language=language;this.support=support;this.extension=[language,support]}}class LanguageDescription{constructor(name,alias,extensions,filename,loadFunc,support=undefined){this.name=name;this.alias=alias;this.extensions=extensions;this.filename=filename;this.loadFunc=loadFunc;this.support=support;this.loading=null}load(){return this.loading||(this.loading=this.loadFunc().then(support=>this.support=support,err=>{this.loading=null;throw err}))}static of(spec){let{load,support}=spec;if(!load){if(!support)throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");load=()=>Promise.resolve(support)}return new LanguageDescription(spec.name,(spec.alias||[]).concat(spec.name).map(s=>s.toLowerCase()),spec.extensions||[],spec.filename,load,support)}static matchFilename(descs,filename){for(let d of descs)if(d.filename&&d.filename.test(filename))return d;let ext=/\.([^.]+)$/.exec(filename);if(ext)for(let d of descs)if(d.extensions.indexOf(ext[1])>-1)return d;return null}static matchLanguageName(descs,name,fuzzy=true){name=name.toLowerCase();for(let d of descs)if(d.alias.some(a=>a==name))return d;if(fuzzy)for(let d of descs)for(let a of d.alias){let found=name.indexOf(a);if(found>-1&&(a.length>2||!/\w/.test(name[found-1])&&!/\w/.test(name[found+a.length])))return d}return null}}const indentService=Facet.define();const indentUnit=Facet.define({combine:values=>{if(!values.length)return" ";if(!/^(?: +|\t+)$/.test(values[0]))throw new Error("Invalid indent unit: "+JSON.stringify(values[0]));return values[0]}});function getIndentUnit(state){let unit=state.facet(indentUnit);return unit.charCodeAt(0)==9?state.tabSize*unit.length:unit.length}function indentString(state,cols){let result="",ts=state.tabSize;if(state.facet(indentUnit).charCodeAt(0)==9)while(cols>=ts){result+="\t";cols-=ts}for(let i=0;i{var _a;return(_a=updated[start])!==null&&_a!==void 0?_a:-1}});let changes=[];for(let pos=from;pos<=to;){let line=state.doc.lineAt(pos);pos=line.to+1;let indent=getIndentation(context,line.from);if(indent==null)continue;if(!/\S/.test(line.text))indent=0;let cur=/^\s*/.exec(line.text)[0];let norm=indentString(state,indent);if(cur!=norm){updated[line.from]=indent;changes.push({from:line.from,to:line.from+cur.length,insert:norm})}}return state.changes(changes)}class IndentContext{constructor(state,options={}){this.state=state;this.options=options;this.unit=getIndentUnit(state)}lineAt(pos,bias=1){let line=this.state.doc.lineAt(pos);let{simulateBreak,simulateDoubleBreak}=this.options;if(simulateBreak!=null&&simulateBreak>=line.from&&simulateBreak<=line.to){if(simulateDoubleBreak&&simulateBreak==pos)return{text:"",from:pos};else if(bias<0?simulateBreak-1)result+=override-this.countColumn(text,text.search(/\S|$/));return result}countColumn(line,pos=line.length){return countColumn(line,this.state.tabSize,pos)}lineIndent(pos,bias=1){let{text,from}=this.lineAt(pos,bias);let override=this.options.overrideIndentation;if(override){let overriden=override(from);if(overriden>-1)return overriden}return this.countColumn(text,text.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const indentNodeProp=new NodeProp;function syntaxIndentation(cx,ast,pos){return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos),pos,cx)}function ignoreClosed(cx){return cx.pos==cx.options.simulateBreak&&cx.options.simulateDoubleBreak}function indentStrategy(tree){let strategy=tree.type.prop(indentNodeProp);if(strategy)return strategy;let first=tree.firstChild,close;if(first&&(close=first.type.prop(NodeProp.closedBy))){let last=tree.lastChild,closed=last&&close.indexOf(last.name)>-1;return cx=>delimitedStrategy(cx,true,1,undefined,closed&&!ignoreClosed(cx)?last.from:undefined)}return tree.parent==null?topIndent:null}function indentFrom(node,pos,base){for(;node;node=node.parent){let strategy=indentStrategy(node);if(strategy)return strategy(TreeIndentContext.create(base,pos,node))}return null}function topIndent(){return 0}class TreeIndentContext extends IndentContext{constructor(base,pos,node){super(base.state,base.options);this.base=base;this.pos=pos;this.node=node}static create(base,pos,node){return new TreeIndentContext(base,pos,node)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){let line=this.state.doc.lineAt(this.node.from);for(;;){let atBreak=this.node.resolve(line.from);while(atBreak.parent&&atBreak.parent.from==atBreak.from)atBreak=atBreak.parent;if(isParent(atBreak,this.node))break;line=this.state.doc.lineAt(atBreak.from)}return this.lineIndent(line.from)}continue(){let parent=this.node.parent;return parent?indentFrom(parent,this.pos,this.base):0}}function isParent(parent,of){for(let cur=of;cur;cur=cur.parent)if(parent==cur)return true;return false}function bracketedAligned(context){let tree=context.node;let openToken=tree.childAfter(tree.from),last=tree.lastChild;if(!openToken)return null;let sim=context.options.simulateBreak;let openLine=context.state.doc.lineAt(openToken.from);let lineEnd=sim==null||sim<=openLine.from?openLine.to:Math.min(openLine.to,sim);for(let pos=openToken.to;;){let next=tree.childAfter(pos);if(!next||next==last)return null;if(!next.type.isSkipped)return next.fromdelimitedStrategy(context,align,units,closing)}function delimitedStrategy(context,align,units,closing,closedAt){let after=context.textAfter,space=after.match(/^\s*/)[0].length;let closed=closing&&after.slice(space,space+closing.length)==closing||closedAt==context.pos+space;let aligned=align?bracketedAligned(context):null;if(aligned)return closed?context.column(aligned.from):context.column(aligned.to);return context.baseIndent+(closed?0:context.unit*units)}const flatIndent=context=>context.baseIndent;function continuedIndent({except,units=1}={}){return context=>{let matchExcept=except&&except.test(context.textAfter);return context.baseIndent+(matchExcept?0:units*context.unit)}}const DontIndentBeyond=200;function indentOnInput(){return EditorState.transactionFilter.of(tr=>{if(!tr.docChanged||!tr.isUserEvent("input.type")&&!tr.isUserEvent("input.complete"))return tr;let rules=tr.startState.languageDataAt("indentOnInput",tr.startState.selection.main.head);if(!rules.length)return tr;let doc=tr.newDoc,{head}=tr.newSelection.main,line=doc.lineAt(head);if(head>line.from+DontIndentBeyond)return tr;let lineStart=doc.sliceString(line.from,head);if(!rules.some(r=>r.test(lineStart)))return tr;let{state}=tr,last=-1,changes=[];for(let{head}of state.selection.ranges){let line=state.doc.lineAt(head);if(line.from==last)continue;last=line.from;let indent=getIndentation(state,line.from);if(indent==null)continue;let cur=/^\s*/.exec(line.text)[0];let norm=indentString(state,indent);if(cur!=norm)changes.push({from:line.from,to:line.from+cur.length,insert:norm})}return changes.length?[tr,{changes:changes,sequential:true}]:tr})}const foldService=Facet.define();const foldNodeProp=new NodeProp;function foldInside(node){let first=node.firstChild,last=node.lastChild;return first&&first.toend)continue;if(found&&cur.from=start&&value.to>end)found=value}}return found}function isUnfinished(node){let ch=node.lastChild;return ch&&ch.to==node.to&&ch.type.isError}function foldable(state,lineStart,lineEnd){for(let service of state.facet(foldService)){let result=service(state,lineStart,lineEnd);if(result)return result}return syntaxFolding(state,lineStart,lineEnd)}function mapRange(range,mapping){let from=mapping.mapPos(range.from,1),to=mapping.mapPos(range.to,-1);return from>=to?undefined:{from:from,to:to}}const foldEffect=StateEffect.define({map:mapRange});const unfoldEffect=StateEffect.define({map:mapRange});function selectedLines(view){let lines=[];for(let{head}of view.state.selection.ranges){if(lines.some(l=>l.from<=head&&l.to>=head))continue;lines.push(view.lineBlockAt(head))}return lines}const foldState=StateField.define({create(){return Decoration.none},update(folded,tr){folded=folded.map(tr.changes);for(let e of tr.effects){if(e.is(foldEffect)&&!foldExists(folded,e.value.from,e.value.to))folded=folded.update({add:[foldWidget.range(e.value.from,e.value.to)]});else if(e.is(unfoldEffect))folded=folded.update({filter:(from,to)=>e.value.from!=from||e.value.to!=to,filterFrom:e.value.from,filterTo:e.value.to})}if(tr.selection){let onSelection=false,{head}=tr.selection.main;folded.between(head,head,(a,b)=>{if(ahead)onSelection=true});if(onSelection)folded=folded.update({filterFrom:head,filterTo:head,filter:(a,b)=>b<=head||a>=head})}return folded},provide:f=>EditorView.decorations.from(f),toJSON(folded,state){let ranges=[];folded.between(0,state.doc.length,(from,to)=>{ranges.push(from,to)});return ranges},fromJSON(value){if(!Array.isArray(value)||value.length%2)throw new RangeError("Invalid JSON for fold state");let ranges=[];for(let i=0;i{if(!found||found.from>from)found={from:from,to:to}});return found}function foldExists(folded,from,to){let found=false;folded.between(from,from,(a,b)=>{if(a==from&&b==to)found=true});return found}function maybeEnable(state,other){return state.field(foldState,false)?other:other.concat(StateEffect.appendConfig.of(codeFolding()))}const foldCode=view=>{for(let line of selectedLines(view)){let range=foldable(view.state,line.from,line.to);if(range){view.dispatch({effects:maybeEnable(view.state,[foldEffect.of(range),announceFold(view,range)])});return true}}return false};const unfoldCode=view=>{if(!view.state.field(foldState,false))return false;let effects=[];for(let line of selectedLines(view)){let folded=findFold(view.state,line.from,line.to);if(folded)effects.push(unfoldEffect.of(folded),announceFold(view,folded,false))}if(effects.length)view.dispatch({effects:effects});return effects.length>0};function announceFold(view,range,fold=true){let lineFrom=view.state.doc.lineAt(range.from).number,lineTo=view.state.doc.lineAt(range.to).number;return EditorView.announce.of(`${view.state.phrase(fold?"Folded lines":"Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`)}const foldAll=view=>{let{state}=view,effects=[];for(let pos=0;pos{let field=view.state.field(foldState,false);if(!field||!field.size)return false;let effects=[];field.between(0,view.state.doc.length,(from,to)=>{effects.push(unfoldEffect.of({from:from,to:to}))});view.dispatch({effects:effects});return true};const foldKeymap=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:foldCode},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:unfoldCode},{key:"Ctrl-Alt-[",run:foldAll},{key:"Ctrl-Alt-]",run:unfoldAll}];const defaultConfig={placeholderDOM:null,placeholderText:"…"};const foldConfig=Facet.define({combine(values){return combineConfig(values,defaultConfig)}});function codeFolding(config){let result=[foldState,baseTheme$1];if(config)result.push(foldConfig.of(config));return result}const foldWidget=Decoration.replace({widget:new class extends WidgetType{toDOM(view){let{state}=view,conf=state.facet(foldConfig);let onclick=event=>{let line=view.lineBlockAt(view.posAtDOM(event.target));let folded=findFold(view.state,line.from,line.to);if(folded)view.dispatch({effects:unfoldEffect.of(folded)});event.preventDefault()};if(conf.placeholderDOM)return conf.placeholderDOM(view,onclick);let element=document.createElement("span");element.textContent=conf.placeholderText;element.setAttribute("aria-label",state.phrase("folded code"));element.title=state.phrase("unfold");element.className="cm-foldPlaceholder";element.onclick=onclick;return element}}});const foldGutterDefaults={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>false};class FoldMarker extends GutterMarker{constructor(config,open){super();this.config=config;this.open=open}eq(other){return this.config==other.config&&this.open==other.open}toDOM(view){if(this.config.markerDOM)return this.config.markerDOM(this.open);let span=document.createElement("span");span.textContent=this.open?this.config.openText:this.config.closedText;span.title=view.state.phrase(this.open?"Fold line":"Unfold line");return span}}function foldGutter(config={}){let fullConfig=Object.assign(Object.assign({},foldGutterDefaults),config);let canFold=new FoldMarker(fullConfig,true),canUnfold=new FoldMarker(fullConfig,false);let markers=ViewPlugin.fromClass(class{constructor(view){this.from=view.viewport.from;this.markers=this.buildMarkers(view)}update(update){if(update.docChanged||update.viewportChanged||update.startState.facet(language)!=update.state.facet(language)||update.startState.field(foldState,false)!=update.state.field(foldState,false)||syntaxTree(update.startState)!=syntaxTree(update.state)||fullConfig.foldingChanged(update))this.markers=this.buildMarkers(update.view)}buildMarkers(view){let builder=new RangeSetBuilder;for(let line of view.viewportLineBlocks){let mark=findFold(view.state,line.from,line.to)?canUnfold:foldable(view.state,line.from,line.to)?canFold:null;if(mark)builder.add(line.from,line.from,mark)}return builder.finish()}});let{domEventHandlers}=fullConfig;return[markers,gutter({class:"cm-foldGutter",markers(view){var _a;return((_a=view.plugin(markers))===null||_a===void 0?void 0:_a.markers)||RangeSet.empty},initialSpacer(){return new FoldMarker(fullConfig,false)},domEventHandlers:Object.assign(Object.assign({},domEventHandlers),{click:(view,line,event)=>{if(domEventHandlers.click&&domEventHandlers.click(view,line,event))return true;let folded=findFold(view.state,line.from,line.to);if(folded){view.dispatch({effects:unfoldEffect.of(folded)});return true}let range=foldable(view.state,line.from,line.to);if(range){view.dispatch({effects:foldEffect.of(range)});return true}return false}})}),codeFolding()]}const baseTheme$1=EditorView.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class HighlightStyle{constructor(specs,options){this.specs=specs;let modSpec;function def(spec){let cls=StyleModule.newName();(modSpec||(modSpec=Object.create(null)))["."+cls]=spec;return cls}const all=typeof options.all=="string"?options.all:options.all?def(options.all):undefined;const scopeOpt=options.scope;this.scope=scopeOpt instanceof Language?type=>type.prop(languageDataProp)==scopeOpt.data:scopeOpt?type=>type==scopeOpt:undefined;this.style=tagHighlighter(specs.map(style=>({tag:style.tag,class:style.class||def(Object.assign({},style,{tag:null}))})),{all:all}).style;this.module=modSpec?new StyleModule(modSpec):null;this.themeType=options.themeType}static define(specs,options){return new HighlightStyle(specs,options||{})}}const highlighterFacet=Facet.define();const fallbackHighlighter=Facet.define({combine(values){return values.length?[values[0]]:null}});function getHighlighters(state){let main=state.facet(highlighterFacet);return main.length?main:state.facet(fallbackHighlighter)}function syntaxHighlighting(highlighter,options){let ext=[treeHighlighter],themeType;if(highlighter instanceof HighlightStyle){if(highlighter.module)ext.push(EditorView.styleModule.of(highlighter.module));themeType=highlighter.themeType}if(options===null||options===void 0?void 0:options.fallback)ext.push(fallbackHighlighter.of(highlighter));else if(themeType)ext.push(highlighterFacet.computeN([EditorView.darkTheme],state=>{return state.facet(EditorView.darkTheme)==(themeType=="dark")?[highlighter]:[]}));else ext.push(highlighterFacet.of(highlighter));return ext}function highlightingFor(state,tags,scope){let highlighters=getHighlighters(state);let result=null;if(highlighters)for(let highlighter of highlighters){if(!highlighter.scope||scope&&highlighter.scope(scope)){let cls=highlighter.style(tags);if(cls)result=result?result+" "+cls:cls}}return result}class TreeHighlighter{constructor(view){this.markCache=Object.create(null);this.tree=syntaxTree(view.state);this.decorations=this.buildDeco(view,getHighlighters(view.state))}update(update){let tree=syntaxTree(update.state),highlighters=getHighlighters(update.state);let styleChange=highlighters!=getHighlighters(update.startState);if(tree.length{builder.add(from,to,this.markCache[style]||(this.markCache[style]=Decoration.mark({class:style})))},from,to)}return builder.finish()}}const treeHighlighter=Prec.high(ViewPlugin.fromClass(TreeHighlighter,{decorations:v=>v.decorations}));const defaultHighlightStyle=HighlightStyle.define([{tag:tags.meta,color:"#7a757a"},{tag:tags.link,textDecoration:"underline"},{tag:tags.heading,textDecoration:"underline",fontWeight:"bold"},{tag:tags.emphasis,fontStyle:"italic"},{tag:tags.strong,fontWeight:"bold"},{tag:tags.strikethrough,textDecoration:"line-through"},{tag:tags.keyword,color:"#708"},{tag:[tags.atom,tags.bool,tags.url,tags.contentSeparator,tags.labelName],color:"#219"},{tag:[tags.literal,tags.inserted],color:"#164"},{tag:[tags.string,tags.deleted],color:"#a11"},{tag:[tags.regexp,tags.escape,tags.special(tags.string)],color:"#e40"},{tag:tags.definition(tags.variableName),color:"#00f"},{tag:tags.local(tags.variableName),color:"#30a"},{tag:[tags.typeName,tags.namespace],color:"#085"},{tag:tags.className,color:"#167"},{tag:[tags.special(tags.variableName),tags.macroName],color:"#256"},{tag:tags.definition(tags.propertyName),color:"#00c"},{tag:tags.comment,color:"#940"},{tag:tags.invalid,color:"#f00"}]);const baseTheme=EditorView.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}});const DefaultScanDist=1e4,DefaultBrackets="()[]{}";const bracketMatchingConfig=Facet.define({combine(configs){return combineConfig(configs,{afterCursor:true,brackets:DefaultBrackets,maxScanDistance:DefaultScanDist,renderMatch:defaultRenderMatch})}});const matchingMark=Decoration.mark({class:"cm-matchingBracket"}),nonmatchingMark=Decoration.mark({class:"cm-nonmatchingBracket"});function defaultRenderMatch(match){let decorations=[];let mark=match.matched?matchingMark:nonmatchingMark;decorations.push(mark.range(match.start.from,match.start.to));if(match.end)decorations.push(mark.range(match.end.from,match.end.to));return decorations}const bracketMatchingState=StateField.define({create(){return Decoration.none},update(deco,tr){if(!tr.docChanged&&!tr.selection)return deco;let decorations=[];let config=tr.state.facet(bracketMatchingConfig);for(let range of tr.state.selection.ranges){if(!range.empty)continue;let match=matchBrackets(tr.state,range.head,-1,config)||range.head>0&&matchBrackets(tr.state,range.head-1,1,config)||config.afterCursor&&(matchBrackets(tr.state,range.head,1,config)||range.headEditorView.decorations.from(f)});const bracketMatchingUnique=[bracketMatchingState,baseTheme];function bracketMatching(config={}){return[bracketMatchingConfig.of(config),bracketMatchingUnique]}function matchingNodes(node,dir,brackets){let byProp=node.prop(dir<0?NodeProp.openedBy:NodeProp.closedBy);if(byProp)return byProp;if(node.name.length==1){let index=brackets.indexOf(node.name);if(index>-1&&index%2==(dir<0?1:0))return[brackets[index+dir]]}return null}function matchBrackets(state,pos,dir,config={}){let maxScanDistance=config.maxScanDistance||DefaultScanDist,brackets=config.brackets||DefaultBrackets;let tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur=node;cur;cur=cur.parent){let matches=matchingNodes(cur.type,dir,brackets);if(matches&&cur.from=token.to){if(depth==0&&matching.indexOf(cursor.type.name)>-1&&cursor.from0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos};let iter=state.doc.iterRange(pos,dir>0?state.doc.length:0),depth=0;for(let distance=0;!iter.next().done&&distance<=maxScanDistance;){let text=iter.value;if(dir<0)distance+=text.length;let basePos=pos+distance*dir;for(let pos=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos!=end;pos+=dir){let found=brackets.indexOf(text[pos]);if(found<0||tree.resolveInner(basePos+pos,1).type!=tokenType)continue;if(found%2==0==dir>0){depth++}else if(depth==1){return{start:startToken,end:{from:basePos+pos,to:basePos+pos+1},matched:found>>1==bracket>>1}}else{depth--}}if(dir>0)distance+=text.length}return iter.done?{start:startToken,matched:false}:null}function countCol(string,end,tabSize,startIndex=0,startValue=0){if(end==null){end=string.search(/[^\s\u00a0]/);if(end==-1)end=string.length}let n=startValue;for(let i=startIndex;i=this.string.length}sol(){return this.pos==0}peek(){return this.string.charAt(this.pos)||undefined}next(){if(this.posstart}eatSpace(){let start=this.pos;while(/[\s\u00a0]/.test(this.string.charAt(this.pos)))++this.pos;return this.pos>start}skipToEnd(){this.pos=this.string.length}skipTo(ch){let found=this.string.indexOf(ch,this.pos);if(found>-1){this.pos=found;return true}}backUp(n){this.pos-=n}column(){if(this.lastColumnPoscaseInsensitive?str.toLowerCase():str;let substr=this.string.substr(this.pos,pattern.length);if(cased(substr)==cased(pattern)){if(consume!==false)this.pos+=pattern.length;return true}else return null}else{let match=this.string.slice(this.pos).match(pattern);if(match&&match.index>0)return null;if(match&&consume!==false)this.pos+=match[0].length;return match}}current(){return this.string.slice(this.start,this.pos)}}function fullParser(spec){return{name:spec.name||"",token:spec.token,blankLine:spec.blankLine||(()=>{}),startState:spec.startState||(()=>true),copyState:spec.copyState||defaultCopyState,indent:spec.indent||(()=>null),languageData:spec.languageData||{},tokenTable:spec.tokenTable||noTokens}}function defaultCopyState(state){if(typeof state!="object")return state;let newState={};for(let prop in state){let val=state[prop];newState[prop]=val instanceof Array?val.slice():val}return newState}class StreamLanguage extends Language{constructor(parser){let data=defineLanguageFacet(parser.languageData);let p=fullParser(parser),self;let impl=new class extends Parser{createParse(input,fragments,ranges){return new Parse(self,input,fragments,ranges)}};super(data,impl,[indentService.of((cx,pos)=>this.getIndent(cx,pos))],parser.name);this.topNode=docID(data);self=this;this.streamParser=p;this.stateAfter=new NodeProp({perNode:true});this.tokenTable=parser.tokenTable?new TokenTable(p.tokenTable):defaultTokenTable}static define(spec){return new StreamLanguage(spec)}getIndent(cx,pos){let tree=syntaxTree(cx.state),at=tree.resolve(pos);while(at&&at.type!=this.topNode)at=at.parent;if(!at)return null;let start=findState(this,tree,0,at.from,pos),statePos,state;if(start){state=start.state;statePos=start.pos+1}else{state=this.streamParser.startState(cx.unit);statePos=0}if(pos-statePos>1e4)return null;while(statePos=startPos&&off+tree.length<=before&&tree.prop(lang.stateAfter);if(state)return{state:lang.streamParser.copyState(state),pos:off+tree.length};for(let i=tree.children.length-1;i>=0;i--){let child=tree.children[i],pos=off+tree.positions[i];let found=child instanceof Tree&&pos=tree.length)return tree;if(!inside&&tree.type==lang.topNode)inside=true;for(let i=tree.children.length-1;i>=0;i--){let pos=tree.positions[i],child=tree.children[i],inner;if(posstartPos&&findState(lang,f.tree,0-f.offset,startPos,to),tree;if(found&&(tree=cutTree(lang,f.tree,startPos+f.offset,found.pos+f.offset,false)))return{state:found.state,tree:tree}}return{state:lang.streamParser.startState(editorState?getIndentUnit(editorState):4),tree:Tree.empty}}class Parse{constructor(lang,input,fragments,ranges){this.lang=lang;this.input=input;this.fragments=fragments;this.ranges=ranges;this.stoppedAt=null;this.chunks=[];this.chunkPos=[];this.chunk=[];this.chunkReused=undefined;this.rangeIndex=0;this.to=ranges[ranges.length-1].to;let context=ParseContext.get(),from=ranges[0].from;let{state,tree}=findStartInFragments(lang,fragments,from,context===null||context===void 0?void 0:context.state);this.state=state;this.parsedPos=this.chunkStart=from+tree.length;for(let i=0;i=parseEnd)return this.finish();if(context&&this.parsedPos>=context.viewport.to){context.skipUntilInView(this.parsedPos,parseEnd);return this.finish()}return null}stopAt(pos){this.stoppedAt=pos}lineAfter(pos){let chunk=this.input.chunk(pos);if(!this.input.lineChunks){let eol=chunk.indexOf("\n");if(eol>-1)chunk=chunk.slice(0,eol)}else if(chunk=="\n"){chunk=""}return pos+chunk.length<=this.to?chunk:chunk.slice(0,this.to-pos)}nextLine(){let from=this.parsedPos,line=this.lineAfter(from),end=from+line.length;for(let index=this.rangeIndex;;){let rangeEnd=this.ranges[index].to;if(rangeEnd>=end)break;line=line.slice(0,rangeEnd-(end-line.length));index++;if(index==this.ranges.length)break;let rangeStart=this.ranges[index].from;let after=this.lineAfter(rangeStart);line+=after;end=rangeStart+after.length}return{line:line,end:end}}skipGapsTo(pos,offset,side){for(;;){let end=this.ranges[this.rangeIndex].to,offPos=pos+offset;if(side>0?end>offPos:end>=offPos)break;let start=this.ranges[++this.rangeIndex].from;offset+=start-end}return offset}moveRangeIndex(){while(this.ranges[this.rangeIndex].to1){offset=this.skipGapsTo(from,offset,1);from+=offset;let len0=this.chunk.length;offset=this.skipGapsTo(to,offset,-1);to+=offset;size+=this.chunk.length-len0}this.chunk.push(id,from,to,size);return offset}parseLine(context){let{line,end}=this.nextLine(),offset=0,{streamParser}=this.lang;let stream=new StringStream(line,context?context.state.tabSize:4,context?getIndentUnit(context.state):2);if(stream.eol()){streamParser.blankLine(this.state,stream.indentUnit)}else{while(!stream.eol()){let token=readToken(streamParser.token,stream,this.state);if(token)offset=this.emitToken(this.lang.tokenTable.resolve(token),this.parsedPos+stream.start,this.parsedPos+stream.pos,4,offset);if(stream.start>1e4)break}}this.parsedPos=end;this.moveRangeIndex();if(this.parsedPosstream.start)return result}throw new Error("Stream parser failed to advance stream.")}const noTokens=Object.create(null);const typeArray=[NodeType.none];const nodeSet=new NodeSet(typeArray);const warned=[];const defaultTable=Object.create(null);for(let[legacyName,name]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=createTokenType(noTokens,name);class TokenTable{constructor(extra){this.extra=extra;this.table=Object.assign(Object.create(null),defaultTable)}resolve(tag){return!tag?0:this.table[tag]||(this.table[tag]=createTokenType(this.extra,tag))}}const defaultTokenTable=new TokenTable(noTokens);function warnForPart(part,msg){if(warned.indexOf(part)>-1)return;warned.push(part);console.warn(msg)}function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags[part];if(!value){warnForPart(part,`Unknown highlighting tag ${part}`)}else if(typeof value=="function"){if(!tag)warnForPart(part,`Modifier ${part} used at start of tag`);else tag=value(tag)}else{if(tag)warnForPart(part,`Tag ${part} used as modifier`);else tag=value}}if(!tag)return 0;let name=tagStr.replace(/ /g,"_"),type=NodeType.define({id:typeArray.length,name:name,props:[styleTags({[name]:tag})]});typeArray.push(type);return type.id}function docID(data){let type=NodeType.define({id:typeArray.length,name:"Document",props:[languageDataProp.add(()=>data)]});typeArray.push(type);return type}export{HighlightStyle,IndentContext,LRLanguage,Language,LanguageDescription,LanguageSupport,ParseContext,StreamLanguage,StringStream,TreeIndentContext,bracketMatching,codeFolding,continuedIndent,defaultHighlightStyle,defineLanguageFacet,delimitedIndent,ensureSyntaxTree,flatIndent,foldAll,foldCode,foldEffect,foldGutter,foldInside,foldKeymap,foldNodeProp,foldService,foldState,foldable,foldedRanges,forceParsing,getIndentUnit,getIndentation,highlightingFor,indentNodeProp,indentOnInput,indentRange,indentService,indentString,indentUnit,language,languageDataProp,matchBrackets,syntaxHighlighting,syntaxParserRunning,syntaxTree,syntaxTreeAvailable,unfoldAll,unfoldCode,unfoldEffect};
\ No newline at end of file
diff --git a/public/js/@codemirror/search.js b/public/js/@codemirror/search.js
new file mode 100755
index 0000000..2247e7a
--- /dev/null
+++ b/public/js/@codemirror/search.js
@@ -0,0 +1 @@
+import{showPanel,EditorView,getPanel,Decoration,ViewPlugin,runScopeHandlers}from"@codemirror/view";import{codePointAt,fromCodePoint,codePointSize,StateEffect,StateField,EditorSelection,Facet,combineConfig,CharCategory,RangeSetBuilder,Prec,EditorState,findClusterBreak}from"@codemirror/state";import elt from"crelt";const basicNormalize=typeof String.prototype.normalize=="function"?x=>x.normalize("NFKD"):x=>x;class SearchCursor{constructor(text,query,from=0,to=text.length,normalize,test){this.test=test;this.value={from:0,to:0};this.done=false;this.matches=[];this.buffer="";this.bufferPos=0;this.iter=text.iterRange(from,to);this.bufferStart=from;this.normalize=normalize?x=>normalize(basicNormalize(x)):basicNormalize;this.query=this.normalize(query)}peek(){if(this.bufferPos==this.buffer.length){this.bufferStart+=this.buffer.length;this.iter.next();if(this.iter.done)return-1;this.bufferPos=0;this.buffer=this.iter.value}return codePointAt(this.buffer,this.bufferPos)}next(){while(this.matches.length)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let next=this.peek();if(next<0){this.done=true;return this}let str=fromCodePoint(next),start=this.bufferStart+this.bufferPos;this.bufferPos+=codePointSize(next);let norm=this.normalize(str);for(let i=0,pos=start;;i++){let code=norm.charCodeAt(i);let match=this.match(code,pos);if(match){this.value=match;return this}if(i==norm.length-1)break;if(pos==start&&ithis.to)this.curLine=this.curLine.slice(0,this.to-this.curLineStart);this.iter.next()}}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1;if(this.curLineStart>this.to)this.curLine="";else this.getLine(0)}next(){for(let off=this.matchPos-this.curLineStart;;){this.re.lastIndex=off;let match=this.matchPos<=this.to&&this.re.exec(this.curLine);if(match){let from=this.curLineStart+match.index,to=from+match[0].length;this.matchPos=toCharEnd(this.text,to+(from==to?1:0));if(from==this.curLineStart+this.curLine.length)this.nextLine();if((fromthis.value.to)&&(!this.test||this.test(from,to,match))){this.value={from:from,to:to,match:match};return this}off=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=to||cached.to<=from){let flat=new FlattenedDoc(from,doc.sliceString(from,to));flattened.set(doc,flat);return flat}if(cached.from==from&&cached.to==to)return cached;let{text,from:cachedFrom}=cached;if(cachedFrom>from){text=doc.sliceString(from,cachedFrom)+text;cachedFrom=from}if(cached.to=this.to?this.to:this.text.lineAt(pos).to}next(){for(;;){let off=this.re.lastIndex=this.matchPos-this.flat.from;let match=this.re.exec(this.flat.text);if(match&&!match[0]&&match.index==off){this.re.lastIndex=off+1;match=this.re.exec(this.flat.text)}if(match){let from=this.flat.from+match.index,to=from+match[0].length;if((this.flat.to>=this.to||match.index+match[0].length<=this.flat.text.length-10)&&(!this.test||this.test(from,to,match))){this.value={from:from,to:to,match:match};this.matchPos=toCharEnd(this.text,to+(from==to?1:0));return this}}if(this.flat.to==this.to){this.done=true;return this}this.flat=FlattenedDoc.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}if(typeof Symbol!="undefined"){RegExpCursor.prototype[Symbol.iterator]=MultilineRegExpCursor.prototype[Symbol.iterator]=function(){return this}}function validRegExp(source){try{new RegExp(source,baseFlags);return true}catch(_a){return false}}function toCharEnd(text,pos){if(pos>=text.length)return pos;let line=text.lineAt(pos),next;while(pos=56320&&next<57344)pos++;return pos}function createLineDialog(view){let input=elt("input",{class:"cm-textfield",name:"line"});let dom=elt("form",{class:"cm-gotoLine",onkeydown:event=>{if(event.keyCode==27){event.preventDefault();view.dispatch({effects:dialogEffect.of(false)});view.focus()}else if(event.keyCode==13){event.preventDefault();go()}},onsubmit:event=>{event.preventDefault();go()}},elt("label",view.state.phrase("Go to line"),": ",input)," ",elt("button",{class:"cm-button",type:"submit"},view.state.phrase("go")));function go(){let match=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);if(!match)return;let{state}=view,startLine=state.doc.lineAt(state.selection.main.head);let[,sign,ln,cl,percent]=match;let col=cl?+cl.slice(1):0;let line=ln?+ln:startLine.number;if(ln&&percent){let pc=line/100;if(sign)pc=pc*(sign=="-"?-1:1)+startLine.number/state.doc.lines;line=Math.round(state.doc.lines*pc)}else if(ln&&sign){line=line*(sign=="-"?-1:1)+startLine.number}let docLine=state.doc.line(Math.max(1,Math.min(state.doc.lines,line)));view.dispatch({effects:dialogEffect.of(false),selection:EditorSelection.cursor(docLine.from+Math.max(0,Math.min(col,docLine.length))),scrollIntoView:true});view.focus()}return{dom:dom}}const dialogEffect=StateEffect.define();const dialogField=StateField.define({create(){return true},update(value,tr){for(let e of tr.effects)if(e.is(dialogEffect))value=e.value;return value},provide:f=>showPanel.from(f,val=>val?createLineDialog:null)});const gotoLine=view=>{let panel=getPanel(view,createLineDialog);if(!panel){let effects=[dialogEffect.of(true)];if(view.state.field(dialogField,false)==null)effects.push(StateEffect.appendConfig.of([dialogField,baseTheme$1]));view.dispatch({effects:effects});panel=getPanel(view,createLineDialog)}if(panel)panel.dom.querySelector("input").focus();return true};const baseTheme$1=EditorView.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}});const defaultHighlightOptions={highlightWordAroundCursor:false,minSelectionLength:1,maxMatches:100,wholeWords:false};const highlightConfig=Facet.define({combine(options){return combineConfig(options,defaultHighlightOptions,{highlightWordAroundCursor:(a,b)=>a||b,minSelectionLength:Math.min,maxMatches:Math.min})}});function highlightSelectionMatches(options){let ext=[defaultTheme,matchHighlighter];if(options)ext.push(highlightConfig.of(options));return ext}const matchDeco=Decoration.mark({class:"cm-selectionMatch"});const mainMatchDeco=Decoration.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function insideWordBoundaries(check,state,from,to){return(from==0||check(state.sliceDoc(from-1,from))!=CharCategory.Word)&&(to==state.doc.length||check(state.sliceDoc(to,to+1))!=CharCategory.Word)}function insideWord(check,state,from,to){return check(state.sliceDoc(from,from+1))==CharCategory.Word&&check(state.sliceDoc(to-1,to))==CharCategory.Word}const matchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){if(update.selectionSet||update.docChanged||update.viewportChanged)this.decorations=this.getDeco(update.view)}getDeco(view){let conf=view.state.facet(highlightConfig);let{state}=view,sel=state.selection;if(sel.ranges.length>1)return Decoration.none;let range=sel.main,query,check=null;if(range.empty){if(!conf.highlightWordAroundCursor)return Decoration.none;let word=state.wordAt(range.head);if(!word)return Decoration.none;check=state.charCategorizer(range.head);query=state.sliceDoc(word.from,word.to)}else{let len=range.to-range.from;if(len200)return Decoration.none;if(conf.wholeWords){query=state.sliceDoc(range.from,range.to);check=state.charCategorizer(range.head);if(!(insideWordBoundaries(check,state,range.from,range.to)&&insideWord(check,state,range.from,range.to)))return Decoration.none}else{query=state.sliceDoc(range.from,range.to).trim();if(!query)return Decoration.none}}let deco=[];for(let part of view.visibleRanges){let cursor=new SearchCursor(state.doc,query,part.from,part.to);while(!cursor.next().done){let{from,to}=cursor.value;if(!check||insideWordBoundaries(check,state,from,to)){if(range.empty&&from<=range.from&&to>=range.to)deco.push(mainMatchDeco.range(from,to));else if(from>=range.to||to<=range.from)deco.push(matchDeco.range(from,to));if(deco.length>conf.maxMatches)return Decoration.none}}}return Decoration.set(deco)}},{decorations:v=>v.decorations});const defaultTheme=EditorView.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}});const selectWord=({state,dispatch})=>{let{selection}=state;let newSel=EditorSelection.create(selection.ranges.map(range=>state.wordAt(range.head)||EditorSelection.cursor(range.head)),selection.mainIndex);if(newSel.eq(selection))return false;dispatch(state.update({selection:newSel}));return true};function findNextOccurrence(state,query){let{main,ranges}=state.selection;let word=state.wordAt(main.head),fullWord=word&&word.from==main.from&&word.to==main.to;for(let cycled=false,cursor=new SearchCursor(state.doc,query,ranges[ranges.length-1].to);;){cursor.next();if(cursor.done){if(cycled)return null;cursor=new SearchCursor(state.doc,query,0,Math.max(0,ranges[ranges.length-1].from-1));cycled=true}else{if(cycled&&ranges.some(r=>r.from==cursor.value.from))continue;if(fullWord){let word=state.wordAt(cursor.value.from);if(!word||word.from!=cursor.value.from||word.to!=cursor.value.to)continue}return cursor.value}}}const selectNextOccurrence=({state,dispatch})=>{let{ranges}=state.selection;if(ranges.some(sel=>sel.from===sel.to))return selectWord({state:state,dispatch:dispatch});let searchedText=state.sliceDoc(ranges[0].from,ranges[0].to);if(state.selection.ranges.some(r=>state.sliceDoc(r.from,r.to)!=searchedText))return false;let range=findNextOccurrence(state,searchedText);if(!range)return false;dispatch(state.update({selection:state.selection.addRange(EditorSelection.range(range.from,range.to),false),effects:EditorView.scrollIntoView(range.to)}));return true};const searchConfigFacet=Facet.define({combine(configs){return combineConfig(configs,{top:false,caseSensitive:false,literal:false,wholeWord:false,createPanel:view=>new SearchPanel(view)})}});function search(config){return config?[searchConfigFacet.of(config),searchExtensions]:searchExtensions}class SearchQuery{constructor(config){this.search=config.search;this.caseSensitive=!!config.caseSensitive;this.literal=!!config.literal;this.regexp=!!config.regexp;this.replace=config.replace||"";this.valid=!!this.search&&(!this.regexp||validRegExp(this.search));this.unquoted=this.unquote(this.search);this.wholeWord=!!config.wholeWord}unquote(text){return this.literal?text:text.replace(/\\([nrt\\])/g,(_,ch)=>ch=="n"?"\n":ch=="r"?"\r":ch=="t"?"\t":"\\")}eq(other){return this.search==other.search&&this.replace==other.replace&&this.caseSensitive==other.caseSensitive&&this.regexp==other.regexp&&this.wholeWord==other.wholeWord}create(){return this.regexp?new RegExpQuery(this):new StringQuery(this)}getCursor(state,from=0,to){let st=state.doc?state:EditorState.create({doc:state});if(to==null)to=st.doc.length;return this.regexp?regexpCursor(this,st,from,to):stringCursor(this,st,from,to)}}class QueryType{constructor(spec){this.spec=spec}}function stringCursor(spec,state,from,to){return new SearchCursor(state.doc,spec.unquoted,from,to,spec.caseSensitive?undefined:x=>x.toLowerCase(),spec.wholeWord?stringWordTest(state.doc,state.charCategorizer(state.selection.main.head)):undefined)}function stringWordTest(doc,categorizer){return(from,to,buf,bufPos)=>{if(bufPos>from||bufPos+buf.length=limit)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add){let cursor=stringCursor(this.spec,state,Math.max(0,from-this.spec.unquoted.length),Math.min(to+this.spec.unquoted.length,state.doc.length));while(!cursor.next().done)add(cursor.value.from,cursor.value.to)}}function regexpCursor(spec,state,from,to){return new RegExpCursor(state.doc,spec.search,{ignoreCase:!spec.caseSensitive,test:spec.wholeWord?regexpWordTest(state.charCategorizer(state.selection.main.head)):undefined},from,to)}function charBefore(str,index){return str.slice(findClusterBreak(str,index,false),index)}function charAfter(str,index){return str.slice(index,findClusterBreak(str,index))}function regexpWordTest(categorizer){return(_from,_to,match)=>!match[0].length||(categorizer(charBefore(match.input,match.index))!=CharCategory.Word||categorizer(charAfter(match.input,match.index))!=CharCategory.Word)&&(categorizer(charAfter(match.input,match.index+match[0].length))!=CharCategory.Word||categorizer(charBefore(match.input,match.index+match[0].length))!=CharCategory.Word)}class RegExpQuery extends QueryType{nextMatch(state,curFrom,curTo){let cursor=regexpCursor(this.spec,state,curTo,state.doc.length).next();if(cursor.done)cursor=regexpCursor(this.spec,state,0,curFrom).next();return cursor.done?null:cursor.value}prevMatchInRange(state,from,to){for(let size=1;;size++){let start=Math.max(from,to-size*1e4);let cursor=regexpCursor(this.spec,state,start,to),range=null;while(!cursor.next().done)range=cursor.value;if(range&&(start==from||range.from>start+10))return range;if(start==from)return null}}prevMatch(state,curFrom,curTo){return this.prevMatchInRange(state,0,curFrom)||this.prevMatchInRange(state,curTo,state.doc.length)}getReplacement(result){return this.spec.unquote(this.spec.replace.replace(/\$([$&\d+])/g,(m,i)=>i=="$"?"$":i=="&"?result.match[0]:i!="0"&&+i=limit)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add){let cursor=regexpCursor(this.spec,state,Math.max(0,from-250),Math.min(to+250,state.doc.length));while(!cursor.next().done)add(cursor.value.from,cursor.value.to)}}const setSearchQuery=StateEffect.define();const togglePanel=StateEffect.define();const searchState=StateField.define({create(state){return new SearchState(defaultQuery(state).create(),null)},update(value,tr){for(let effect of tr.effects){if(effect.is(setSearchQuery))value=new SearchState(effect.value.create(),value.panel);else if(effect.is(togglePanel))value=new SearchState(value.query,effect.value?createSearchPanel:null)}return value},provide:f=>showPanel.from(f,val=>val.panel)});function getSearchQuery(state){let curState=state.field(searchState,false);return curState?curState.query.spec:defaultQuery(state)}function searchPanelOpen(state){var _a;return((_a=state.field(searchState,false))===null||_a===void 0?void 0:_a.panel)!=null}class SearchState{constructor(query,panel){this.query=query;this.panel=panel}}const matchMark=Decoration.mark({class:"cm-searchMatch"}),selectedMatchMark=Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"});const searchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.view=view;this.decorations=this.highlight(view.state.field(searchState))}update(update){let state=update.state.field(searchState);if(state!=update.startState.field(searchState)||update.docChanged||update.selectionSet||update.viewportChanged)this.decorations=this.highlight(state)}highlight({query,panel}){if(!panel||!query.spec.valid)return Decoration.none;let{view}=this;let builder=new RangeSetBuilder;for(let i=0,ranges=view.visibleRanges,l=ranges.length;iranges[i+1].from-2*250)to=ranges[++i].to;query.highlight(view.state,from,to,(from,to)=>{let selected=view.state.selection.ranges.some(r=>r.from==from&&r.to==to);builder.add(from,to,selected?selectedMatchMark:matchMark)})}return builder.finish()}},{decorations:v=>v.decorations});function searchCommand(f){return view=>{let state=view.state.field(searchState,false);return state&&state.query.spec.valid?f(view,state):openSearchPanel(view)}}const findNext=searchCommand((view,{query})=>{let{to}=view.state.selection.main;let next=query.nextMatch(view.state,to,to);if(!next)return false;view.dispatch({selection:{anchor:next.from,head:next.to},scrollIntoView:true,effects:announceMatch(view,next),userEvent:"select.search"});return true});const findPrevious=searchCommand((view,{query})=>{let{state}=view,{from}=state.selection.main;let range=query.prevMatch(state,from,from);if(!range)return false;view.dispatch({selection:{anchor:range.from,head:range.to},scrollIntoView:true,effects:announceMatch(view,range),userEvent:"select.search"});return true});const selectMatches=searchCommand((view,{query})=>{let ranges=query.matchAll(view.state,1e3);if(!ranges||!ranges.length)return false;view.dispatch({selection:EditorSelection.create(ranges.map(r=>EditorSelection.range(r.from,r.to))),userEvent:"select.search.matches"});return true});const selectSelectionMatches=({state,dispatch})=>{let sel=state.selection;if(sel.ranges.length>1||sel.main.empty)return false;let{from,to}=sel.main;let ranges=[],main=0;for(let cur=new SearchCursor(state.doc,state.sliceDoc(from,to));!cur.next().done;){if(ranges.length>1e3)return false;if(cur.value.from==from)main=ranges.length;ranges.push(EditorSelection.range(cur.value.from,cur.value.to))}dispatch(state.update({selection:EditorSelection.create(ranges,main),userEvent:"select.search.matches"}));return true};const replaceNext=searchCommand((view,{query})=>{let{state}=view,{from,to}=state.selection.main;if(state.readOnly)return false;let next=query.nextMatch(state,from,from);if(!next)return false;let changes=[],selection,replacement;let announce=[];if(next.from==from&&next.to==to){replacement=state.toText(query.getReplacement(next));changes.push({from:next.from,to:next.to,insert:replacement});next=query.nextMatch(state,next.from,next.to);announce.push(EditorView.announce.of(state.phrase("replaced match on line $",state.doc.lineAt(from).number)+"."))}if(next){let off=changes.length==0||changes[0].from>=next.to?0:next.to-next.from-replacement.length;selection={anchor:next.from-off,head:next.to-off};announce.push(announceMatch(view,next))}view.dispatch({changes:changes,selection:selection,scrollIntoView:!!selection,effects:announce,userEvent:"input.replace"});return true});const replaceAll=searchCommand((view,{query})=>{if(view.state.readOnly)return false;let changes=query.matchAll(view.state,1e9).map(match=>{let{from,to}=match;return{from:from,to:to,insert:query.getReplacement(match)}});if(!changes.length)return false;let announceText=view.state.phrase("replaced $ matches",changes.length)+".";view.dispatch({changes:changes,effects:EditorView.announce.of(announceText),userEvent:"input.replace.all"});return true});function createSearchPanel(view){return view.state.facet(searchConfigFacet).createPanel(view)}function defaultQuery(state,fallback){var _a,_b,_c,_d;let sel=state.selection.main;let selText=sel.empty||sel.to>sel.from+100?"":state.sliceDoc(sel.from,sel.to);if(fallback&&!selText)return fallback;let config=state.facet(searchConfigFacet);return new SearchQuery({search:((_a=fallback===null||fallback===void 0?void 0:fallback.literal)!==null&&_a!==void 0?_a:config.literal)?selText:selText.replace(/\n/g,"\\n"),caseSensitive:(_b=fallback===null||fallback===void 0?void 0:fallback.caseSensitive)!==null&&_b!==void 0?_b:config.caseSensitive,literal:(_c=fallback===null||fallback===void 0?void 0:fallback.literal)!==null&&_c!==void 0?_c:config.literal,wholeWord:(_d=fallback===null||fallback===void 0?void 0:fallback.wholeWord)!==null&&_d!==void 0?_d:config.wholeWord})}const openSearchPanel=view=>{let state=view.state.field(searchState,false);if(state&&state.panel){let panel=getPanel(view,createSearchPanel);if(!panel)return false;let searchInput=panel.dom.querySelector("[main-field]");if(searchInput&&searchInput!=view.root.activeElement){let query=defaultQuery(view.state,state.query.spec);if(query.valid)view.dispatch({effects:setSearchQuery.of(query)});searchInput.focus();searchInput.select()}}else{view.dispatch({effects:[togglePanel.of(true),state?setSearchQuery.of(defaultQuery(view.state,state.query.spec)):StateEffect.appendConfig.of(searchExtensions)]})}return true};const closeSearchPanel=view=>{let state=view.state.field(searchState,false);if(!state||!state.panel)return false;let panel=getPanel(view,createSearchPanel);if(panel&&panel.dom.contains(view.root.activeElement))view.focus();view.dispatch({effects:togglePanel.of(false)});return true};const searchKeymap=[{key:"Mod-f",run:openSearchPanel,scope:"editor search-panel"},{key:"F3",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:true},{key:"Mod-g",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:true},{key:"Escape",run:closeSearchPanel,scope:"editor search-panel"},{key:"Mod-Shift-l",run:selectSelectionMatches},{key:"Alt-g",run:gotoLine},{key:"Mod-d",run:selectNextOccurrence,preventDefault:true}];class SearchPanel{constructor(view){this.view=view;let query=this.query=view.state.field(searchState).query.spec;this.commit=this.commit.bind(this);this.searchField=elt("input",{value:query.search,placeholder:phrase(view,"Find"),"aria-label":phrase(view,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit});this.replaceField=elt("input",{value:query.replace,placeholder:phrase(view,"Replace"),"aria-label":phrase(view,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit});this.caseField=elt("input",{type:"checkbox",name:"case",form:"",checked:query.caseSensitive,onchange:this.commit});this.reField=elt("input",{type:"checkbox",name:"re",form:"",checked:query.regexp,onchange:this.commit});this.wordField=elt("input",{type:"checkbox",name:"word",form:"",checked:query.wholeWord,onchange:this.commit});function button(name,onclick,content){return elt("button",{class:"cm-button",name:name,onclick:onclick,type:"button"},content)}this.dom=elt("div",{onkeydown:e=>this.keydown(e),class:"cm-search"},[this.searchField,button("next",()=>findNext(view),[phrase(view,"next")]),button("prev",()=>findPrevious(view),[phrase(view,"previous")]),button("select",()=>selectMatches(view),[phrase(view,"all")]),elt("label",null,[this.caseField,phrase(view,"match case")]),elt("label",null,[this.reField,phrase(view,"regexp")]),elt("label",null,[this.wordField,phrase(view,"by word")]),...view.state.readOnly?[]:[elt("br"),this.replaceField,button("replace",()=>replaceNext(view),[phrase(view,"replace")]),button("replaceAll",()=>replaceAll(view),[phrase(view,"replace all")]),elt("button",{name:"close",onclick:()=>closeSearchPanel(view),"aria-label":phrase(view,"close"),type:"button"},["×"])]])}commit(){let query=new SearchQuery({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});if(!query.eq(this.query)){this.query=query;this.view.dispatch({effects:setSearchQuery.of(query)})}}keydown(e){if(runScopeHandlers(this.view,e,"search-panel")){e.preventDefault()}else if(e.keyCode==13&&e.target==this.searchField){e.preventDefault();(e.shiftKey?findPrevious:findNext)(this.view)}else if(e.keyCode==13&&e.target==this.replaceField){e.preventDefault();replaceNext(this.view)}}update(update){for(let tr of update.transactions)for(let effect of tr.effects){if(effect.is(setSearchQuery)&&!effect.value.eq(this.query))this.setQuery(effect.value)}}setQuery(query){this.query=query;this.searchField.value=query.search;this.replaceField.value=query.replace;this.caseField.checked=query.caseSensitive;this.reField.checked=query.regexp;this.wordField.checked=query.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(searchConfigFacet).top}}function phrase(view,phrase){return view.state.phrase(phrase)}const AnnounceMargin=30;const Break=/[\s\.,:;?!]/;function announceMatch(view,{from,to}){let line=view.state.doc.lineAt(from),lineEnd=view.state.doc.lineAt(to).to;let start=Math.max(line.from,from-AnnounceMargin),end=Math.min(lineEnd,to+AnnounceMargin);let text=view.state.sliceDoc(start,end);if(start!=line.from){for(let i=0;itext.length-AnnounceMargin;i--)if(!Break.test(text[i-1])&&Break.test(text[i])){text=text.slice(0,i);break}}return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`)}const baseTheme=EditorView.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}});const searchExtensions=[searchState,Prec.lowest(searchHighlighter),baseTheme];export{RegExpCursor,SearchCursor,SearchQuery,closeSearchPanel,findNext,findPrevious,getSearchQuery,gotoLine,highlightSelectionMatches,openSearchPanel,replaceAll,replaceNext,search,searchKeymap,searchPanelOpen,selectMatches,selectNextOccurrence,selectSelectionMatches,setSearchQuery};
\ No newline at end of file
diff --git a/public/js/@codemirror/state.js b/public/js/@codemirror/state.js
new file mode 100755
index 0000000..12656d9
--- /dev/null
+++ b/public/js/@codemirror/state.js
@@ -0,0 +1 @@
+class Text{constructor(){}lineAt(pos){if(pos<0||pos>this.length)throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);return this.lineInner(pos,false,1,0)}line(n){if(n<1||n>this.lines)throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);return this.lineInner(n,true,1,0)}replace(from,to,text){let parts=[];this.decompose(0,from,parts,2);if(text.length)text.decompose(0,text.length,parts,1|2);this.decompose(to,this.length,parts,1);return TextNode.from(parts,this.length-(to-from)+text.length)}append(other){return this.replace(this.length,this.length,other)}slice(from,to=this.length){let parts=[];this.decompose(from,to,parts,0);return TextNode.from(parts,to-from)}eq(other){if(other==this)return true;if(other.length!=this.length||other.lines!=this.lines)return false;let start=this.scanIdentical(other,1),end=this.length-this.scanIdentical(other,-1);let a=new RawTextCursor(this),b=new RawTextCursor(other);for(let skip=start,pos=start;;){a.next(skip);b.next(skip);skip=0;if(a.lineBreak!=b.lineBreak||a.done!=b.done||a.value!=b.value)return false;pos+=a.value.length;if(a.done||pos>=end)return true}}iter(dir=1){return new RawTextCursor(this,dir)}iterRange(from,to=this.length){return new PartialTextCursor(this,from,to)}iterLines(from,to){let inner;if(from==null){inner=this.iter()}else{if(to==null)to=this.lines+1;let start=this.line(from).from;inner=this.iterRange(start,Math.max(start,to==this.lines+1?this.length:to<=1?0:this.line(to-1).to))}return new LineCursor(inner)}toString(){return this.sliceString(0)}toJSON(){let lines=[];this.flatten(lines);return lines}static of(text){if(text.length==0)throw new RangeError("A document must have at least one line");if(text.length==1&&!text[0])return Text.empty;return text.length<=32?new TextLeaf(text):TextNode.from(TextLeaf.split(text,[]))}}class TextLeaf extends Text{constructor(text,length=textLength(text)){super();this.text=text;this.length=length}get lines(){return this.text.length}get children(){return null}lineInner(target,isLine,line,offset){for(let i=0;;i++){let string=this.text[i],end=offset+string.length;if((isLine?line:end)>=target)return new Line(offset,end,line,string);offset=end+1;line++}}decompose(from,to,target,open){let text=from<=0&&to>=this.length?this:new TextLeaf(sliceText(this.text,from,to),Math.min(to,this.length)-Math.max(0,from));if(open&1){let prev=target.pop();let joined=appendText(text.text,prev.text.slice(),0,text.length);if(joined.length<=32){target.push(new TextLeaf(joined,prev.length+text.length))}else{let mid=joined.length>>1;target.push(new TextLeaf(joined.slice(0,mid)),new TextLeaf(joined.slice(mid)))}}else{target.push(text)}}replace(from,to,text){if(!(text instanceof TextLeaf))return super.replace(from,to,text);let lines=appendText(this.text,appendText(text.text,sliceText(this.text,0,from)),to);let newLen=this.length+text.length-(to-from);if(lines.length<=32)return new TextLeaf(lines,newLen);return TextNode.from(TextLeaf.split(lines,[]),newLen)}sliceString(from,to=this.length,lineSep="\n"){let result="";for(let pos=0,i=0;pos<=to&&ifrom&&i)result+=lineSep;if(frompos)result+=line.slice(Math.max(0,from-pos),to-pos);pos=end+1}return result}flatten(target){for(let line of this.text)target.push(line)}scanIdentical(){return 0}static split(text,target){let part=[],len=-1;for(let line of text){part.push(line);len+=line.length+1;if(part.length==32){target.push(new TextLeaf(part,len));part=[];len=-1}}if(len>-1)target.push(new TextLeaf(part,len));return target}}class TextNode extends Text{constructor(children,length){super();this.children=children;this.length=length;this.lines=0;for(let child of children)this.lines+=child.lines}lineInner(target,isLine,line,offset){for(let i=0;;i++){let child=this.children[i],end=offset+child.length,endLine=line+child.lines-1;if((isLine?endLine:end)>=target)return child.lineInner(target,isLine,line,offset);offset=end+1;line=endLine+1}}decompose(from,to,target,open){for(let i=0,pos=0;pos<=to&&i=pos){let childOpen=open&((pos<=from?1:0)|(end>=to?2:0));if(pos>=from&&end<=to&&!childOpen)target.push(child);else child.decompose(from-pos,to-pos,target,childOpen)}pos=end+1}}replace(from,to,text){if(text.lines=pos&&to<=end){let updated=child.replace(from-pos,to-pos,text);let totalLines=this.lines-child.lines+updated.lines;if(updated.lines>5-1&&updated.lines>totalLines>>5+1){let copy=this.children.slice();copy[i]=updated;return new TextNode(copy,this.length-(to-from)+text.length)}return super.replace(pos,end,updated)}pos=end+1}return super.replace(from,to,text)}sliceString(from,to=this.length,lineSep="\n"){let result="";for(let i=0,pos=0;ifrom&&i)result+=lineSep;if(frompos)result+=child.sliceString(from-pos,to-pos,lineSep);pos=end+1}return result}flatten(target){for(let child of this.children)child.flatten(target)}scanIdentical(other,dir){if(!(other instanceof TextNode))return 0;let length=0;let[iA,iB,eA,eB]=dir>0?[0,0,this.children.length,other.children.length]:[this.children.length-1,other.children.length-1,-1,-1];for(;;iA+=dir,iB+=dir){if(iA==eA||iB==eB)return length;let chA=this.children[iA],chB=other.children[iB];if(chA!=chB)return length+chA.scanIdentical(chB,dir);length+=chA.length+1}}static from(children,length=children.reduce((l,ch)=>l+ch.length+1,-1)){let lines=0;for(let ch of children)lines+=ch.lines;if(lines<32){let flat=[];for(let ch of children)ch.flatten(flat);return new TextLeaf(flat,length)}let chunk=Math.max(32,lines>>5),maxChunk=chunk<<1,minChunk=chunk>>1;let chunked=[],currentLines=0,currentLen=-1,currentChunk=[];function add(child){let last;if(child.lines>maxChunk&&child instanceof TextNode){for(let node of child.children)add(node)}else if(child.lines>minChunk&&(currentLines>minChunk||!currentLines)){flush();chunked.push(child)}else if(child instanceof TextLeaf&¤tLines&&(last=currentChunk[currentChunk.length-1])instanceof TextLeaf&&child.lines+last.lines<=32){currentLines+=child.lines;currentLen+=child.length+1;currentChunk[currentChunk.length-1]=new TextLeaf(last.text.concat(child.text),last.length+1+child.length)}else{if(currentLines+child.lines>chunk)flush();currentLines+=child.lines;currentLen+=child.length+1;currentChunk.push(child)}}function flush(){if(currentLines==0)return;chunked.push(currentChunk.length==1?currentChunk[0]:TextNode.from(currentChunk,currentLen));currentLen=-1;currentLines=currentChunk.length=0}for(let child of children)add(child);flush();return chunked.length==1?chunked[0]:new TextNode(chunked,length)}}Text.empty=new TextLeaf([""],0);function textLength(text){let length=-1;for(let line of text)length+=line.length+1;return length}function appendText(text,target,from=0,to=1e9){for(let pos=0,i=0,first=true;i=from){if(end>to)line=line.slice(0,to-pos);if(pos0?1:(text instanceof TextLeaf?text.text.length:text.children.length)<<1]}nextInner(skip,dir){this.done=this.lineBreak=false;for(;;){let last=this.nodes.length-1;let top=this.nodes[last],offsetValue=this.offsets[last],offset=offsetValue>>1;let size=top instanceof TextLeaf?top.text.length:top.children.length;if(offset==(dir>0?size:0)){if(last==0){this.done=true;this.value="";return this}if(dir>0)this.offsets[last-1]++;this.nodes.pop();this.offsets.pop()}else if((offsetValue&1)==(dir>0?0:1)){this.offsets[last]+=dir;if(skip==0){this.lineBreak=true;this.value="\n";return this}skip--}else if(top instanceof TextLeaf){let next=top.text[offset+(dir<0?-1:0)];this.offsets[last]+=dir;if(next.length>Math.max(0,skip)){this.value=skip==0?next:dir>0?next.slice(skip):next.slice(0,next.length-skip);return this}skip-=next.length}else{let next=top.children[offset+(dir<0?-1:0)];if(skip>next.length){skip-=next.length;this.offsets[last]+=dir}else{if(dir<0)this.offsets[last]--;this.nodes.push(next);this.offsets.push(dir>0?1:(next instanceof TextLeaf?next.text.length:next.children.length)<<1)}}}}next(skip=0){if(skip<0){this.nextInner(-skip,-this.dir);skip=this.value.length}return this.nextInner(skip,this.dir)}}class PartialTextCursor{constructor(text,start,end){this.value="";this.done=false;this.cursor=new RawTextCursor(text,start>end?-1:1);this.pos=start>end?text.length:0;this.from=Math.min(start,end);this.to=Math.max(start,end)}nextInner(skip,dir){if(dir<0?this.pos<=this.from:this.pos>=this.to){this.value="";this.done=true;return this}skip+=Math.max(0,dir<0?this.pos-this.to:this.from-this.pos);let limit=dir<0?this.pos-this.from:this.to-this.pos;if(skip>limit)skip=limit;limit-=skip;let{value}=this.cursor.next(skip);this.pos+=(value.length+skip)*dir;this.value=value.length<=limit?value:dir<0?value.slice(value.length-limit):value.slice(0,limit);this.done=!this.value;return this}next(skip=0){if(skip<0)skip=Math.max(skip,this.from-this.pos);else if(skip>0)skip=Math.min(skip,this.to-this.pos);return this.nextInner(skip,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class LineCursor{constructor(inner){this.inner=inner;this.afterBreak=true;this.value="";this.done=false}next(skip=0){let{done,lineBreak,value}=this.inner.next(skip);if(done){this.done=true;this.value=""}else if(lineBreak){if(this.afterBreak){this.value=""}else{this.afterBreak=true;this.next()}}else{this.value=value;this.afterBreak=false}return this}get lineBreak(){return false}}if(typeof Symbol!="undefined"){Text.prototype[Symbol.iterator]=function(){return this.iter()};RawTextCursor.prototype[Symbol.iterator]=PartialTextCursor.prototype[Symbol.iterator]=LineCursor.prototype[Symbol.iterator]=function(){return this}}class Line{constructor(from,to,number,text){this.from=from;this.to=to;this.number=number;this.text=text}get length(){return this.to-this.from}}let extend="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s=>s?parseInt(s,36):1);for(let i=1;icode)return extend[i-1]<=code;return false}function isRegionalIndicator(code){return code>=127462&&code<=127487}const ZWJ=8205;function findClusterBreak(str,pos,forward=true,includeExtending=true){return(forward?nextClusterBreak:prevClusterBreak)(str,pos,includeExtending)}function nextClusterBreak(str,pos,includeExtending){if(pos==str.length)return pos;if(pos&&surrogateLow(str.charCodeAt(pos))&&surrogateHigh(str.charCodeAt(pos-1)))pos--;let prev=codePointAt(str,pos);pos+=codePointSize(prev);while(pos=0&&isRegionalIndicator(codePointAt(str,i))){countBefore++;i-=2}if(countBefore%2==0)break;else pos+=2}else{break}}return pos}function prevClusterBreak(str,pos,includeExtending){while(pos>0){let found=nextClusterBreak(str,pos-2,includeExtending);if(found=56320&&ch<57344}function surrogateHigh(ch){return ch>=55296&&ch<56320}function codePointAt(str,pos){let code0=str.charCodeAt(pos);if(!surrogateHigh(code0)||pos+1==str.length)return code0;let code1=str.charCodeAt(pos+1);if(!surrogateLow(code1))return code0;return(code0-55296<<10)+(code1-56320)+65536}function fromCodePoint(code){if(code<=65535)return String.fromCharCode(code);code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}function codePointSize(code){return code<65536?1:2}const DefaultSplit=/\r\n?|\n/;var MapMode=function(MapMode){MapMode[MapMode["Simple"]=0]="Simple";MapMode[MapMode["TrackDel"]=1]="TrackDel";MapMode[MapMode["TrackBefore"]=2]="TrackBefore";MapMode[MapMode["TrackAfter"]=3]="TrackAfter";return MapMode}(MapMode||(MapMode={}));class ChangeDesc{constructor(sections){this.sections=sections}get length(){let result=0;for(let i=0;ipos)return posB+(pos-posA);posB+=len}else{if(mode!=MapMode.Simple&&endA>=pos&&(mode==MapMode.TrackDel&&posApos||mode==MapMode.TrackBefore&&posApos))return null;if(endA>pos||endA==pos&&assoc<0&&!len)return pos==posA||assoc<0?posB:posB+ins;posB+=ins}posA=endA}if(pos>posA)throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);return posB}touchesRange(from,to=from){for(let i=0,pos=0;i=0&&pos<=to&&end>=from)return posto?"cover":true;pos=end}return false}toString(){let result="";for(let i=0;i=0?":"+ins:"")}return result}toJSON(){return this.sections}static fromJSON(json){if(!Array.isArray(json)||json.length%2||json.some(a=>typeof a!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new ChangeDesc(json)}static create(sections){return new ChangeDesc(sections)}}class ChangeSet extends ChangeDesc{constructor(sections,inserted){super(sections);this.inserted=inserted}apply(doc){if(this.length!=doc.length)throw new RangeError("Applying change set to a document with the wrong length");iterChanges(this,(fromA,toA,fromB,_toB,text)=>doc=doc.replace(fromB,fromB+(toA-fromA),text),false);return doc}mapDesc(other,before=false){return mapSet(this,other,before,true)}invert(doc){let sections=this.sections.slice(),inserted=[];for(let i=0,pos=0;i=0){sections[i]=ins;sections[i+1]=len;let index=i>>1;while(inserted.length0)addInsert(resultInserted,resultSections,iter.text);iter.forward(len);pos+=len}let end=ranges[i++];while(pos>1].toJSON()))}return parts}static of(changes,length,lineSep){let sections=[],inserted=[],pos=0;let total=null;function flush(force=false){if(!force&&!sections.length)return;if(posto||from<0||to>length)throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);let insText=!insert?Text.empty:typeof insert=="string"?Text.of(insert.split(lineSep||DefaultSplit)):insert;let insLen=insText.length;if(from==to&&insLen==0)return;if(frompos)addSection(sections,from-pos,-1);addSection(sections,to-from,insLen);addInsert(inserted,sections,insText);pos=to}}process(changes);flush(!total);return total}static empty(length){return new ChangeSet(length?[length,-1]:[],[])}static fromJSON(json){if(!Array.isArray(json))throw new RangeError("Invalid JSON representation of ChangeSet");let sections=[],inserted=[];for(let i=0;ii&&typeof e!="string")){throw new RangeError("Invalid JSON representation of ChangeSet")}else if(part.length==1){sections.push(part[0],0)}else{while(inserted.length=0&&ins<=0&&ins==sections[last+1])sections[last]+=len;else if(len==0&§ions[last]==0)sections[last+1]+=ins;else if(forceJoin){sections[last]+=len;sections[last+1]+=ins}else sections.push(len,ins)}function addInsert(values,sections,value){if(value.length==0)return;let index=sections.length-2>>1;if(index>1]);if(individual||i==desc.sections.length||desc.sections[i+1]<0)break;len=desc.sections[i++];ins=desc.sections[i++]}f(posA,endA,posB,endB,text);posA=endA;posB=endB}}}function mapSet(setA,setB,before,mkSet=false){let sections=[],insert=mkSet?[]:null;let a=new SectionIter(setA),b=new SectionIter(setB);for(let inserted=-1;;){if(a.ins==-1&&b.ins==-1){let len=Math.min(a.len,b.len);addSection(sections,len,-1);a.forward(len);b.forward(len)}else if(b.ins>=0&&(a.ins<0||inserted==a.i||a.off==0&&(b.len=0&&inserted=0){let len=0,left=a.len;while(left){if(b.ins==-1){let piece=Math.min(left,b.len);len+=piece;left-=piece;b.forward(piece)}else if(b.ins==0&&b.lenlen||b.ins>=0&&b.len>len)&&(open||sections.length>sectionLen);a.forward2(len);b.forward(len)}}}class SectionIter{constructor(set){this.set=set;this.i=0;this.next()}next(){let{sections}=this.set;if(this.i>1;return index>=inserted.length?Text.empty:inserted[index]}textBit(len){let{inserted}=this.set,index=this.i-2>>1;return index>=inserted.length&&!len?Text.empty:inserted[index].slice(this.off,len==null?undefined:this.off+len)}forward(len){if(len==this.len)this.next();else{this.len-=len;this.off+=len}}forward2(len){if(this.ins==-1)this.forward(len);else if(len==this.ins)this.next();else{this.ins-=len;this.off+=len}}}class SelectionRange{constructor(from,to,flags){this.from=from;this.to=to;this.flags=flags}get anchor(){return this.flags&16?this.to:this.from}get head(){return this.flags&16?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&4?-1:this.flags&8?1:0}get bidiLevel(){let level=this.flags&3;return level==3?null:level}get goalColumn(){let value=this.flags>>5;return value==33554431?undefined:value}map(change,assoc=-1){let from,to;if(this.empty){from=to=change.mapPos(this.from,assoc)}else{from=change.mapPos(this.from,1);to=change.mapPos(this.to,-1)}return from==this.from&&to==this.to?this:new SelectionRange(from,to,this.flags)}extend(from,to=from){if(from<=this.anchor&&to>=this.anchor)return EditorSelection.range(from,to);let head=Math.abs(from-this.anchor)>Math.abs(to-this.anchor)?from:to;return EditorSelection.range(this.anchor,head)}eq(other){return this.anchor==other.anchor&&this.head==other.head}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(json){if(!json||typeof json.anchor!="number"||typeof json.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return EditorSelection.range(json.anchor,json.head)}static create(from,to,flags){return new SelectionRange(from,to,flags)}}class EditorSelection{constructor(ranges,mainIndex){this.ranges=ranges;this.mainIndex=mainIndex}map(change,assoc=-1){if(change.empty)return this;return EditorSelection.create(this.ranges.map(r=>r.map(change,assoc)),this.mainIndex)}eq(other){if(this.ranges.length!=other.ranges.length||this.mainIndex!=other.mainIndex)return false;for(let i=0;ir.toJSON()),main:this.mainIndex}}static fromJSON(json){if(!json||!Array.isArray(json.ranges)||typeof json.main!="number"||json.main>=json.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new EditorSelection(json.ranges.map(r=>SelectionRange.fromJSON(r)),json.main)}static single(anchor,head=anchor){return new EditorSelection([EditorSelection.range(anchor,head)],0)}static create(ranges,mainIndex=0){if(ranges.length==0)throw new RangeError("A selection needs at least one range");for(let pos=0,i=0;ianchor?4:0))}static normalized(ranges,mainIndex=0){let main=ranges[mainIndex];ranges.sort((a,b)=>a.from-b.from);mainIndex=ranges.indexOf(main);for(let i=1;irange.head?EditorSelection.range(to,from):EditorSelection.range(from,to))}}return new EditorSelection(ranges,mainIndex)}}function checkSelection(selection,docLength){for(let range of selection.ranges)if(range.to>docLength)throw new RangeError("Selection points outside of document")}let nextID=0;class Facet{constructor(combine,compareInput,compare,isStatic,enables){this.combine=combine;this.compareInput=compareInput;this.compare=compare;this.isStatic=isStatic;this.id=nextID++;this.default=combine([]);this.extensions=typeof enables=="function"?enables(this):enables}static define(config={}){return new Facet(config.combine||(a=>a),config.compareInput||((a,b)=>a===b),config.compare||(!config.combine?sameArray:(a,b)=>a===b),!!config.static,config.enables)}of(value){return new FacetProvider([],this,0,value)}compute(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,1,get)}computeN(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,2,get)}from(field,get){if(!get)get=x=>x;return this.compute([field],state=>get(state.field(field)))}}function sameArray(a,b){return a==b||a.length==b.length&&a.every((e,i)=>e===b[i])}class FacetProvider{constructor(dependencies,facet,type,value){this.dependencies=dependencies;this.facet=facet;this.type=type;this.value=value;this.id=nextID++}dynamicSlot(addresses){var _a;let getter=this.value;let compare=this.facet.compareInput;let id=this.id,idx=addresses[id]>>1,multi=this.type==2;let depDoc=false,depSel=false,depAddrs=[];for(let dep of this.dependencies){if(dep=="doc")depDoc=true;else if(dep=="selection")depSel=true;else if((((_a=addresses[dep.id])!==null&&_a!==void 0?_a:1)&1)==0)depAddrs.push(addresses[dep.id])}return{create(state){state.values[idx]=getter(state);return 1},update(state,tr){if(depDoc&&tr.docChanged||depSel&&(tr.docChanged||tr.selection)||ensureAll(state,depAddrs)){let newVal=getter(state);if(multi?!compareArray(newVal,state.values[idx],compare):!compare(newVal,state.values[idx])){state.values[idx]=newVal;return 1}}return 0},reconfigure:(state,oldState)=>{let newVal=getter(state);let oldAddr=oldState.config.address[id];if(oldAddr!=null){let oldVal=getAddr(oldState,oldAddr);if(this.dependencies.every(dep=>{return dep instanceof Facet?oldState.facet(dep)===state.facet(dep):dep instanceof StateField?oldState.field(dep,false)==state.field(dep,false):true})||(multi?compareArray(newVal,oldVal,compare):compare(newVal,oldVal))){state.values[idx]=oldVal;return 0}}state.values[idx]=newVal;return 1}}}}function compareArray(a,b,compare){if(a.length!=b.length)return false;for(let i=0;iaddresses[p.id]);let providerTypes=providers.map(p=>p.type);let dynamic=providerAddrs.filter(p=>!(p&1));let idx=addresses[facet.id]>>1;function get(state){let values=[];for(let i=0;ia===b),config);if(config.provide)field.provides=config.provide(field);return field}create(state){let init=state.facet(initField).find(i=>i.field==this);return((init===null||init===void 0?void 0:init.create)||this.createF)(state)}slot(addresses){let idx=addresses[this.id]>>1;return{create:state=>{state.values[idx]=this.create(state);return 1},update:(state,tr)=>{let oldVal=state.values[idx];let value=this.updateF(oldVal,tr);if(this.compareF(oldVal,value))return 0;state.values[idx]=value;return 1},reconfigure:(state,oldState)=>{if(oldState.config.address[this.id]!=null){state.values[idx]=oldState.field(this);return 0}state.values[idx]=this.create(state);return 1}}}init(create){return[this,initField.of({field:this,create:create})]}get extension(){return this}}const Prec_={lowest:4,low:3,default:2,high:1,highest:0};function prec(value){return ext=>new PrecExtension(ext,value)}const Prec={highest:prec(Prec_.highest),high:prec(Prec_.high),default:prec(Prec_.default),low:prec(Prec_.low),lowest:prec(Prec_.lowest)};class PrecExtension{constructor(inner,prec){this.inner=inner;this.prec=prec}}class Compartment{of(ext){return new CompartmentInstance(this,ext)}reconfigure(content){return Compartment.reconfigure.of({compartment:this,extension:content})}get(state){return state.config.compartments.get(this)}}class CompartmentInstance{constructor(compartment,inner){this.compartment=compartment;this.inner=inner}}class Configuration{constructor(base,compartments,dynamicSlots,address,staticValues,facets){this.base=base;this.compartments=compartments;this.dynamicSlots=dynamicSlots;this.address=address;this.staticValues=staticValues;this.facets=facets;this.statusTemplate=[];while(this.statusTemplate.length>1]}static resolve(base,compartments,oldState){let fields=[];let facets=Object.create(null);let newCompartments=new Map;for(let ext of flatten(base,compartments,newCompartments)){if(ext instanceof StateField)fields.push(ext);else(facets[ext.facet.id]||(facets[ext.facet.id]=[])).push(ext)}let address=Object.create(null);let staticValues=[];let dynamicSlots=[];for(let field of fields){address[field.id]=dynamicSlots.length<<1;dynamicSlots.push(a=>field.slot(a))}let oldFacets=oldState===null||oldState===void 0?void 0:oldState.config.facets;for(let id in facets){let providers=facets[id],facet=providers[0].facet;let oldProviders=oldFacets&&oldFacets[id]||[];if(providers.every(p=>p.type==0)){address[facet.id]=staticValues.length<<1|1;if(sameArray(oldProviders,providers)){staticValues.push(oldState.facet(facet))}else{let value=facet.combine(providers.map(p=>p.value));staticValues.push(oldState&&facet.compare(value,oldState.facet(facet))?oldState.facet(facet):value)}}else{for(let p of providers){if(p.type==0){address[p.id]=staticValues.length<<1|1;staticValues.push(p.value)}else{address[p.id]=dynamicSlots.length<<1;dynamicSlots.push(a=>p.dynamicSlot(a))}}address[facet.id]=dynamicSlots.length<<1;dynamicSlots.push(a=>dynamicFacetSlot(a,facet,providers))}}let dynamic=dynamicSlots.map(f=>f(address));return new Configuration(base,newCompartments,dynamic,address,staticValues,facets)}}function flatten(extension,compartments,newCompartments){let result=[[],[],[],[],[]];let seen=new Map;function inner(ext,prec){let known=seen.get(ext);if(known!=null){if(known<=prec)return;let found=result[known].indexOf(ext);if(found>-1)result[known].splice(found,1);if(ext instanceof CompartmentInstance)newCompartments.delete(ext.compartment)}seen.set(ext,prec);if(Array.isArray(ext)){for(let e of ext)inner(e,prec)}else if(ext instanceof CompartmentInstance){if(newCompartments.has(ext.compartment))throw new RangeError(`Duplicate use of compartment in extensions`);let content=compartments.get(ext.compartment)||ext.inner;newCompartments.set(ext.compartment,content);inner(content,prec)}else if(ext instanceof PrecExtension){inner(ext.inner,ext.prec)}else if(ext instanceof StateField){result[prec].push(ext);if(ext.provides)inner(ext.provides,prec)}else if(ext instanceof FacetProvider){result[prec].push(ext);if(ext.facet.extensions)inner(ext.facet.extensions,Prec_.default)}else{let content=ext.extension;if(!content)throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);inner(content,prec)}}inner(extension,Prec_.default);return result.reduce((a,b)=>a.concat(b))}function ensureAddr(state,addr){if(addr&1)return 2;let idx=addr>>1;let status=state.status[idx];if(status==4)throw new Error("Cyclic dependency between fields and/or facets");if(status&2)return status;state.status[idx]=4;let changed=state.computeSlot(state,state.config.dynamicSlots[idx]);return state.status[idx]=2|changed}function getAddr(state,addr){return addr&1?state.config.staticValues[addr>>1]:state.values[addr>>1]}const languageData=Facet.define();const allowMultipleSelections=Facet.define({combine:values=>values.some(v=>v),static:true});const lineSeparator=Facet.define({combine:values=>values.length?values[0]:undefined,static:true});const changeFilter=Facet.define();const transactionFilter=Facet.define();const transactionExtender=Facet.define();const readOnly=Facet.define({combine:values=>values.length?values[0]:false});class Annotation{constructor(type,value){this.type=type;this.value=value}static define(){return new AnnotationType}}class AnnotationType{of(value){return new Annotation(this,value)}}class StateEffectType{constructor(map){this.map=map}of(value){return new StateEffect(this,value)}}class StateEffect{constructor(type,value){this.type=type;this.value=value}map(mapping){let mapped=this.type.map(this.value,mapping);return mapped===undefined?undefined:mapped==this.value?this:new StateEffect(this.type,mapped)}is(type){return this.type==type}static define(spec={}){return new StateEffectType(spec.map||(v=>v))}static mapEffects(effects,mapping){if(!effects.length)return effects;let result=[];for(let effect of effects){let mapped=effect.map(mapping);if(mapped)result.push(mapped)}return result}}StateEffect.reconfigure=StateEffect.define();StateEffect.appendConfig=StateEffect.define();class Transaction{constructor(startState,changes,selection,effects,annotations,scrollIntoView){this.startState=startState;this.changes=changes;this.selection=selection;this.effects=effects;this.annotations=annotations;this.scrollIntoView=scrollIntoView;this._doc=null;this._state=null;if(selection)checkSelection(selection,changes.newLength);if(!annotations.some(a=>a.type==Transaction.time))this.annotations=annotations.concat(Transaction.time.of(Date.now()))}static create(startState,changes,selection,effects,annotations,scrollIntoView){return new Transaction(startState,changes,selection,effects,annotations,scrollIntoView)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){if(!this._state)this.startState.applyTransaction(this);return this._state}annotation(type){for(let ann of this.annotations)if(ann.type==type)return ann.value;return undefined}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(event){let e=this.annotation(Transaction.userEvent);return!!(e&&(e==event||e.length>event.length&&e.slice(0,event.length)==event&&e[event.length]=="."))}}Transaction.time=Annotation.define();Transaction.userEvent=Annotation.define();Transaction.addToHistory=Annotation.define();Transaction.remote=Annotation.define();function joinRanges(a,b){let result=[];for(let iA=0,iB=0;;){let from,to;if(iA=a[iA])){from=a[iA++];to=a[iA++]}else if(iB=0;i--){let filtered=filters[i](tr);if(filtered instanceof Transaction)tr=filtered;else if(Array.isArray(filtered)&&filtered.length==1&&filtered[0]instanceof Transaction)tr=filtered[0];else tr=resolveTransaction(state,asArray(filtered),false)}return tr}function extendTransaction(tr){let state=tr.startState,extenders=state.facet(transactionExtender),spec=tr;for(let i=extenders.length-1;i>=0;i--){let extension=extenders[i](tr);if(extension&&Object.keys(extension).length)spec=mergeTransaction(spec,resolveTransactionInner(state,extension,tr.changes.newLength),true)}return spec==tr?tr:Transaction.create(state,tr.changes,tr.selection,spec.effects,spec.annotations,spec.scrollIntoView)}const none=[];function asArray(value){return value==null?none:Array.isArray(value)?value:[value]}var CharCategory=function(CharCategory){CharCategory[CharCategory["Word"]=0]="Word";CharCategory[CharCategory["Space"]=1]="Space";CharCategory[CharCategory["Other"]=2]="Other";return CharCategory}(CharCategory||(CharCategory={}));const nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let wordChar;try{wordChar=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch(_){}function hasWordChar(str){if(wordChar)return wordChar.test(str);for(let i=0;i""&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch)))return true}return false}function makeCategorizer(wordChars){return char=>{if(!/\S/.test(char))return CharCategory.Space;if(hasWordChar(char))return CharCategory.Word;for(let i=0;i-1)return CharCategory.Word;return CharCategory.Other}}class EditorState{constructor(config,doc,selection,values,computeSlot,tr){this.config=config;this.doc=doc;this.selection=selection;this.values=values;this.status=config.statusTemplate.slice();this.computeSlot=computeSlot;if(tr)tr._state=this;for(let i=0;icompartments.set(key,val));conf=null}compartments.set(effect.value.compartment,effect.value.extension)}else if(effect.is(StateEffect.reconfigure)){conf=null;base=effect.value}else if(effect.is(StateEffect.appendConfig)){conf=null;base=asArray(base).concat(effect.value)}}let startValues;if(!conf){conf=Configuration.resolve(base,compartments,this);let intermediateState=new EditorState(conf,this.doc,this.selection,conf.dynamicSlots.map(()=>null),(state,slot)=>slot.reconfigure(state,this),null);startValues=intermediateState.values}else{startValues=tr.startState.values.slice()}new EditorState(conf,tr.newDoc,tr.newSelection,startValues,(state,slot)=>slot.update(state,tr),tr)}replaceSelection(text){if(typeof text=="string")text=this.toText(text);return this.changeByRange(range=>({changes:{from:range.from,to:range.to,insert:text},range:EditorSelection.cursor(range.from+text.length)}))}changeByRange(f){let sel=this.selection;let result1=f(sel.ranges[0]);let changes=this.changes(result1.changes),ranges=[result1.range];let effects=asArray(result1.effects);for(let i=1;ifield.spec.fromJSON(value,state)))}}return EditorState.create({doc:json.doc,selection:EditorSelection.fromJSON(json.selection),extensions:config.extensions?fieldInit.concat([config.extensions]):fieldInit})}static create(config={}){let configuration=Configuration.resolve(config.extensions||[],new Map);let doc=config.doc instanceof Text?config.doc:Text.of((config.doc||"").split(configuration.staticFacet(EditorState.lineSeparator)||DefaultSplit));let selection=!config.selection?EditorSelection.single(0):config.selection instanceof EditorSelection?config.selection:EditorSelection.single(config.selection.anchor,config.selection.head);checkSelection(selection,doc.length);if(!configuration.staticFacet(allowMultipleSelections))selection=selection.asSingle();return new EditorState(configuration,doc,selection,configuration.dynamicSlots.map(()=>null),(state,slot)=>slot.create(state),null)}get tabSize(){return this.facet(EditorState.tabSize)}get lineBreak(){return this.facet(EditorState.lineSeparator)||"\n"}get readOnly(){return this.facet(readOnly)}phrase(phrase,...insert){for(let map of this.facet(EditorState.phrases))if(Object.prototype.hasOwnProperty.call(map,phrase)){phrase=map[phrase];break}if(insert.length)phrase=phrase.replace(/\$(\$|\d*)/g,(m,i)=>{if(i=="$")return"$";let n=+(i||1);return!n||n>insert.length?m:insert[n-1]});return phrase}languageDataAt(name,pos,side=-1){let values=[];for(let provider of this.facet(languageData)){for(let result of provider(this,pos,side)){if(Object.prototype.hasOwnProperty.call(result,name))values.push(result[name])}}return values}charCategorizer(at){return makeCategorizer(this.languageDataAt("wordChars",at).join(""))}wordAt(pos){let{text,from,length}=this.doc.lineAt(pos);let cat=this.charCategorizer(pos);let start=pos-from,end=pos-from;while(start>0){let prev=findClusterBreak(text,start,false);if(cat(text.slice(prev,start))!=CharCategory.Word)break;start=prev}while(endvalues.length?values[0]:4});EditorState.lineSeparator=lineSeparator;EditorState.readOnly=readOnly;EditorState.phrases=Facet.define({compare(a,b){let kA=Object.keys(a),kB=Object.keys(b);return kA.length==kB.length&&kA.every(k=>a[k]==b[k])}});EditorState.languageData=languageData;EditorState.changeFilter=changeFilter;EditorState.transactionFilter=transactionFilter;EditorState.transactionExtender=transactionExtender;Compartment.reconfigure=StateEffect.define();function combineConfig(configs,defaults,combine={}){let result={};for(let config of configs)for(let key of Object.keys(config)){let value=config[key],current=result[key];if(current===undefined)result[key]=value;else if(current===value||value===undefined);else if(Object.hasOwnProperty.call(combine,key))result[key]=combine[key](current,value);else throw new Error("Config merge conflict for field "+key)}for(let key in defaults)if(result[key]===undefined)result[key]=defaults[key];return result}class RangeValue{eq(other){return this==other}range(from,to=from){return Range.create(from,to,this)}}RangeValue.prototype.startSide=RangeValue.prototype.endSide=0;RangeValue.prototype.point=false;RangeValue.prototype.mapMode=MapMode.TrackDel;class Range{constructor(from,to,value){this.from=from;this.to=to;this.value=value}static create(from,to,value){return new Range(from,to,value)}}function cmpRange(a,b){return a.from-b.from||a.value.startSide-b.value.startSide}class Chunk{constructor(from,to,value,maxPoint){this.from=from;this.to=to;this.value=value;this.maxPoint=maxPoint}get length(){return this.to[this.to.length-1]}findIndex(pos,side,end,startAt=0){let arr=end?this.to:this.from;for(let lo=startAt,hi=arr.length;;){if(lo==hi)return lo;let mid=lo+hi>>1;let diff=arr[mid]-pos||(end?this.value[mid].endSide:this.value[mid].startSide)-side;if(mid==lo)return diff>=0?lo:hi;if(diff>=0)hi=mid;else lo=mid+1}}between(offset,from,to,f){for(let i=this.findIndex(from,-1e9,true),e=this.findIndex(to,1e9,false,i);inewTo||newFrom==newTo&&val.startSide>0&&val.endSide<=0)continue}if((newTo-newFrom||val.endSide-val.startSide)<0)continue;if(newPos<0)newPos=newFrom;if(val.point)maxPoint=Math.max(maxPoint,newTo-newFrom);value.push(val);from.push(newFrom-newPos);to.push(newTo-newPos)}return{mapped:value.length?new Chunk(from,to,value,maxPoint):null,pos:newPos}}}class RangeSet{constructor(chunkPos,chunk,nextLayer,maxPoint){this.chunkPos=chunkPos;this.chunk=chunk;this.nextLayer=nextLayer;this.maxPoint=maxPoint}static create(chunkPos,chunk,nextLayer,maxPoint){return new RangeSet(chunkPos,chunk,nextLayer,maxPoint)}get length(){let last=this.chunk.length-1;return last<0?0:Math.max(this.chunkEnd(last),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let size=this.nextLayer.size;for(let chunk of this.chunk)size+=chunk.value.length;return size}chunkEnd(index){return this.chunkPos[index]+this.chunk[index].length}update(updateSpec){let{add=[],sort=false,filterFrom=0,filterTo=this.length}=updateSpec;let filter=updateSpec.filter;if(add.length==0&&!filter)return this;if(sort)add=add.slice().sort(cmpRange);if(this.isEmpty)return add.length?RangeSet.of(add):this;let cur=new LayerCursor(this,null,-1).goto(0),i=0,spill=[];let builder=new RangeSetBuilder;while(cur.value||i=0){let range=add[i++];if(!builder.addInner(range.from,range.to,range.value))spill.push(range)}else if(cur.rangeIndex==1&&cur.chunkIndexthis.chunkEnd(cur.chunkIndex)||filterTocur.to||filterTo=start&&from<=start+chunk.length&&chunk.between(start,from-start,to-start,f)===false)return}this.nextLayer.between(from,to,f)}iter(from=0){return HeapCursor.from([this]).goto(from)}get isEmpty(){return this.nextLayer==this}static iter(sets,from=0){return HeapCursor.from(sets).goto(from)}static compare(oldSets,newSets,textDiff,comparator,minPointSize=-1){let a=oldSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize);let b=newSets.filter(set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize);let sharedChunks=findSharedChunks(a,b,textDiff);let sideA=new SpanCursor(a,sharedChunks,minPointSize);let sideB=new SpanCursor(b,sharedChunks,minPointSize);textDiff.iterGaps((fromA,fromB,length)=>compare(sideA,fromA,sideB,fromB,length,comparator));if(textDiff.empty&&textDiff.length==0)compare(sideA,0,sideB,0,0,comparator)}static eq(oldSets,newSets,from=0,to){if(to==null)to=1e9;let a=oldSets.filter(set=>!set.isEmpty&&newSets.indexOf(set)<0);let b=newSets.filter(set=>!set.isEmpty&&oldSets.indexOf(set)<0);if(a.length!=b.length)return false;if(!a.length)return true;let sharedChunks=findSharedChunks(a,b);let sideA=new SpanCursor(a,sharedChunks,0).goto(from),sideB=new SpanCursor(b,sharedChunks,0).goto(from);for(;;){if(sideA.to!=sideB.to||!sameValues(sideA.active,sideB.active)||sideA.point&&(!sideB.point||!sideA.point.eq(sideB.point)))return false;if(sideA.to>to)return true;sideA.next();sideB.next()}}static spans(sets,from,to,iterator,minPointSize=-1){let cursor=new SpanCursor(sets,null,minPointSize).goto(from),pos=from;let open=cursor.openStart;for(;;){let curTo=Math.min(cursor.to,to);if(cursor.point){iterator.point(pos,curTo,cursor.point,cursor.activeForPoint(cursor.to),open,cursor.pointRank);open=cursor.openEnd(curTo)+(cursor.to>curTo?1:0)}else if(curTo>pos){iterator.span(pos,curTo,cursor.active,open);open=cursor.openEnd(curTo)}if(cursor.to>to)break;pos=cursor.to;cursor.next()}return open}static of(ranges,sort=false){let build=new RangeSetBuilder;for(let range of ranges instanceof Range?[ranges]:sort?lazySort(ranges):ranges)build.add(range.from,range.to,range.value);return build.finish()}}RangeSet.empty=new RangeSet([],[],null,-1);function lazySort(ranges){if(ranges.length>1)for(let prev=ranges[0],i=1;i0)return ranges.slice().sort(cmpRange);prev=cur}return ranges}RangeSet.empty.nextLayer=RangeSet.empty;class RangeSetBuilder{constructor(){this.chunks=[];this.chunkPos=[];this.chunkStart=-1;this.last=null;this.lastFrom=-1e9;this.lastTo=-1e9;this.from=[];this.to=[];this.value=[];this.maxPoint=-1;this.setMaxPoint=-1;this.nextLayer=null}finishChunk(newArrays){this.chunks.push(new Chunk(this.from,this.to,this.value,this.maxPoint));this.chunkPos.push(this.chunkStart);this.chunkStart=-1;this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint);this.maxPoint=-1;if(newArrays){this.from=[];this.to=[];this.value=[]}}add(from,to,value){if(!this.addInner(from,to,value))(this.nextLayer||(this.nextLayer=new RangeSetBuilder)).add(from,to,value)}addInner(from,to,value){let diff=from-this.lastTo||value.startSide-this.last.endSide;if(diff<=0&&(from-this.lastFrom||value.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");if(diff<0)return false;if(this.from.length==250)this.finishChunk(true);if(this.chunkStart<0)this.chunkStart=from;this.from.push(from-this.chunkStart);this.to.push(to-this.chunkStart);this.last=value;this.lastFrom=from;this.lastTo=to;this.value.push(value);if(value.point)this.maxPoint=Math.max(this.maxPoint,to-from);return true}addChunk(from,chunk){if((from-this.lastTo||chunk.value[0].startSide-this.last.endSide)<0)return false;if(this.from.length)this.finishChunk(true);this.setMaxPoint=Math.max(this.setMaxPoint,chunk.maxPoint);this.chunks.push(chunk);this.chunkPos.push(from);let last=chunk.value.length-1;this.last=chunk.value[last];this.lastFrom=chunk.from[last]+from;this.lastTo=chunk.to[last]+from;return true}finish(){return this.finishInner(RangeSet.empty)}finishInner(next){if(this.from.length)this.finishChunk(false);if(this.chunks.length==0)return next;let result=RangeSet.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(next):next,this.setMaxPoint);this.from=null;return result}}function findSharedChunks(a,b,textDiff){let inA=new Map;for(let set of a)for(let i=0;i=this.minPoint)break}}}setRangeIndex(index){if(index==this.layer.chunk[this.chunkIndex].value.length){this.chunkIndex++;if(this.skip){while(this.chunkIndex=minPoint)heap.push(new LayerCursor(cur,skip,minPoint,i))}}return heap.length==1?heap[0]:new HeapCursor(heap)}get startSide(){return this.value?this.value.startSide:0}goto(pos,side=-1e9){for(let cur of this.heap)cur.goto(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);this.next();return this}forward(pos,side){for(let cur of this.heap)cur.forward(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);if((this.to-pos||this.value.endSide-side)<0)this.next()}next(){if(this.heap.length==0){this.from=this.to=1e9;this.value=null;this.rank=-1}else{let top=this.heap[0];this.from=top.from;this.to=top.to;this.value=top.value;this.rank=top.rank;if(top.value)top.next();heapBubble(this.heap,0)}}}function heapBubble(heap,index){for(let cur=heap[index];;){let childIndex=(index<<1)+1;if(childIndex>=heap.length)break;let child=heap[childIndex];if(childIndex+1=0){child=heap[childIndex+1];childIndex++}if(cur.compare(child)<0)break;heap[childIndex]=cur;heap[index]=child;index=childIndex}}class SpanCursor{constructor(sets,skip,minPoint){this.minPoint=minPoint;this.active=[];this.activeTo=[];this.activeRank=[];this.minActive=-1;this.point=null;this.pointFrom=0;this.pointRank=0;this.to=-1e9;this.endSide=0;this.openStart=-1;this.cursor=HeapCursor.from(sets,skip,minPoint)}goto(pos,side=-1e9){this.cursor.goto(pos,side);this.active.length=this.activeTo.length=this.activeRank.length=0;this.minActive=-1;this.to=pos;this.endSide=side;this.openStart=-1;this.next();return this}forward(pos,side){while(this.minActive>-1&&(this.activeTo[this.minActive]-pos||this.active[this.minActive].endSide-side)<0)this.removeActive(this.minActive);this.cursor.forward(pos,side)}removeActive(index){remove(this.active,index);remove(this.activeTo,index);remove(this.activeRank,index);this.minActive=findMinIndex(this.active,this.activeTo)}addActive(trackOpen){let i=0,{value,to,rank}=this.cursor;while(i-1&&(this.activeTo[a]-this.cursor.from||this.active[a].endSide-this.cursor.startSide)<0){if(this.activeTo[a]>from){this.to=this.activeTo[a];this.endSide=this.active[a].endSide;break}this.removeActive(a);if(trackOpen)remove(trackOpen,a)}else if(!this.cursor.value){this.to=this.endSide=1e9;break}else if(this.cursor.from>from){this.to=this.cursor.from;this.endSide=this.cursor.startSide;break}else{let nextVal=this.cursor.value;if(!nextVal.point){this.addActive(trackOpen);if(this.cursor.fromfrom)trackExtra++;this.cursor.next()}else if(wasPoint&&this.cursor.to==this.to&&this.cursor.from=0;i--){if(this.activeRank[i]to||this.activeTo[i]==to&&this.active[i].endSide>=this.point.endSide)active.push(this.active[i])}return active.reverse()}openEnd(to){let open=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>to;i--)open++;return open}}function compare(a,startA,b,startB,length,comparator){a.goto(startA);b.goto(startB);let endB=startB+length;let pos=startB,dPos=startB-startA;for(;;){let diff=a.to+dPos-b.to||a.endSide-b.endSide;let end=diff<0?a.to+dPos:b.to,clipEnd=Math.min(end,endB);if(a.point||b.point){if(!(a.point&&b.point&&(a.point==b.point||a.point.eq(b.point))&&sameValues(a.activeForPoint(a.to+dPos),b.activeForPoint(b.to))))comparator.comparePoint(pos,clipEnd,a.point,b.point)}else{if(clipEnd>pos&&!sameValues(a.active,b.active))comparator.compareRange(pos,clipEnd,a.active,b.active)}if(end>endB)break;pos=end;if(diff<=0)a.next();if(diff>=0)b.next()}}function sameValues(a,b){if(a.length!=b.length)return false;for(let i=0;i=index;i--)array[i+1]=array[i];array[index]=value}function findMinIndex(value,array){let found=-1,foundPos=1e9;for(let i=0;i=col)return i;if(i==string.length)break;n+=string.charCodeAt(i)==9?tabSize-n%tabSize:1;i=findClusterBreak(string,i)}return strict===true?-1:string.length}export{Annotation,AnnotationType,ChangeDesc,ChangeSet,CharCategory,Compartment,EditorSelection,EditorState,Facet,Line,MapMode,Prec,Range,RangeSet,RangeSetBuilder,RangeValue,SelectionRange,StateEffect,StateEffectType,StateField,Text,Transaction,codePointAt,codePointSize,combineConfig,countColumn,findClusterBreak,findColumn,fromCodePoint};
\ No newline at end of file
diff --git a/public/js/@codemirror/view.js b/public/js/@codemirror/view.js
new file mode 100755
index 0000000..239c4c7
--- /dev/null
+++ b/public/js/@codemirror/view.js
@@ -0,0 +1 @@
+import{Text,RangeSet,MapMode,RangeValue,Facet,StateEffect,ChangeSet,findClusterBreak,EditorSelection,EditorState,findColumn,CharCategory,Prec,Transaction,codePointAt,codePointSize,combineConfig,StateField,RangeSetBuilder,countColumn}from"@codemirror/state";import{StyleModule}from"style-mod";import{keyName,base,shift}from"w3c-keyname";function getSelection(root){let target;if(root.nodeType==11){target=root.getSelection?root:root.ownerDocument}else{target=root}return target.getSelection()}function contains(dom,node){return node?dom==node||dom.contains(node.nodeType!=1?node.parentNode:node):false}function deepActiveElement(doc){let elt=doc.activeElement;while(elt&&elt.shadowRoot)elt=elt.shadowRoot.activeElement;return elt}function hasSelection(dom,selection){if(!selection.anchorNode)return false;try{return contains(dom,selection.anchorNode)}catch(_){return false}}function clientRectsFor(dom){if(dom.nodeType==3)return textRange(dom,0,dom.nodeValue.length).getClientRects();else if(dom.nodeType==1)return dom.getClientRects();else return[]}function isEquivalentPosition(node,off,targetNode,targetOff){return targetNode?scanFor(node,off,targetNode,targetOff,-1)||scanFor(node,off,targetNode,targetOff,1):false}function domIndex(node){for(var index=0;;index++){node=node.previousSibling;if(!node)return index}}function scanFor(node,off,targetNode,targetOff,dir){for(;;){if(node==targetNode&&off==targetOff)return true;if(off==(dir<0?0:maxOffset(node))){if(node.nodeName=="DIV")return false;let parent=node.parentNode;if(!parent||parent.nodeType!=1)return false;off=domIndex(node)+(dir<0?0:1);node=parent}else if(node.nodeType==1){node=node.childNodes[off+(dir<0?-1:0)];if(node.nodeType==1&&node.contentEditable=="false")return false;off=dir<0?maxOffset(node):0}else{return false}}}function maxOffset(node){return node.nodeType==3?node.nodeValue.length:node.childNodes.length}const Rect0={left:0,right:0,top:0,bottom:0};function flattenRect(rect,left){let x=left?rect.left:rect.right;return{left:x,right:x,top:rect.top,bottom:rect.bottom}}function windowRect(win){return{left:0,right:win.innerWidth,top:0,bottom:win.innerHeight}}function scrollRectIntoView(dom,rect,side,x,y,xMargin,yMargin,ltr){let doc=dom.ownerDocument,win=doc.defaultView||window;for(let cur=dom;cur;){if(cur.nodeType==1){let bounding,top=cur==doc.body;if(top){bounding=windowRect(win)}else{if(cur.scrollHeight<=cur.clientHeight&&cur.scrollWidth<=cur.clientWidth){cur=cur.assignedSlot||cur.parentNode;continue}let rect=cur.getBoundingClientRect();bounding={left:rect.left,right:rect.left+cur.clientWidth,top:rect.top,bottom:rect.top+cur.clientHeight}}let moveX=0,moveY=0;if(y=="nearest"){if(rect.top0&&rect.bottom>bounding.bottom+moveY)moveY=rect.bottom-bounding.bottom+moveY+yMargin}else if(rect.bottom>bounding.bottom){moveY=rect.bottom-bounding.bottom+yMargin;if(side<0&&rect.top-moveY0&&rect.right>bounding.right+moveX)moveX=rect.right-bounding.right+moveX+xMargin}else if(rect.right>bounding.right){moveX=rect.right-bounding.right+xMargin;if(side<0&&rect.leftto)return child.domBoundsAround(from,to,pos);if(end>=from&&fromI==-1){fromI=i;fromStart=pos}if(pos>to&&child.dom.parentNode==this.dom){toI=i;toEnd=prevEnd;break}prevEnd=end;pos=end+child.breakAfter}return{from:fromStart,to:toEnd<0?offset+this.length:toEnd,startDOM:(fromI?this.children[fromI-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:toI=0?this.children[toI].dom:null}}markDirty(andParent=false){this.dirty|=2;this.markParentsDirty(andParent)}markParentsDirty(childList){for(let parent=this.parent;parent;parent=parent.parent){if(childList)parent.dirty|=2;if(parent.dirty&1)return;parent.dirty|=1;childList=false}}setParent(parent){if(this.parent!=parent){this.parent=parent;if(this.dirty)this.markParentsDirty(true)}}setDOM(dom){if(this.dom)this.dom.cmView=null;this.dom=dom;dom.cmView=this}get rootView(){for(let v=this;;){let parent=v.parent;if(!parent)return v;v=parent}}replaceChildren(from,to,children=noChildren){this.markDirty();for(let i=from;ithis.pos||pos==this.pos&&(bias>0||this.i==0||this.children[this.i-1].breakAfter)){this.off=pos-this.pos;return this}let next=this.children[--this.i];this.pos-=next.length+next.breakAfter}}}function replaceRange(parent,fromI,fromOff,toI,toOff,insert,breakAtStart,openStart,openEnd){let{children}=parent;let before=children.length?children[fromI]:null;let last=insert.length?insert[insert.length-1]:null;let breakAtEnd=last?last.breakAfter:breakAtStart;if(fromI==toI&&before&&!breakAtStart&&!breakAtEnd&&insert.length<2&&before.merge(fromOff,toOff,insert.length?last:null,fromOff==0,openStart,openEnd))return;if(toI0){if(!breakAtStart&&insert.length&&before.merge(fromOff,before.length,insert[0],false,openStart,0)){before.breakAfter=insert.shift().breakAfter}else if(fromOff2);var browser={mac:ios||/Mac/.test(nav.platform),windows:/Win/.test(nav.platform),linux:/Linux|X11/.test(nav.platform),ie:ie,ie_version:ie_upto10?doc.documentMode||6:ie_11up?+ie_11up[1]:ie_edge?+ie_edge[1]:0,gecko:gecko,gecko_version:gecko?+(/Firefox\/(\d+)/.exec(nav.userAgent)||[0,0])[1]:0,chrome:!!chrome,chrome_version:chrome?+chrome[1]:0,ios:ios,android:/Android\b/.test(nav.userAgent),webkit:webkit,safari:safari,webkit_version:webkit?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:doc.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};const MaxJoinLen=256;class TextView extends ContentView{constructor(text){super();this.text=text}get length(){return this.text.length}createDOM(textDOM){this.setDOM(textDOM||document.createTextNode(this.text))}sync(track){if(!this.dom)this.createDOM();if(this.dom.nodeValue!=this.text){if(track&&track.node==this.dom)track.written=true;this.dom.nodeValue=this.text}}reuseDOM(dom){if(dom.nodeType==3)this.createDOM(dom)}merge(from,to,source){if(source&&(!(source instanceof TextView)||this.length-(to-from)+source.length>MaxJoinLen))return false;this.text=this.text.slice(0,from)+(source?source.text:"")+this.text.slice(to);this.markDirty();return true}split(from){let result=new TextView(this.text.slice(from));this.text=this.text.slice(0,from);this.markDirty();return result}localPosFromDOM(node,offset){return node==this.dom?offset:offset?this.text.length:0}domAtPos(pos){return new DOMPos(this.dom,pos)}domBoundsAround(_from,_to,offset){return{from:offset,to:offset+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(pos,side){return textCoords(this.dom,pos,side)}}class MarkView extends ContentView{constructor(mark,children=[],length=0){super();this.mark=mark;this.children=children;this.length=length;for(let ch of children)ch.setParent(this)}setAttrs(dom){clearAttributes(dom);if(this.mark.class)dom.className=this.mark.class;if(this.mark.attrs)for(let name in this.mark.attrs)dom.setAttribute(name,this.mark.attrs[name]);return dom}reuseDOM(node){if(node.nodeName==this.mark.tagName.toUpperCase()){this.setDOM(node);this.dirty|=4|2}}sync(track){if(!this.dom)this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));else if(this.dirty&4)this.setAttrs(this.dom);super.sync(track)}merge(from,to,source,_hasStart,openStart,openEnd){if(source&&(!(source instanceof MarkView&&source.mark.eq(this.mark))||from&&openStart<=0||tofrom)result.push(off=from)detachFrom=i;off=end;i++}let length=this.length-from;this.length=from;if(detachFrom>-1){this.children.length=detachFrom;this.markDirty()}return new MarkView(this.mark,result,length)}domAtPos(pos){return inlineDOMAtPos(this,pos)}coordsAt(pos,side){return coordsInChildren(this,pos,side)}}function textCoords(text,pos,side){let length=text.nodeValue.length;if(pos>length)pos=length;let from=pos,to=pos,flatten=0;if(pos==0&&side<0||pos==length&&side>=0){if(!(browser.chrome||browser.gecko)){if(pos){from--;flatten=1}else if(to=0)?0:rects.length-1];if(browser.safari&&!flatten&&rect.width==0)rect=Array.prototype.find.call(rects,r=>r.width)||rect;return flatten?flattenRect(rect,flatten<0):rect||null}class WidgetView extends ContentView{constructor(widget,length,side){super();this.widget=widget;this.length=length;this.side=side;this.prevWidget=null}static create(widget,length,side){return new(widget.customView||WidgetView)(widget,length,side)}split(from){let result=WidgetView.create(this.widget,this.length-from,this.side);this.length-=from;return result}sync(){if(!this.dom||!this.widget.updateDOM(this.dom)){if(this.dom&&this.prevWidget)this.prevWidget.destroy(this.dom);this.prevWidget=null;this.setDOM(this.widget.toDOM(this.editorView));this.dom.contentEditable="false"}}getSide(){return this.side}merge(from,to,source,hasStart,openStart,openEnd){if(source&&(!(source instanceof WidgetView)||!this.widget.compare(source.widget)||from>0&&openStart<=0||to0?rects.length-1:0;;i+=pos>0?-1:1){rect=rects[i];if(pos>0?i==0:i==rects.length-1||rect.top0)}get isEditable(){return false}destroy(){super.destroy();if(this.dom)this.widget.destroy(this.dom)}}class CompositionView extends WidgetView{domAtPos(pos){let{topView,text}=this.widget;if(!topView)return new DOMPos(text,Math.min(pos,text.nodeValue.length));return scanCompositionTree(pos,0,topView,text,(v,p)=>v.domAtPos(p),p=>new DOMPos(text,Math.min(p,text.nodeValue.length)))}sync(){this.setDOM(this.widget.toDOM())}localPosFromDOM(node,offset){let{topView,text}=this.widget;if(!topView)return Math.min(offset,this.length);return posFromDOMInCompositionTree(node,offset,topView,text)}ignoreMutation(){return false}get overrideDOMText(){return null}coordsAt(pos,side){let{topView,text}=this.widget;if(!topView)return textCoords(text,pos,side);return scanCompositionTree(pos,side,topView,text,(v,pos,side)=>v.coordsAt(pos,side),(pos,side)=>textCoords(text,pos,side))}destroy(){var _a;super.destroy();(_a=this.widget.topView)===null||_a===void 0?void 0:_a.destroy()}get isEditable(){return true}canReuseDOM(){return true}}function scanCompositionTree(pos,side,view,text,enterView,fromText){if(view instanceof MarkView){for(let child=view.dom.firstChild;child;child=child.nextSibling){let desc=ContentView.get(child);if(!desc)return fromText(pos,side);let hasComp=contains(child,text);let len=desc.length+(hasComp?text.nodeValue.length:0);if(pos0?-1:1);return siblingRect&&siblingRect.topimgRect.top?{left:imgRect.left,right:imgRect.right,top:siblingRect.top,bottom:siblingRect.bottom}:imgRect}get overrideDOMText(){return Text.empty}}TextView.prototype.children=WidgetView.prototype.children=WidgetBufferView.prototype.children=noChildren;function inlineSiblingRect(view,side){let parent=view.parent,index=parent?parent.children.indexOf(view):-1;while(parent&&index>=0){if(side<0?index>0:indexoff&&pos0;j--){let prev=children[j-1];if(prev.dom.parentNode==dom)return prev.domAtPos(prev.length)}for(let j=i;j0&&view instanceof MarkView&&children.length&&(last=children[children.length-1])instanceof MarkView&&last.mark.eq(view.mark)){joinInlineInto(last,view.children[0],open-1)}else{children.push(view);view.setParent(parent)}parent.length+=view.length}function coordsInChildren(view,pos,side){let before=null,beforePos=-1,after=null,afterPos=-1;function scan(view,pos){for(let i=0,off=0;i=pos){if(child.children.length){scan(child,pos-off)}else if(!after&&(end>pos||off==end&&child.getSide()>0)){after=child;afterPos=pos-off}else if(off0?3e8:-4e8:side>0?1e8:-1e8;return new PointDecoration(spec,side,side,block,spec.widget||null,false)}static replace(spec){let block=!!spec.block,startSide,endSide;if(spec.isBlockGap){startSide=-5e8;endSide=4e8}else{let{start,end}=getInclusive(spec,block);startSide=(start?block?-3e8:-1:5e8)-1;endSide=(end?block?2e8:1:-6e8)+1}return new PointDecoration(spec,startSide,endSide,block,spec.widget||null,true)}static line(spec){return new LineDecoration(spec)}static set(of,sort=false){return RangeSet.of(of,sort)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:false}}Decoration.none=RangeSet.empty;class MarkDecoration extends Decoration{constructor(spec){let{start,end}=getInclusive(spec);super(start?-1:5e8,end?1:-6e8,null,spec);this.tagName=spec.tagName||"span";this.class=spec.class||"";this.attrs=spec.attributes||null}eq(other){return this==other||other instanceof MarkDecoration&&this.tagName==other.tagName&&this.class==other.class&&attrsEq(this.attrs,other.attrs)}range(from,to=from){if(from>=to)throw new RangeError("Mark decorations may not be empty");return super.range(from,to)}}MarkDecoration.prototype.point=false;class LineDecoration extends Decoration{constructor(spec){super(-2e8,-2e8,null,spec)}eq(other){return other instanceof LineDecoration&&attrsEq(this.spec.attributes,other.spec.attributes)}range(from,to=from){if(to!=from)throw new RangeError("Line decoration ranges must be zero-length");return super.range(from,to)}}LineDecoration.prototype.mapMode=MapMode.TrackBefore;LineDecoration.prototype.point=true;class PointDecoration extends Decoration{constructor(spec,startSide,endSide,block,widget,isReplace){super(startSide,endSide,widget,spec);this.block=block;this.isReplace=isReplace;this.mapMode=!block?MapMode.TrackDel:startSide<=0?MapMode.TrackBefore:MapMode.TrackAfter}get type(){return this.startSide=5}eq(other){return other instanceof PointDecoration&&widgetsEq(this.widget,other.widget)&&this.block==other.block&&this.startSide==other.startSide&&this.endSide==other.endSide}range(from,to=from){if(this.isReplace&&(from>to||from==to&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&to!=from)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(from,to)}}PointDecoration.prototype.point=true;function getInclusive(spec,block=false){let{inclusiveStart:start,inclusiveEnd:end}=spec;if(start==null)start=spec.inclusive;if(end==null)end=spec.inclusive;return{start:start!==null&&start!==void 0?start:block,end:end!==null&&end!==void 0?end:block}}function widgetsEq(a,b){return a==b||!!(a&&b&&a.compare(b))}function addRange(from,to,ranges,margin=0){let last=ranges.length-1;if(last>=0&&ranges[last]+margin>=from)ranges[last]=Math.max(ranges[last],to);else ranges.push(from,to)}class LineView extends ContentView{constructor(){super(...arguments);this.children=[];this.length=0;this.prevAttrs=undefined;this.attrs=null;this.breakAfter=0}merge(from,to,source,hasStart,openStart,openEnd){if(source){if(!(source instanceof LineView))return false;if(!this.dom)source.transferDOM(this)}if(hasStart)this.setDeco(source?source.attrs:null);mergeChildrenInto(this,from,to,source?source.children:[],openStart,openEnd);return true}split(at){let end=new LineView;end.breakAfter=this.breakAfter;if(this.length==0)return end;let{i,off}=this.childPos(at);if(off){end.append(this.children[i].split(off),0);this.children[i].merge(off,this.children[i].length,null,false,0,0);i++}for(let j=i;j0&&this.children[i-1].length==0)this.children[--i].destroy();this.children.length=i;this.markDirty();this.length=at;return end}transferDOM(other){if(!this.dom)return;this.markDirty();other.setDOM(this.dom);other.prevAttrs=this.prevAttrs===undefined?this.attrs:this.prevAttrs;this.prevAttrs=undefined;this.dom=null}setDeco(attrs){if(!attrsEq(this.attrs,attrs)){if(this.dom){this.prevAttrs=this.attrs;this.markDirty()}this.attrs=attrs}}append(child,openStart){joinInlineInto(this,child,openStart)}addLineDeco(deco){let attrs=deco.spec.attributes,cls=deco.spec.class;if(attrs)this.attrs=combineAttrs(attrs,this.attrs||{});if(cls)this.attrs=combineAttrs({class:cls},this.attrs||{})}domAtPos(pos){return inlineDOMAtPos(this,pos)}reuseDOM(node){if(node.nodeName=="DIV"){this.setDOM(node);this.dirty|=4|2}}sync(track){var _a;if(!this.dom){this.setDOM(document.createElement("div"));this.dom.className="cm-line";this.prevAttrs=this.attrs?null:undefined}else if(this.dirty&4){clearAttributes(this.dom);this.dom.className="cm-line";this.prevAttrs=this.attrs?null:undefined}if(this.prevAttrs!==undefined){updateAttrs(this.dom,this.prevAttrs,this.attrs);this.dom.classList.add("cm-line");this.prevAttrs=undefined}super.sync(track);let last=this.dom.lastChild;while(last&&ContentView.get(last)instanceof MarkView)last=last.lastChild;if(!last||!this.length||last.nodeName!="BR"&&((_a=ContentView.get(last))===null||_a===void 0?void 0:_a.isEditable)==false&&(!browser.ios||!this.children.some(ch=>ch instanceof TextView))){let hack=document.createElement("BR");hack.cmIgnore=true;this.dom.appendChild(hack)}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let totalWidth=0;for(let child of this.children){if(!(child instanceof TextView)||/[^ -~]/.test(child.text))return null;let rects=clientRectsFor(child.dom);if(rects.length!=1)return null;totalWidth+=rects[0].width}return!totalWidth?null:{lineHeight:this.dom.getBoundingClientRect().height,charWidth:totalWidth/this.length}}coordsAt(pos,side){return coordsInChildren(this,pos,side)}become(_other){return false}get type(){return BlockType.Text}static find(docView,pos){for(let i=0,off=0;i=pos){if(block instanceof LineView)return block;if(end>pos)break}off=end+block.breakAfter}return null}}class BlockWidgetView extends ContentView{constructor(widget,length,type){super();this.widget=widget;this.length=length;this.type=type;this.breakAfter=0;this.prevWidget=null}merge(from,to,source,_takeDeco,openStart,openEnd){if(source&&(!(source instanceof BlockWidgetView)||!this.widget.compare(source.widget)||from>0&&openStart<=0||to0){if(this.textOff==this.text.length){let{value,lineBreak,done}=this.cursor.next(this.skip);this.skip=0;if(done)throw new Error("Ran out of text content when drawing inline views");if(lineBreak){if(!this.posCovered())this.getLine();if(this.content.length)this.content[this.content.length-1].breakAfter=1;else this.breakAtStart=1;this.flushBuffer([]);this.curLine=null;length--;continue}else{this.text=value;this.textOff=0}}let take=Math.min(this.text.length-this.textOff,length,512);this.flushBuffer(active.slice(0,openStart));this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff,this.textOff+take)),active),openStart);this.atCursorPos=true;this.textOff+=take;length-=take;openStart=0}}span(from,to,active,openStart){this.buildText(to-from,active,openStart);this.pos=to;if(this.openStart<0)this.openStart=openStart}point(from,to,deco,active,openStart,index){if(this.disallowBlockEffectsFor[index]&&deco instanceof PointDecoration){if(deco.block)throw new RangeError("Block decorations may not be specified via plugins");if(to>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let len=to-from;if(deco instanceof PointDecoration){if(deco.block){let{type}=deco;if(type==BlockType.WidgetAfter&&!this.posCovered())this.getLine();this.addBlockWidget(new BlockWidgetView(deco.widget||new NullWidget("div"),len,type))}else{let view=WidgetView.create(deco.widget||new NullWidget("span"),len,len?0:deco.startSide);let cursorBefore=this.atCursorPos&&!view.isEditable&&openStart<=active.length&&(from0);let cursorAfter=!view.isEditable&&(fromvalues.some(x=>x)});class ScrollTarget{constructor(range,y="nearest",x="nearest",yMargin=5,xMargin=5){this.range=range;this.y=y;this.x=x;this.yMargin=yMargin;this.xMargin=xMargin}map(changes){return changes.empty?this:new ScrollTarget(this.range.map(changes),this.y,this.x,this.yMargin,this.xMargin)}}const scrollIntoView=StateEffect.define({map:(t,ch)=>t.map(ch)});function logException(state,exception,context){let handler=state.facet(exceptionSink);if(handler.length)handler[0](exception);else if(window.onerror)window.onerror(String(exception),context,undefined,undefined,exception);else if(context)console.error(context+":",exception);else console.error(exception)}const editable=Facet.define({combine:values=>values.length?values[0]:true});let nextPluginID=0;const viewPlugin=Facet.define();class ViewPlugin{constructor(id,create,domEventHandlers,buildExtensions){this.id=id;this.create=create;this.domEventHandlers=domEventHandlers;this.extension=buildExtensions(this)}static define(create,spec){const{eventHandlers,provide,decorations:deco}=spec||{};return new ViewPlugin(nextPluginID++,create,eventHandlers,plugin=>{let ext=[viewPlugin.of(plugin)];if(deco)ext.push(decorations.of(view=>{let pluginInst=view.plugin(plugin);return pluginInst?deco(pluginInst):Decoration.none}));if(provide)ext.push(provide(plugin));return ext})}static fromClass(cls,spec){return ViewPlugin.define(view=>new cls(view),spec)}}class PluginInstance{constructor(spec){this.spec=spec;this.mustUpdate=null;this.value=null}update(view){if(!this.value){if(this.spec){try{this.value=this.spec.create(view)}catch(e){logException(view.state,e,"CodeMirror plugin crashed");this.deactivate()}}}else if(this.mustUpdate){let update=this.mustUpdate;this.mustUpdate=null;if(this.value.update){try{this.value.update(update)}catch(e){logException(update.state,e,"CodeMirror plugin crashed");if(this.value.destroy)try{this.value.destroy()}catch(_){}this.deactivate()}}}return this}destroy(view){var _a;if((_a=this.value)===null||_a===void 0?void 0:_a.destroy){try{this.value.destroy()}catch(e){logException(view.state,e,"CodeMirror plugin crashed")}}}deactivate(){this.spec=this.value=null}}const editorAttributes=Facet.define();const contentAttributes=Facet.define();const decorations=Facet.define();const atomicRanges=Facet.define();const scrollMargins=Facet.define();const styleModule=Facet.define();class ChangedRange{constructor(fromA,toA,fromB,toB){this.fromA=fromA;this.toA=toA;this.fromB=fromB;this.toB=toB}join(other){return new ChangedRange(Math.min(this.fromA,other.fromA),Math.max(this.toA,other.toA),Math.min(this.fromB,other.fromB),Math.max(this.toB,other.toB))}addToSet(set){let i=set.length,me=this;for(;i>0;i--){let range=set[i-1];if(range.fromA>me.toA)continue;if(range.toAend)break;else rI+=2}if(!next)return result;new ChangedRange(next.fromA,next.toA,next.fromB,next.toB).addToSet(result);posA=next.toA;posB=next.toB}}}class ViewUpdate{constructor(view,state,transactions){this.view=view;this.state=state;this.transactions=transactions;this.flags=0;this.startState=view.state;this.changes=ChangeSet.empty(this.startState.doc.length);for(let tr of transactions)this.changes=this.changes.compose(tr.changes);let changedRanges=[];this.changes.iterChangedRanges((fromA,toA,fromB,toB)=>changedRanges.push(new ChangedRange(fromA,toA,fromB,toB)));this.changedRanges=changedRanges;let focus=view.hasFocus;if(focus!=view.inputState.notifiedFocused){view.inputState.notifiedFocused=focus;this.flags|=1}}static create(view,state,transactions){return new ViewUpdate(view,state,transactions)}get viewportChanged(){return(this.flags&4)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&(8|2))>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(tr=>tr.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}var Direction=function(Direction){Direction[Direction["LTR"]=0]="LTR";Direction[Direction["RTL"]=1]="RTL";return Direction}(Direction||(Direction={}));const LTR=Direction.LTR,RTL=Direction.RTL;function dec(str){let result=[];for(let i=0;i=index){if(span.level==level)return i;if(maybe<0||(assoc!=0?assoc<0?span.fromindex:order[maybe].level>span.level))maybe=i}}if(maybe<0)throw new RangeError("Index out of range");return maybe}}const types=[];function computeOrder(line,direction){let len=line.length,outerType=direction==LTR?1:2,oppositeType=direction==LTR?2:1;if(!line||outerType==1&&!BidiRE.test(line))return trivialOrder(len);for(let i=0,prev=outerType,prevStrong=outerType;i=0;sJ-=3){if(BracketStack[sJ+1]==-br){let flags=BracketStack[sJ+2];let type=flags&2?outerType:!(flags&4)?0:flags&1?oppositeType:outerType;if(type)types[i]=types[BracketStack[sJ]]=type;sI=sJ;break}}}else if(BracketStack.length==189){break}else{BracketStack[sI++]=i;BracketStack[sI++]=ch;BracketStack[sI++]=context}}else if((type=types[i])==2||type==1){let embed=type==outerType;context=embed?0:1;for(let sJ=sI-3;sJ>=0;sJ-=3){let cur=BracketStack[sJ+2];if(cur&2)break;if(embed){BracketStack[sJ+2]|=2}else{if(cur&4)break;BracketStack[sJ+2]|=4}}}}for(let i=0;istart;){let end=j,l=types[--j]!=2;while(j>start&&l==(types[j-1]!=2))j--;order.push(new BidiSpan(j,end,l?2:1))}}else{order.push(new BidiSpan(start,i,0))}}}else{for(let i=0;i1)for(let point of this.points)if(point.node==node&&point.pos>this.text.length)point.pos-=breakSize-1;off=nextBreak+breakSize}}readNode(node){if(node.cmIgnore)return;let view=ContentView.get(node);let fromView=view&&view.overrideDOMText;if(fromView!=null){this.findPointInside(node,fromView.length);for(let i=fromView.iter();!i.next().done;){if(i.lineBreak)this.lineBreak();else this.append(i.value)}}else if(node.nodeType==3){this.readTextNode(node)}else if(node.nodeName=="BR"){if(node.nextSibling)this.lineBreak()}else if(node.nodeType==1){this.readRange(node.firstChild,null)}}findPointBefore(node,next){for(let point of this.points)if(point.node==node&&node.childNodes[point.offset]==next)point.pos=this.text.length}findPointInside(node,maxLen){for(let point of this.points)if(node.nodeType==3?point.node==node:node.contains(point.node))point.pos=this.text.length+Math.min(maxLen,point.offset)}}function isBlockElement(node){return node.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName)}class DOMPoint{constructor(node,offset){this.node=node;this.offset=offset;this.pos=-1}}class DocView extends ContentView{constructor(view){super();this.view=view;this.compositionDeco=Decoration.none;this.decorations=[];this.dynamicDecorationMap=[];this.minWidth=0;this.minWidthFrom=0;this.minWidthTo=0;this.impreciseAnchor=null;this.impreciseHead=null;this.forceSelection=false;this.lastUpdate=Date.now();this.setDOM(view.contentDOM);this.children=[new LineView];this.children[0].setParent(this);this.updateDeco();this.updateInner([new ChangedRange(0,0,0,view.state.doc.length)],0)}get editorView(){return this.view}get length(){return this.view.state.doc.length}update(update){let changedRanges=update.changedRanges;if(this.minWidth>0&&changedRanges.length){if(!changedRanges.every(({fromA,toA})=>toAthis.minWidthTo)){this.minWidth=this.minWidthFrom=this.minWidthTo=0}else{this.minWidthFrom=update.changes.mapPos(this.minWidthFrom,1);this.minWidthTo=update.changes.mapPos(this.minWidthTo,1)}}if(this.view.inputState.composing<0)this.compositionDeco=Decoration.none;else if(update.transactions.length||this.dirty)this.compositionDeco=computeCompositionDeco(this.view,update.changes);if((browser.ie||browser.chrome)&&!this.compositionDeco.size&&update&&update.state.doc.lines!=update.startState.doc.lines)this.forceSelection=true;let prevDeco=this.decorations,deco=this.updateDeco();let decoDiff=findChangedDeco(prevDeco,deco,update.changes);changedRanges=ChangedRange.extendWithRanges(changedRanges,decoDiff);if(this.dirty==0&&changedRanges.length==0){return false}else{this.updateInner(changedRanges,update.startState.doc.length);if(update.transactions.length)this.lastUpdate=Date.now();return true}}updateInner(changes,oldLength){this.view.viewState.mustMeasureContent=true;this.updateChildren(changes,oldLength);let{observer}=this.view;observer.ignore(()=>{this.dom.style.height=this.view.viewState.contentHeight+"px";this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let track=browser.chrome||browser.ios?{node:observer.selectionRange.focusNode,written:false}:undefined;this.sync(track);this.dirty=0;if(track&&(track.written||observer.selectionRange.focusNode!=track.node))this.forceSelection=true;this.dom.style.height=""});let gaps=[];if(this.view.viewport.from||this.view.viewport.to=0?changes[i]:null;if(!next)break;let{fromA,toA,fromB,toB}=next;let{content,breakAtStart,openStart,openEnd}=ContentBuilder.build(this.view.state.doc,fromB,toB,this.decorations,this.dynamicDecorationMap);let{i:toI,off:toOff}=cursor.findPos(toA,1);let{i:fromI,off:fromOff}=cursor.findPos(fromA,-1);replaceRange(this,fromI,fromOff,toI,toOff,content,breakAtStart,openStart,openEnd)}}updateSelection(mustRead=false,fromPointer=false){if(mustRead||!this.view.observer.selectionRange.focusNode)this.view.observer.readSelectionRange();if(!(fromPointer||this.mayControlSelection()))return;let force=this.forceSelection;this.forceSelection=false;let main=this.view.state.selection.main;let anchor=this.domAtPos(main.anchor);let head=main.empty?anchor:this.domAtPos(main.head);if(browser.gecko&&main.empty&&betweenUneditable(anchor)){let dummy=document.createTextNode("");this.view.observer.ignore(()=>anchor.node.insertBefore(dummy,anchor.node.childNodes[anchor.offset]||null));anchor=head=new DOMPos(dummy,0);force=true}let domSel=this.view.observer.selectionRange;if(force||!domSel.focusNode||!isEquivalentPosition(anchor.node,anchor.offset,domSel.anchorNode,domSel.anchorOffset)||!isEquivalentPosition(head.node,head.offset,domSel.focusNode,domSel.focusOffset)){this.view.observer.ignore(()=>{if(browser.android&&browser.chrome&&this.dom.contains(domSel.focusNode)&&inUneditable(domSel.focusNode,this.dom)){this.dom.blur();this.dom.focus({preventScroll:true})}let rawSel=getSelection(this.view.root);if(!rawSel);else if(main.empty){if(browser.gecko){let nextTo=nextToUneditable(anchor.node,anchor.offset);if(nextTo&&nextTo!=(1|2)){let text=nearbyTextNode(anchor.node,anchor.offset,nextTo==1?1:-1);if(text)anchor=new DOMPos(text,nextTo==1?0:text.nodeValue.length)}}rawSel.collapse(anchor.node,anchor.offset);if(main.bidiLevel!=null&&domSel.cursorBidiLevel!=null)domSel.cursorBidiLevel=main.bidiLevel}else if(rawSel.extend){rawSel.collapse(anchor.node,anchor.offset);try{rawSel.extend(head.node,head.offset)}catch(_){}}else{let range=document.createRange();if(main.anchor>main.head)[anchor,head]=[head,anchor];range.setEnd(head.node,head.offset);range.setStart(anchor.node,anchor.offset);rawSel.removeAllRanges();rawSel.addRange(range)}});this.view.observer.setSelectionRange(anchor,head)}this.impreciseAnchor=anchor.precise?null:new DOMPos(domSel.anchorNode,domSel.anchorOffset);this.impreciseHead=head.precise?null:new DOMPos(domSel.focusNode,domSel.focusOffset)}enforceCursorAssoc(){if(this.compositionDeco.size)return;let cursor=this.view.state.selection.main;let sel=getSelection(this.view.root);if(!sel||!cursor.empty||!cursor.assoc||!sel.modify)return;let line=LineView.find(this,cursor.head);if(!line)return;let lineStart=line.posAtStart;if(cursor.head==lineStart||cursor.head==lineStart+line.length)return;let before=this.coordsAt(cursor.head,-1),after=this.coordsAt(cursor.head,1);if(!before||!after||before.bottom>after.top)return;let dom=this.domAtPos(cursor.head+cursor.assoc);sel.collapse(dom.node,dom.offset);sel.modify("move",cursor.assoc<0?"forward":"backward","lineboundary")}mayControlSelection(){let active=this.view.root.activeElement;return active==this.dom||hasSelection(this.dom,this.view.observer.selectionRange)&&!(active&&this.dom.contains(active))}nearest(dom){for(let cur=dom;cur;){let domView=ContentView.get(cur);if(domView&&domView.rootView==this)return domView;cur=cur.parentNode}return null}posFromDOM(node,offset){let view=this.nearest(node);if(!view)throw new RangeError("Trying to find position for a DOM position outside of the document");return view.localPosFromDOM(node,offset)+view.posAtStart}domAtPos(pos){let{i,off}=this.childCursor().findPos(pos,-1);for(;istart||pos==start&&child.type!=BlockType.WidgetBefore&&child.type!=BlockType.WidgetAfter&&(!i||side==2||this.children[i-1].breakAfter||this.children[i-1].type==BlockType.WidgetBefore&&side>-2))return child.coordsAt(pos-start,side);off=start}}measureVisibleLineHeights(viewport){let result=[],{from,to}=viewport;let contentWidth=this.view.contentDOM.clientWidth;let isWider=contentWidth>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1;let widest=-1,ltr=this.view.textDirection==Direction.LTR;for(let pos=0,i=0;ito)break;if(pos>=from){let childRect=child.dom.getBoundingClientRect();result.push(childRect.height);if(isWider){let last=child.dom.lastChild;let rects=last?clientRectsFor(last):[];if(rects.length){let rect=rects[rects.length-1];let width=ltr?rect.right-childRect.left:childRect.right-rect.left;if(width>widest){widest=width;this.minWidth=contentWidth;this.minWidthFrom=pos;this.minWidthTo=end}}}}pos=end+child.breakAfter}return result}textDirectionAt(pos){let{i}=this.childPos(pos,1);return getComputedStyle(this.children[i].dom).direction=="rtl"?Direction.RTL:Direction.LTR}measureTextSize(){for(let child of this.children){if(child instanceof LineView){let measure=child.measureTextSize();if(measure)return measure}}let dummy=document.createElement("div"),lineHeight,charWidth;dummy.className="cm-line";dummy.style.width="99999px";dummy.textContent="abc def ghi jkl mno pqr stu";this.view.observer.ignore(()=>{this.dom.appendChild(dummy);let rect=clientRectsFor(dummy.firstChild)[0];lineHeight=dummy.getBoundingClientRect().height;charWidth=rect?rect.width/27:7;dummy.remove()});return{lineHeight:lineHeight,charWidth:charWidth}}childCursor(pos=this.length){let i=this.children.length;if(i)pos-=this.children[--i].length;return new ChildCursor(this.children,pos,i)}computeBlockGapDeco(){let deco=[],vs=this.view.viewState;for(let pos=0,i=0;;i++){let next=i==vs.viewports.length?null:vs.viewports[i];let end=next?next.from-1:this.length;if(end>pos){let height=vs.lineBlockAt(end).bottom-vs.lineBlockAt(pos).top;deco.push(Decoration.replace({widget:new BlockGapWidget(height),block:true,inclusive:true,isBlockGap:true}).range(pos,end))}if(!next)break;pos=next.to+1}return Decoration.set(deco)}updateDeco(){let allDeco=this.view.state.facet(decorations).map((d,i)=>{let dynamic=this.dynamicDecorationMap[i]=typeof d=="function";return dynamic?d(this.view):d});for(let i=allDeco.length;irange.anchor?-1:1),other;if(!rect)return;if(!range.empty&&(other=this.coordsAt(range.anchor,range.anchor>range.head?-1:1)))rect={left:Math.min(rect.left,other.left),top:Math.min(rect.top,other.top),right:Math.max(rect.right,other.right),bottom:Math.max(rect.bottom,other.bottom)};let mLeft=0,mRight=0,mTop=0,mBottom=0;for(let margins of this.view.state.facet(scrollMargins).map(f=>f(this.view)))if(margins){let{left,right,top,bottom}=margins;if(left!=null)mLeft=Math.max(mLeft,left);if(right!=null)mRight=Math.max(mRight,right);if(top!=null)mTop=Math.max(mTop,top);if(bottom!=null)mBottom=Math.max(mBottom,bottom)}let targetRect={left:rect.left-mLeft,top:rect.top-mTop,right:rect.right+mRight,bottom:rect.bottom+mBottom};scrollRectIntoView(this.view.scrollDOM,targetRect,range.head0&&side<=0){node=node.childNodes[offset-1];offset=maxOffset(node)}else if(node.nodeType==1&&offset=0){node=node.childNodes[offset];offset=0}else{return null}}}function nextToUneditable(node,offset){if(node.nodeType!=1)return 0;return(offset&&node.childNodes[offset-1].contentEditable=="false"?1:0)|(offset0){let prev=findClusterBreak(line.text,from,false);if(categorize(line.text.slice(prev,from))!=cat)break;from=prev}while(tox?rect.left-x:Math.max(0,x-rect.right)}function getdy(y,rect){return rect.top>y?rect.top-y:Math.max(0,y-rect.bottom)}function yOverlap(a,b){return a.topb.top+1}function upTop(rect,top){return toprect.bottom?{top:rect.top,left:rect.left,right:rect.right,bottom:bottom}:rect}function domPosAtCoords(parent,x,y){let closest,closestRect,closestX,closestY,closestOverlap=false;let above,below,aboveRect,belowRect;for(let child=parent.firstChild;child;child=child.nextSibling){let rects=clientRectsFor(child);for(let i=0;idy||closestY==dy&&closestX>dx){closest=child;closestRect=rect;closestX=dx;closestY=dy;closestOverlap=!dx||(dx>0?i0)}if(dx==0){if(y>rect.bottom&&(!aboveRect||aboveRect.bottomrect.top)){below=child;belowRect=rect}}else if(aboveRect&&yOverlap(aboveRect,rect)){aboveRect=upBot(aboveRect,rect.bottom)}else if(belowRect&&yOverlap(belowRect,rect)){belowRect=upTop(belowRect,rect.top)}}}if(aboveRect&&aboveRect.bottom>=y){closest=above;closestRect=aboveRect}else if(belowRect&&belowRect.top<=y){closest=below;closestRect=belowRect}if(!closest)return{node:parent,offset:0};let clipX=Math.max(closestRect.left,Math.min(closestRect.right,x));if(closest.nodeType==3)return domPosInText(closest,clipX,y);if(closestOverlap&&closest.contentEditable!="false")return domPosAtCoords(closest,clipX,y);let offset=Array.prototype.indexOf.call(parent.childNodes,closest)+(x>=(closestRect.left+closestRect.right)/2?1:0);return{node:parent,offset:offset}}function domPosInText(node,x,y){let len=node.nodeValue.length;let closestOffset=-1,closestDY=1e9,generalSide=0;for(let i=0;iy?rect.top-y:y-rect.bottom)-1;if(rect.left-1<=x&&rect.right+1>=x&&dy=(rect.left+rect.right)/2,after=right;if(browser.chrome||browser.gecko){let rectBefore=textRange(node,i).getBoundingClientRect();if(rectBefore.left==rect.right)after=!right}if(dy<=0)return{node:node,offset:i+(after?1:0)};closestOffset=i+(after?1:0);closestDY=dy}}}return{node:node,offset:closestOffset>-1?closestOffset:generalSide>0?node.nodeValue.length:0}}function posAtCoords(view,{x,y},precise,bias=-1){var _a;let content=view.contentDOM.getBoundingClientRect(),docTop=content.top+view.viewState.paddingTop;let block,{docHeight}=view.viewState;let yOffset=y-docTop;if(yOffset<0)return 0;if(yOffset>docHeight)return view.state.doc.length;for(let halfLine=view.defaultLineHeight/2,bounced=false;;){block=view.elementAtHeight(yOffset);if(block.type==BlockType.Text)break;for(;;){yOffset=bias>0?block.bottom+halfLine:block.top-halfLine;if(yOffset>=0&&yOffset<=docHeight)break;if(bounced)return precise?null:0;bounced=true;bias=-bias}}y=docTop+yOffset;let lineStart=block.from;if(lineStartview.viewport.to)return view.viewport.to==view.state.doc.length?view.state.doc.length:precise?null:posAtCoordsImprecise(view,content,block,x,y);let doc=view.dom.ownerDocument;let root=view.root.elementFromPoint?view.root:doc;let element=root.elementFromPoint(x,y);if(element&&!view.contentDOM.contains(element))element=null;if(!element){x=Math.max(content.left+1,Math.min(content.right-1,x));element=root.elementFromPoint(x,y);if(element&&!view.contentDOM.contains(element))element=null}let node,offset=-1;if(element&&((_a=view.docView.nearest(element))===null||_a===void 0?void 0:_a.isEditable)!=false){if(doc.caretPositionFromPoint){let pos=doc.caretPositionFromPoint(x,y);if(pos)({offsetNode:node,offset}=pos)}else if(doc.caretRangeFromPoint){let range=doc.caretRangeFromPoint(x,y);if(range){({startContainer:node,startOffset:offset}=range);if(!view.contentDOM.contains(node)||browser.safari&&isSuspiciousSafariCaretResult(node,offset,x)||browser.chrome&&isSuspiciousChromeCaretResult(node,offset,x))node=undefined}}}if(!node||!view.docView.dom.contains(node)){let line=LineView.find(view.docView,lineStart);if(!line)return yOffset>block.top+block.height/2?block.to:block.from;({node,offset}=domPosAtCoords(line.dom,x,y))}return view.docView.posFromDOM(node,offset)}function posAtCoordsImprecise(view,contentRect,block,x,y){let into=Math.round((x-contentRect.left)*view.defaultCharacterWidth);if(view.lineWrapping&&block.height>view.defaultLineHeight*1.5){let line=Math.floor((y-block.top)/view.defaultLineHeight);into+=line*view.viewState.heightOracle.lineLength}let content=view.state.sliceDoc(block.from,block.to);return block.from+findColumn(content,into,view.state.tabSize)}function isSuspiciousSafariCaretResult(node,offset,x){let len;if(node.nodeType!=3||offset!=(len=node.nodeValue.length))return false;for(let next=node.nextSibling;next;next=next.nextSibling)if(next.nodeType!=1||next.nodeName!="BR")return false;return textRange(node,len-1,len).getBoundingClientRect().left>x}function isSuspiciousChromeCaretResult(node,offset,x){if(offset!=0)return false;for(let cur=node;;){let parent=cur.parentNode;if(!parent||parent.nodeType!=1||parent.firstChild!=cur)return false;if(parent.classList.contains("cm-line"))break;cur=parent}let rect=node.nodeType==1?node.getBoundingClientRect():textRange(node,0,Math.max(node.nodeValue.length,1)).getBoundingClientRect();return x-rect.left>5}function moveToLineBoundary(view,start,forward,includeWrap){let line=view.state.doc.lineAt(start.head);let coords=!includeWrap||!view.lineWrapping?null:view.coordsAtPos(start.assoc<0&&start.head>line.from?start.head-1:start.head);if(coords){let editorRect=view.dom.getBoundingClientRect();let direction=view.textDirectionAt(line.from);let pos=view.posAtCoords({x:forward==(direction==Direction.LTR)?editorRect.right-1:editorRect.left+1,y:(coords.top+coords.bottom)/2});if(pos!=null)return EditorSelection.cursor(pos,forward?-1:1)}let lineView=LineView.find(view.docView,start.head);let end=lineView?forward?lineView.posAtEnd:lineView.posAtStart:forward?line.to:line.from;return EditorSelection.cursor(end,forward?-1:1)}function moveByChar(view,start,forward,by){let line=view.state.doc.lineAt(start.head),spans=view.bidiSpans(line);let direction=view.textDirectionAt(line.from);for(let cur=start,check=null;;){let next=moveVisually(line,spans,direction,cur,forward),char=movedOver;if(!next){if(line.number==(forward?view.state.doc.lines:1))return cur;char="\n";line=view.state.doc.line(line.number+(forward?1:-1));spans=view.bidiSpans(line);next=EditorSelection.cursor(forward?line.from:line.to)}if(!check){if(!by)return next;check=by(char)}else if(!check(char)){return cur}cur=next}}function byGroup(view,pos,start){let categorize=view.state.charCategorizer(pos);let cat=categorize(start);return next=>{let nextCat=categorize(next);if(cat==CharCategory.Space)cat=nextCat;return cat==nextCat}}function moveVertically(view,start,forward,distance){let startPos=start.head,dir=forward?1:-1;if(startPos==(forward?view.state.doc.length:0))return EditorSelection.cursor(startPos,start.assoc);let goal=start.goalColumn,startY;let rect=view.contentDOM.getBoundingClientRect();let startCoords=view.coordsAtPos(startPos),docTop=view.documentTop;if(startCoords){if(goal==null)goal=startCoords.left-rect.left;startY=dir<0?startCoords.top:startCoords.bottom}else{let line=view.viewState.lineBlockAt(startPos);if(goal==null)goal=Math.min(rect.right-rect.left,view.defaultCharacterWidth*(startPos-line.from));startY=(dir<0?line.top:line.bottom)+docTop}let resolvedGoal=rect.left+goal;let dist=distance!==null&&distance!==void 0?distance:view.defaultLineHeight>>1;for(let extra=0;;extra+=10){let curY=startY+(dist+extra)*dir;let pos=posAtCoords(view,{x:resolvedGoal,y:curY},false,dir);if(curYrect.bottom||(dir<0?posstartPos))return EditorSelection.cursor(pos,start.assoc,undefined,goal)}}function skipAtoms(view,oldPos,pos){let atoms=view.state.facet(atomicRanges).map(f=>f(view));for(;;){let moved=false;for(let set of atoms){set.between(pos.from-1,pos.from+1,(from,to,value)=>{if(pos.from>from&&pos.frompos.from?EditorSelection.cursor(from,1):EditorSelection.cursor(to,-1);moved=true}})}if(!moved)return pos}}class InputState{constructor(view){this.lastKeyCode=0;this.lastKeyTime=0;this.lastTouchTime=0;this.lastFocusTime=0;this.lastScrollTop=0;this.lastScrollLeft=0;this.chromeScrollHack=-1;this.pendingIOSKey=undefined;this.lastSelectionOrigin=null;this.lastSelectionTime=0;this.lastEscPress=0;this.lastContextMenu=0;this.scrollHandlers=[];this.registeredEvents=[];this.customHandlers=[];this.composing=-1;this.compositionFirstChange=null;this.compositionEndedAt=0;this.mouseSelection=null;for(let type in handlers){let handler=handlers[type];view.contentDOM.addEventListener(type,event=>{if(!eventBelongsToEditor(view,event)||this.ignoreDuringComposition(event))return;if(type=="keydown"&&this.keydown(view,event))return;if(this.mustFlushObserver(event))view.observer.forceFlush();if(this.runCustomHandlers(type,view,event))event.preventDefault();else handler(view,event)},handlerOptions[type]);this.registeredEvents.push(type)}if(browser.chrome&&browser.chrome_version==102){view.scrollDOM.addEventListener("wheel",()=>{if(this.chromeScrollHack<0)view.contentDOM.style.pointerEvents="none";else window.clearTimeout(this.chromeScrollHack);this.chromeScrollHack=setTimeout(()=>{this.chromeScrollHack=-1;view.contentDOM.style.pointerEvents=""},100)},{passive:true})}this.notifiedFocused=view.hasFocus;if(browser.safari)view.contentDOM.addEventListener("input",()=>null)}setSelectionOrigin(origin){this.lastSelectionOrigin=origin;this.lastSelectionTime=Date.now()}ensureHandlers(view,plugins){var _a;let handlers;this.customHandlers=[];for(let plugin of plugins)if(handlers=(_a=plugin.update(view).spec)===null||_a===void 0?void 0:_a.domEventHandlers){this.customHandlers.push({plugin:plugin.value,handlers:handlers});for(let type in handlers)if(this.registeredEvents.indexOf(type)<0&&type!="scroll"){this.registeredEvents.push(type);view.contentDOM.addEventListener(type,event=>{if(!eventBelongsToEditor(view,event))return;if(this.runCustomHandlers(type,view,event))event.preventDefault()})}}}runCustomHandlers(type,view,event){for(let set of this.customHandlers){let handler=set.handlers[type];if(handler){try{if(handler.call(set.plugin,event,view)||event.defaultPrevented)return true}catch(e){logException(view.state,e)}}}return false}runScrollHandlers(view,event){this.lastScrollTop=view.scrollDOM.scrollTop;this.lastScrollLeft=view.scrollDOM.scrollLeft;for(let set of this.customHandlers){let handler=set.handlers.scroll;if(handler){try{handler.call(set.plugin,event,view)}catch(e){logException(view.state,e)}}}}keydown(view,event){this.lastKeyCode=event.keyCode;this.lastKeyTime=Date.now();if(event.keyCode==9&&Date.now()key.keyCode==event.keyCode))&&!event.ctrlKey||EmacsyPendingKeys.indexOf(event.key)>-1&&event.ctrlKey&&!event.shiftKey)){this.pendingIOSKey=pending||event;setTimeout(()=>this.flushIOSKey(view),250);return true}return false}flushIOSKey(view){let key=this.pendingIOSKey;if(!key)return false;this.pendingIOSKey=undefined;return dispatchKey(view.contentDOM,key.key,key.keyCode)}ignoreDuringComposition(event){if(!/^key/.test(event.type))return false;if(this.composing>0)return true;if(browser.safari&&!browser.ios&&Date.now()-this.compositionEndedAt<100){this.compositionEndedAt=0;return true}return false}mustFlushObserver(event){return event.type=="keydown"&&event.keyCode!=229}startMouseSelection(mouseSelection){if(this.mouseSelection)this.mouseSelection.destroy();this.mouseSelection=mouseSelection}update(update){if(this.mouseSelection)this.mouseSelection.update(update);if(update.transactions.length)this.lastKeyCode=this.lastSelectionTime=0}destroy(){if(this.mouseSelection)this.mouseSelection.destroy()}}const PendingKeys=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}];const EmacsyPendingKeys="dthko";const modifierCodes=[16,17,18,20,91,92,224,225];class MouseSelection{constructor(view,startEvent,style,mustSelect){this.view=view;this.style=style;this.mustSelect=mustSelect;this.lastEvent=startEvent;let doc=view.contentDOM.ownerDocument;doc.addEventListener("mousemove",this.move=this.move.bind(this));doc.addEventListener("mouseup",this.up=this.up.bind(this));this.extend=startEvent.shiftKey;this.multiple=view.state.facet(EditorState.allowMultipleSelections)&&addsSelectionRange(view,startEvent);this.dragMove=dragMovesSelection(view,startEvent);this.dragging=isInPrimarySelection(view,startEvent)&&getClickType(startEvent)==1?null:false;if(this.dragging===false){startEvent.preventDefault();this.select(startEvent)}}move(event){if(event.buttons==0)return this.destroy();if(this.dragging!==false)return;this.select(this.lastEvent=event)}up(event){if(this.dragging==null)this.select(this.lastEvent);if(!this.dragging)event.preventDefault();this.destroy()}destroy(){let doc=this.view.contentDOM.ownerDocument;doc.removeEventListener("mousemove",this.move);doc.removeEventListener("mouseup",this.up);this.view.inputState.mouseSelection=null}select(event){let selection=this.style.get(event,this.extend,this.multiple);if(this.mustSelect||!selection.eq(this.view.state.selection)||selection.main.assoc!=this.view.state.selection.main.assoc)this.view.dispatch({selection:selection,userEvent:"select.pointer",scrollIntoView:true});this.mustSelect=false}update(update){if(update.docChanged&&this.dragging)this.dragging=this.dragging.map(update.changes);if(this.style.update(update))setTimeout(()=>this.select(this.lastEvent),20)}}function addsSelectionRange(view,event){let facet=view.state.facet(clickAddsSelectionRange);return facet.length?facet[0](event):browser.mac?event.metaKey:event.ctrlKey}function dragMovesSelection(view,event){let facet=view.state.facet(dragMovesSelection$1);return facet.length?facet[0](event):browser.mac?!event.altKey:!event.ctrlKey}function isInPrimarySelection(view,event){let{main}=view.state.selection;if(main.empty)return false;let sel=getSelection(view.root);if(!sel||sel.rangeCount==0)return true;let rects=sel.getRangeAt(0).getClientRects();for(let i=0;i=event.clientX&&rect.top<=event.clientY&&rect.bottom>=event.clientY)return true}return false}function eventBelongsToEditor(view,event){if(!event.bubbles)return true;if(event.defaultPrevented)return false;for(let node=event.target,cView;node!=view.contentDOM;node=node.parentNode)if(!node||node.nodeType==11||(cView=ContentView.get(node))&&cView.ignoreEvent(event))return false;return true}const handlers=Object.create(null);const handlerOptions=Object.create(null);const brokenClipboardAPI=browser.ie&&browser.ie_version<15||browser.ios&&browser.webkit_version<604;function capturePaste(view){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px";target.focus();setTimeout(()=>{view.focus();target.remove();doPaste(view,target.value)},50)}function doPaste(view,input){let{state}=view,changes,i=1,text=state.toText(input);let byLine=text.lines==state.selection.ranges.length;let linewise=lastLinewiseCopy!=null&&state.selection.ranges.every(r=>r.empty)&&lastLinewiseCopy==text.toString();if(linewise){let lastLine=-1;changes=state.changeByRange(range=>{let line=state.doc.lineAt(range.from);if(line.from==lastLine)return{range:range};lastLine=line.from;let insert=state.toText((byLine?text.line(i++).text:input)+state.lineBreak);return{changes:{from:line.from,insert:insert},range:EditorSelection.cursor(range.from+insert.length)}})}else if(byLine){changes=state.changeByRange(range=>{let line=text.line(i++);return{changes:{from:range.from,to:range.to,insert:line.text},range:EditorSelection.cursor(range.from+line.length)}})}else{changes=state.replaceSelection(text)}view.dispatch(changes,{userEvent:"input.paste",scrollIntoView:true})}handlers.keydown=(view,event)=>{view.inputState.setSelectionOrigin("select");if(event.keyCode==27)view.inputState.lastEscPress=Date.now();else if(modifierCodes.indexOf(event.keyCode)<0)view.inputState.lastEscPress=0};handlers.touchstart=(view,e)=>{view.inputState.lastTouchTime=Date.now();view.inputState.setSelectionOrigin("select.pointer")};handlers.touchmove=view=>{view.inputState.setSelectionOrigin("select.pointer")};handlerOptions.touchstart=handlerOptions.touchmove={passive:true};handlers.mousedown=(view,event)=>{view.observer.flush();if(view.inputState.lastTouchTime>Date.now()-2e3)return;let style=null;for(let makeStyle of view.state.facet(mouseSelectionStyle)){style=makeStyle(view,event);if(style)break}if(!style&&event.button==0)style=basicMouseSelection(view,event);if(style){let mustFocus=view.root.activeElement!=view.contentDOM;if(mustFocus)view.observer.ignore(()=>focusPreventScroll(view.contentDOM));view.inputState.startMouseSelection(new MouseSelection(view,event,style,mustFocus))}};function rangeForClick(view,pos,bias,type){if(type==1){return EditorSelection.cursor(pos,bias)}else if(type==2){return groupAt(view.state,pos,bias)}else{let visual=LineView.find(view.docView,pos),line=view.state.doc.lineAt(visual?visual.posAtEnd:pos);let from=visual?visual.posAtStart:line.from,to=visual?visual.posAtEnd:line.to;if(toy>=rect.top&&y<=rect.bottom;let inside=(x,y,rect)=>insideY(y,rect)&&x>=rect.left&&x<=rect.right;function findPositionSide(view,pos,x,y){let line=LineView.find(view.docView,pos);if(!line)return 1;let off=pos-line.posAtStart;if(off==0)return 1;if(off==line.length)return-1;let before=line.coordsAt(off,-1);if(before&&inside(x,y,before))return-1;let after=line.coordsAt(off,1);if(after&&inside(x,y,after))return 1;return before&&insideY(y,before)?-1:1}function queryPos(view,event){let pos=view.posAtCoords({x:event.clientX,y:event.clientY},false);return{pos:pos,bias:findPositionSide(view,pos,event.clientX,event.clientY)}}const BadMouseDetail=browser.ie&&browser.ie_version<=11;let lastMouseDown=null,lastMouseDownCount=0,lastMouseDownTime=0;function getClickType(event){if(!BadMouseDetail)return event.detail;let last=lastMouseDown,lastTime=lastMouseDownTime;lastMouseDown=event;lastMouseDownTime=Date.now();return lastMouseDownCount=!last||lastTime>Date.now()-400&&Math.abs(last.clientX-event.clientX)<2&&Math.abs(last.clientY-event.clientY)<2?(lastMouseDownCount+1)%3:1}function basicMouseSelection(view,event){let start=queryPos(view,event),type=getClickType(event);let startSel=view.state.selection;let last=start,lastEvent=event;return{update(update){if(update.docChanged){start.pos=update.changes.mapPos(start.pos);startSel=startSel.map(update.changes);lastEvent=null}},get(event,extend,multiple){let cur;if(lastEvent&&event.clientX==lastEvent.clientX&&event.clientY==lastEvent.clientY)cur=last;else{cur=last=queryPos(view,event);lastEvent=event}let range=rangeForClick(view,cur.pos,cur.bias,type);if(start.pos!=cur.pos&&!extend){let startRange=rangeForClick(view,start.pos,start.bias,type);let from=Math.min(startRange.from,range.from),to=Math.max(startRange.to,range.to);range=from1&&startSel.ranges.some(r=>r.eq(range)))return removeRange(startSel,range);else if(multiple)return startSel.addRange(range);else return EditorSelection.create([range])}}}function removeRange(sel,range){for(let i=0;;i++){if(sel.ranges[i].eq(range))return EditorSelection.create(sel.ranges.slice(0,i).concat(sel.ranges.slice(i+1)),sel.mainIndex==i?0:sel.mainIndex-(sel.mainIndex>i?1:0))}}handlers.dragstart=(view,event)=>{let{selection:{main}}=view.state;let{mouseSelection}=view.inputState;if(mouseSelection)mouseSelection.dragging=main;if(event.dataTransfer){event.dataTransfer.setData("Text",view.state.sliceDoc(main.from,main.to));event.dataTransfer.effectAllowed="copyMove"}};function dropText(view,event,text,direct){if(!text)return;let dropPos=view.posAtCoords({x:event.clientX,y:event.clientY},false);event.preventDefault();let{mouseSelection}=view.inputState;let del=direct&&mouseSelection&&mouseSelection.dragging&&mouseSelection.dragMove?{from:mouseSelection.dragging.from,to:mouseSelection.dragging.to}:null;let ins={from:dropPos,insert:text};let changes=view.state.changes(del?[del,ins]:ins);view.focus();view.dispatch({changes:changes,selection:{anchor:changes.mapPos(dropPos,-1),head:changes.mapPos(dropPos,1)},userEvent:del?"move.drop":"input.drop"})}handlers.drop=(view,event)=>{if(!event.dataTransfer)return;if(view.state.readOnly)return event.preventDefault();let files=event.dataTransfer.files;if(files&&files.length){event.preventDefault();let text=Array(files.length),read=0;let finishFile=()=>{if(++read==files.length)dropText(view,event,text.filter(s=>s!=null).join(view.state.lineBreak),false)};for(let i=0;i{if(!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result))text[i]=reader.result;finishFile()};reader.readAsText(files[i])}}else{dropText(view,event,event.dataTransfer.getData("Text"),true)}};handlers.paste=(view,event)=>{if(view.state.readOnly)return event.preventDefault();view.observer.flush();let data=brokenClipboardAPI?null:event.clipboardData;if(data){doPaste(view,data.getData("text/plain"));event.preventDefault()}else{capturePaste(view)}};function captureCopy(view,text){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px";target.value=text;target.focus();target.selectionEnd=text.length;target.selectionStart=0;setTimeout(()=>{target.remove();view.focus()},50)}function copiedRange(state){let content=[],ranges=[],linewise=false;for(let range of state.selection.ranges)if(!range.empty){content.push(state.sliceDoc(range.from,range.to));ranges.push(range)}if(!content.length){let upto=-1;for(let{from}of state.selection.ranges){let line=state.doc.lineAt(from);if(line.number>upto){content.push(line.text);ranges.push({from:line.from,to:Math.min(state.doc.length,line.to+1)})}upto=line.number}linewise=true}return{text:content.join(state.lineBreak),ranges:ranges,linewise:linewise}}let lastLinewiseCopy=null;handlers.copy=handlers.cut=(view,event)=>{let{text,ranges,linewise}=copiedRange(view.state);if(!text&&!linewise)return;lastLinewiseCopy=linewise?text:null;let data=brokenClipboardAPI?null:event.clipboardData;if(data){event.preventDefault();data.clearData();data.setData("text/plain",text)}else{captureCopy(view,text)}if(event.type=="cut"&&!view.state.readOnly)view.dispatch({changes:ranges,scrollIntoView:true,userEvent:"delete.cut"})};function updateForFocusChange(view){setTimeout(()=>{if(view.hasFocus!=view.inputState.notifiedFocused)view.update([])},10)}handlers.focus=view=>{view.inputState.lastFocusTime=Date.now();if(!view.scrollDOM.scrollTop&&(view.inputState.lastScrollTop||view.inputState.lastScrollLeft)){view.scrollDOM.scrollTop=view.inputState.lastScrollTop;view.scrollDOM.scrollLeft=view.inputState.lastScrollLeft}updateForFocusChange(view)};handlers.blur=view=>{view.observer.clearSelectionRange();updateForFocusChange(view)};handlers.compositionstart=handlers.compositionupdate=view=>{if(view.inputState.compositionFirstChange==null)view.inputState.compositionFirstChange=true;if(view.inputState.composing<0){view.inputState.composing=0}};handlers.compositionend=view=>{view.inputState.composing=-1;view.inputState.compositionEndedAt=Date.now();view.inputState.compositionFirstChange=null;if(browser.chrome&&browser.android)view.observer.flushSoon();setTimeout(()=>{if(view.inputState.composing<0&&view.docView.compositionDeco.size)view.update([])},50)};handlers.contextmenu=view=>{view.inputState.lastContextMenu=Date.now()};handlers.beforeinput=(view,event)=>{var _a;let pending;if(browser.chrome&&browser.android&&(pending=PendingKeys.find(key=>key.inputType==event.inputType))){view.observer.delayAndroidKey(pending.key,pending.keyCode);if(pending.key=="Backspace"||pending.key=="Delete"){let startViewHeight=((_a=window.visualViewport)===null||_a===void 0?void 0:_a.height)||0;setTimeout(()=>{var _a;if((((_a=window.visualViewport)===null||_a===void 0?void 0:_a.height)||0)>startViewHeight+10&&view.hasFocus){view.contentDOM.blur();view.focus()}},100)}}};const wrappingWhiteSpace=["pre-wrap","normal","pre-line","break-spaces"];class HeightOracle{constructor(){this.doc=Text.empty;this.lineWrapping=false;this.heightSamples={};this.lineHeight=14;this.charWidth=7;this.lineLength=30;this.heightChanged=false}heightForGap(from,to){let lines=this.doc.lineAt(to).number-this.doc.lineAt(from).number+1;if(this.lineWrapping)lines+=Math.ceil((to-from-lines*this.lineLength*.5)/this.lineLength);return this.lineHeight*lines}heightForLine(length){if(!this.lineWrapping)return this.lineHeight;let lines=1+Math.max(0,Math.ceil((length-this.lineLength)/(this.lineLength-5)));return lines*this.lineHeight}setDoc(doc){this.doc=doc;return this}mustRefreshForWrapping(whiteSpace){return wrappingWhiteSpace.indexOf(whiteSpace)>-1!=this.lineWrapping}mustRefreshForHeights(lineHeights){let newHeight=false;for(let i=0;i-1;let changed=Math.round(lineHeight)!=Math.round(this.lineHeight)||this.lineWrapping!=lineWrapping;this.lineWrapping=lineWrapping;this.lineHeight=lineHeight;this.charWidth=charWidth;this.lineLength=lineLength;if(changed){this.heightSamples={};for(let i=0;i0}set outdated(value){this.flags=(value?2:0)|this.flags&~2}setHeight(oracle,height){if(this.height!=height){if(Math.abs(this.height-height)>Epsilon)oracle.heightChanged=true;this.height=height}}replace(_from,_to,nodes){return HeightMap.of(nodes)}decomposeLeft(_to,result){result.push(this)}decomposeRight(_from,result){result.push(this)}applyChanges(decorations,oldDoc,oracle,changes){let me=this;for(let i=changes.length-1;i>=0;i--){let{fromA,toA,fromB,toB}=changes[i];let start=me.lineAt(fromA,QueryType.ByPosNoHeight,oldDoc,0,0);let end=start.to>=toA?start:me.lineAt(toA,QueryType.ByPosNoHeight,oldDoc,0,0);toB+=end.to-toA;toA=end.to;while(i>0&&start.from<=changes[i-1].toA){fromA=changes[i-1].fromA;fromB=changes[i-1].fromB;i--;if(fromAafter*2){let split=nodes[i-1];if(split.break)nodes.splice(--i,1,split.left,null,split.right);else nodes.splice(--i,1,split.left,split.right);j+=1+split.break;before-=split.size}else if(after>before*2){let split=nodes[j];if(split.break)nodes.splice(j,1,split.left,null,split.right);else nodes.splice(j,1,split.left,split.right);j+=2+split.break;after-=split.size}else{break}}else if(before=offset)f(this.blockAt(0,doc,top,offset))}updateHeight(oracle,offset=0,_force=false,measured){if(measured&&measured.from<=offset&&measured.more)this.setHeight(oracle,measured.heights[measured.index++]);this.outdated=false;return this}toString(){return`block(${this.length})`}}class HeightMapText extends HeightMapBlock{constructor(length,height){super(length,height,BlockType.Text);this.collapsed=0;this.widgetHeight=0}replace(_from,_to,nodes){let node=nodes[0];if(nodes.length==1&&(node instanceof HeightMapText||node instanceof HeightMapGap&&node.flags&4)&&Math.abs(this.length-node.length)<10){if(node instanceof HeightMapGap)node=new HeightMapText(node.length,this.height);else node.height=this.height;if(!this.outdated)node.outdated=false;return node}else{return HeightMap.of(nodes)}}updateHeight(oracle,offset=0,force=false,measured){if(measured&&measured.from<=offset&&measured.more)this.setHeight(oracle,measured.heights[measured.index++]);else if(force||this.outdated)this.setHeight(oracle,Math.max(this.widgetHeight,oracle.heightForLine(this.length-this.collapsed)));this.outdated=false;return this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class HeightMapGap extends HeightMap{constructor(length){super(length,0)}lines(doc,offset){let firstLine=doc.lineAt(offset).number,lastLine=doc.lineAt(offset+this.length).number;return{firstLine:firstLine,lastLine:lastLine,lineHeight:this.height/(lastLine-firstLine+1)}}blockAt(height,doc,top,offset){let{firstLine,lastLine,lineHeight}=this.lines(doc,offset);let line=Math.max(0,Math.min(lastLine-firstLine,Math.floor((height-top)/lineHeight)));let{from,length}=doc.line(firstLine+line);return new BlockInfo(from,length,top+lineHeight*line,lineHeight,BlockType.Text)}lineAt(value,type,doc,top,offset){if(type==QueryType.ByHeight)return this.blockAt(value,doc,top,offset);if(type==QueryType.ByPosNoHeight){let{from,to}=doc.lineAt(value);return new BlockInfo(from,to-from,0,0,BlockType.Text)}let{firstLine,lineHeight}=this.lines(doc,offset);let{from,length,number}=doc.lineAt(value);return new BlockInfo(from,length,top+lineHeight*(number-firstLine),lineHeight,BlockType.Text)}forEachLine(from,to,doc,top,offset,f){let{firstLine,lineHeight}=this.lines(doc,offset);for(let pos=Math.max(from,offset),end=Math.min(offset+this.length,to);pos<=end;){let line=doc.lineAt(pos);if(pos==from)top+=lineHeight*(line.number-firstLine);f(new BlockInfo(line.from,line.length,top,lineHeight,BlockType.Text));top+=lineHeight;pos=line.to+1}}replace(from,to,nodes){let after=this.length-to;if(after>0){let last=nodes[nodes.length-1];if(last instanceof HeightMapGap)nodes[nodes.length-1]=new HeightMapGap(last.length+after);else nodes.push(null,new HeightMapGap(after-1))}if(from>0){let first=nodes[0];if(first instanceof HeightMapGap)nodes[0]=new HeightMapGap(from+first.length);else nodes.unshift(new HeightMapGap(from-1),null)}return HeightMap.of(nodes)}decomposeLeft(to,result){result.push(new HeightMapGap(to-1),null)}decomposeRight(from,result){result.push(null,new HeightMapGap(this.length-from-1))}updateHeight(oracle,offset=0,force=false,measured){let end=offset+this.length;if(measured&&measured.from<=offset+this.length&&measured.more){let nodes=[],pos=Math.max(offset,measured.from),singleHeight=-1;let wasChanged=oracle.heightChanged;if(measured.from>offset)nodes.push(new HeightMapGap(measured.from-offset-1).updateHeight(oracle,offset));while(pos<=end&&measured.more){let len=oracle.doc.lineAt(pos).length;if(nodes.length)nodes.push(null);let height=measured.heights[measured.index++];if(singleHeight==-1)singleHeight=height;else if(Math.abs(height-singleHeight)>=Epsilon)singleHeight=-2;let line=new HeightMapText(len,height);line.outdated=false;nodes.push(line);pos+=len+1}if(pos<=end)nodes.push(null,new HeightMapGap(end-pos).updateHeight(oracle,pos));let result=HeightMap.of(nodes);oracle.heightChanged=wasChanged||singleHeight<0||Math.abs(result.height-this.height)>=Epsilon||Math.abs(singleHeight-this.lines(oracle.doc,offset).lineHeight)>=Epsilon;return result}else if(force||this.outdated){this.setHeight(oracle,oracle.heightForGap(offset,offset+this.length));this.outdated=false}return this}toString(){return`gap(${this.length})`}}class HeightMapBranch extends HeightMap{constructor(left,brk,right){super(left.length+brk+right.length,left.height+right.height,brk|(left.outdated||right.outdated?2:0));this.left=left;this.right=right;this.size=left.size+right.size}get break(){return this.flags&1}blockAt(height,doc,top,offset){let mid=top+this.left.height;return heightrightOffset))return base;let subQuery=type==QueryType.ByPosNoHeight?QueryType.ByPosNoHeight:QueryType.ByPos;if(left)return base.join(this.right.lineAt(rightOffset,subQuery,doc,rightTop,rightOffset));else return this.left.lineAt(rightOffset,subQuery,doc,top,offset).join(base)}forEachLine(from,to,doc,top,offset,f){let rightTop=top+this.left.height,rightOffset=offset+this.left.length+this.break;if(this.break){if(from=rightOffset)this.right.forEachLine(from,to,doc,rightTop,rightOffset,f)}else{let mid=this.lineAt(rightOffset,QueryType.ByPos,doc,top,offset);if(from=from&&mid.from<=to)f(mid);if(to>mid.to)this.right.forEachLine(mid.to+1,to,doc,rightTop,rightOffset,f)}}replace(from,to,nodes){let rightStart=this.left.length+this.break;if(tothis.left.length)return this.balanced(this.left,this.right.replace(from-rightStart,to-rightStart,nodes));let result=[];if(from>0)this.decomposeLeft(from,result);let left=result.length;for(let node of nodes)result.push(node);if(from>0)mergeGaps(result,left-1);if(to=left)result.push(null)}if(to>left)this.right.decomposeLeft(to-left,result)}decomposeRight(from,result){let left=this.left.length,right=left+this.break;if(from>=right)return this.right.decomposeRight(from-right,result);if(from2*right.size||right.size>2*left.size)return HeightMap.of(this.break?[left,null,right]:[left,right]);this.left=left;this.right=right;this.height=left.height+right.height;this.outdated=left.outdated||right.outdated;this.size=left.size+right.size;this.length=left.length+this.break+right.length;return this}updateHeight(oracle,offset=0,force=false,measured){let{left,right}=this,rightStart=offset+left.length+this.break,rebalance=null;if(measured&&measured.from<=offset+left.length&&measured.more)rebalance=left=left.updateHeight(oracle,offset,force,measured);else left.updateHeight(oracle,offset,force);if(measured&&measured.from<=rightStart+right.length&&measured.more)rebalance=right=right.updateHeight(oracle,rightStart,force,measured);else right.updateHeight(oracle,rightStart,force);if(rebalance)return this.balanced(left,right);this.height=this.left.height+this.right.height;this.outdated=false;return this}toString(){return this.left+(this.break?" ":"-")+this.right}}function mergeGaps(nodes,around){let before,after;if(nodes[around]==null&&(before=nodes[around-1])instanceof HeightMapGap&&(after=nodes[around+1])instanceof HeightMapGap)nodes.splice(around-1,3,new HeightMapGap(before.length+1+after.length))}const relevantWidgetHeight=5;class NodeBuilder{constructor(pos,oracle){this.pos=pos;this.oracle=oracle;this.nodes=[];this.lineStart=-1;this.lineEnd=-1;this.covering=null;this.writtenTo=pos}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(_from,to){if(this.lineStart>-1){let end=Math.min(to,this.lineEnd),last=this.nodes[this.nodes.length-1];if(last instanceof HeightMapText)last.length+=end-this.pos;else if(end>this.pos||!this.isCovered)this.nodes.push(new HeightMapText(end-this.pos,-1));this.writtenTo=end;if(to>end){this.nodes.push(null);this.writtenTo++;this.lineStart=-1}}this.pos=to}point(from,to,deco){if(from=relevantWidgetHeight){this.addLineDeco(height,len)}}else if(to>from){this.span(from,to)}if(this.lineEnd>-1&&this.lineEnd-1)return;let{from,to}=this.oracle.doc.lineAt(this.pos);this.lineStart=from;this.lineEnd=to;if(this.writtenTofrom)this.nodes.push(new HeightMapText(this.pos-from,-1));this.writtenTo=this.pos}blankContent(from,to){let gap=new HeightMapGap(to-from);if(this.oracle.doc.lineAt(from).to==to)gap.flags|=4;return gap}ensureLine(){this.enterLine();let last=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(last instanceof HeightMapText)return last;let line=new HeightMapText(0,-1);this.nodes.push(line);return line}addBlock(block){this.enterLine();if(block.type==BlockType.WidgetAfter&&!this.isCovered)this.ensureLine();this.nodes.push(block);this.writtenTo=this.pos=this.pos+block.length;if(block.type!=BlockType.WidgetBefore)this.covering=block}addLineDeco(height,length){let line=this.ensureLine();line.length+=length;line.collapsed+=length;line.widgetHeight=Math.max(line.widgetHeight,height);this.writtenTo=this.pos=this.pos+length}finish(from){let last=this.nodes.length==0?null:this.nodes[this.nodes.length-1];if(this.lineStart>-1&&!(last instanceof HeightMapText)&&!this.isCovered)this.nodes.push(new HeightMapText(0,-1));else if(this.writtenToelt.clientHeight||elt.scrollWidth>elt.clientWidth)&&style.overflow!="visible"){let parentRect=elt.getBoundingClientRect();left=Math.max(left,parentRect.left);right=Math.min(right,parentRect.right);top=Math.max(top,parentRect.top);bottom=parent==dom.parentNode?parentRect.bottom:Math.min(bottom,parentRect.bottom)}parent=style.position=="absolute"||style.position=="fixed"?elt.offsetParent:elt.parentNode}else if(parent.nodeType==11){parent=parent.host}else{break}}return{left:left-rect.left,right:Math.max(left,right)-rect.left,top:top-(rect.top+paddingTop),bottom:Math.max(top,bottom)-(rect.top+paddingTop)}}function fullPixelRange(dom,paddingTop){let rect=dom.getBoundingClientRect();return{left:0,right:rect.right-rect.left,top:paddingTop,bottom:rect.bottom-(rect.top+paddingTop)}}class LineGap{constructor(from,to,size){this.from=from;this.to=to;this.size=size}static same(a,b){if(a.length!=b.length)return false;for(let i=0;itypeof d!="function");this.heightMap=HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle.setDoc(state.doc),[new ChangedRange(0,0,0,state.doc.length)]);this.viewport=this.getViewport(0,null);this.updateViewportLines();this.updateForViewport();this.lineGaps=this.ensureLineGaps([]);this.lineGapDeco=Decoration.set(this.lineGaps.map(gap=>gap.draw(false)));this.computeVisibleRanges()}updateForViewport(){let viewports=[this.viewport],{main}=this.state.selection;for(let i=0;i<=1;i++){let pos=i?main.head:main.anchor;if(!viewports.some(({from,to})=>pos>=from&&pos<=to)){let{from,to}=this.lineBlockAt(pos);viewports.push(new Viewport(from,to))}}this.viewports=viewports.sort((a,b)=>a.from-b.from);this.scaler=this.heightMap.height<=7e6?IdScaler:new BigScaler(this.heightOracle.doc,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[];this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.state.doc,0,0,block=>{this.viewportLines.push(this.scaler.scale==1?block:scaleBlock(block,this.scaler))})}update(update,scrollTarget=null){this.state=update.state;let prevDeco=this.stateDeco;this.stateDeco=this.state.facet(decorations).filter(d=>typeof d!="function");let contentChanges=update.changedRanges;let heightChanges=ChangedRange.extendWithRanges(contentChanges,heightRelevantDecoChanges(prevDeco,this.stateDeco,update?update.changes:ChangeSet.empty(this.state.doc.length)));let prevHeight=this.heightMap.height;this.heightMap=this.heightMap.applyChanges(this.stateDeco,update.startState.doc,this.heightOracle.setDoc(this.state.doc),heightChanges);if(this.heightMap.height!=prevHeight)update.flags|=2;let viewport=heightChanges.length?this.mapViewport(this.viewport,update.changes):this.viewport;if(scrollTarget&&(scrollTarget.range.headviewport.to)||!this.viewportIsAppropriate(viewport))viewport=this.getViewport(0,scrollTarget);let updateLines=!update.changes.empty||update.flags&2||viewport.from!=this.viewport.from||viewport.to!=this.viewport.to;this.viewport=viewport;this.updateForViewport();if(updateLines)this.updateViewportLines();if(this.lineGaps.length||this.viewport.to-this.viewport.from>2e3<<1)this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,update.changes)));update.flags|=this.computeVisibleRanges();if(scrollTarget)this.scrollTarget=scrollTarget;if(!this.mustEnforceCursorAssoc&&update.selectionSet&&update.view.lineWrapping&&update.state.selection.main.empty&&update.state.selection.main.assoc)this.mustEnforceCursorAssoc=true}measure(view){let dom=view.contentDOM,style=window.getComputedStyle(dom);let oracle=this.heightOracle;let whiteSpace=style.whiteSpace;this.defaultTextDirection=style.direction=="rtl"?Direction.RTL:Direction.LTR;let refresh=this.heightOracle.mustRefreshForWrapping(whiteSpace);let measureContent=refresh||this.mustMeasureContent||this.contentDOMHeight!=dom.clientHeight;this.contentDOMHeight=dom.clientHeight;this.mustMeasureContent=false;let result=0,bias=0;let paddingTop=parseInt(style.paddingTop)||0,paddingBottom=parseInt(style.paddingBottom)||0;if(this.paddingTop!=paddingTop||this.paddingBottom!=paddingBottom){this.paddingTop=paddingTop;this.paddingBottom=paddingBottom;result|=8|2}if(this.editorWidth!=view.scrollDOM.clientWidth){if(oracle.lineWrapping)measureContent=true;this.editorWidth=view.scrollDOM.clientWidth;result|=8}let pixelViewport=(this.printing?fullPixelRange:visiblePixelRange)(dom,this.paddingTop);let dTop=pixelViewport.top-this.pixelViewport.top,dBottom=pixelViewport.bottom-this.pixelViewport.bottom;this.pixelViewport=pixelViewport;let inView=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(inView!=this.inView){this.inView=inView;if(inView)measureContent=true}if(!this.inView&&!this.scrollTarget)return 0;let contentWidth=dom.clientWidth;if(this.contentDOMWidth!=contentWidth||this.editorHeight!=view.scrollDOM.clientHeight){this.contentDOMWidth=contentWidth;this.editorHeight=view.scrollDOM.clientHeight;result|=8}if(measureContent){let lineHeights=view.docView.measureVisibleLineHeights(this.viewport);if(oracle.mustRefreshForHeights(lineHeights))refresh=true;if(refresh||oracle.lineWrapping&&Math.abs(contentWidth-this.contentDOMWidth)>oracle.charWidth){let{lineHeight,charWidth}=view.docView.measureTextSize();refresh=lineHeight>0&&oracle.refresh(whiteSpace,lineHeight,charWidth,contentWidth/charWidth,lineHeights);if(refresh){view.docView.minWidth=0;result|=8}}if(dTop>0&&dBottom>0)bias=Math.max(dTop,dBottom);else if(dTop<0&&dBottom<0)bias=Math.min(dTop,dBottom);oracle.heightChanged=false;for(let vp of this.viewports){let heights=vp.from==this.viewport.from?lineHeights:view.docView.measureVisibleLineHeights(vp);this.heightMap=this.heightMap.updateHeight(oracle,0,refresh,new MeasuredHeights(vp.from,heights))}if(oracle.heightChanged)result|=2}let viewportChange=!this.viewportIsAppropriate(this.viewport,bias)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);if(viewportChange)this.viewport=this.getViewport(bias,this.scrollTarget);this.updateForViewport();if(result&2||viewportChange)this.updateViewportLines();if(this.lineGaps.length||this.viewport.to-this.viewport.from>2e3<<1)this.updateLineGaps(this.ensureLineGaps(refresh?[]:this.lineGaps,view));result|=this.computeVisibleRanges();if(this.mustEnforceCursorAssoc){this.mustEnforceCursorAssoc=false;view.docView.enforceCursorAssoc()}return result}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(bias,scrollTarget){let marginTop=.5-Math.max(-.5,Math.min(.5,bias/1e3/2));let map=this.heightMap,doc=this.state.doc,{visibleTop,visibleBottom}=this;let viewport=new Viewport(map.lineAt(visibleTop-marginTop*1e3,QueryType.ByHeight,doc,0,0).from,map.lineAt(visibleBottom+(1-marginTop)*1e3,QueryType.ByHeight,doc,0,0).to);if(scrollTarget){let{head}=scrollTarget.range;if(headviewport.to){let viewHeight=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top);let block=map.lineAt(head,QueryType.ByPos,doc,0,0),topPos;if(scrollTarget.y=="center")topPos=(block.top+block.bottom)/2-viewHeight/2;else if(scrollTarget.y=="start"||scrollTarget.y=="nearest"&&head=visibleBottom+Math.max(10,Math.min(bias,250)))&&(top>visibleTop-2*1e3&&bottom>1,doubleMargin=margin<<1;if(this.defaultTextDirection!=Direction.LTR&&!wrapping)return[];let gaps=[];let addGap=(from,to,line,structure)=>{if(to-fromfrom&&posgap.from>=line.from&&gap.to<=line.to&&Math.abs(gap.from-from)gap.frompos));if(!gap){if(tor.from<=to&&r.to>=to)){let lineStart=mayMeasure.moveToLineBoundary(EditorSelection.cursor(to),false,true).head;if(lineStart>from)to=lineStart}gap=new LineGap(from,to,this.gapSize(line,from,to,structure))}gaps.push(gap)};for(let line of this.viewportLines){if(line.lengthline.from)addGap(line.from,viewFrom,line,structure);if(viewTogap.draw(this.heightOracle.lineWrapping)))}}computeVisibleRanges(){let deco=this.stateDeco;if(this.lineGaps.length)deco=deco.concat(this.lineGapDeco);let ranges=[];RangeSet.spans(deco,this.viewport.from,this.viewport.to,{span(from,to){ranges.push({from:from,to:to})},point(){}},20);let changed=ranges.length!=this.visibleRanges.length||this.visibleRanges.some((r,i)=>r.from!=ranges[i].from||r.to!=ranges[i].to);this.visibleRanges=ranges;return changed?4:0}lineBlockAt(pos){return pos>=this.viewport.from&&pos<=this.viewport.to&&this.viewportLines.find(b=>b.from<=pos&&b.to>=pos)||scaleBlock(this.heightMap.lineAt(pos,QueryType.ByPos,this.state.doc,0,0),this.scaler)}lineBlockAtHeight(height){return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height),QueryType.ByHeight,this.state.doc,0,0),this.scaler)}elementAtHeight(height){return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height),this.state.doc,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class Viewport{constructor(from,to){this.from=from;this.to=to}}function lineStructure(from,to,stateDeco){let ranges=[],pos=from,total=0;RangeSet.spans(stateDeco,from,to,{span(){},point(from,to){if(from>pos){ranges.push({from:pos,to:from});total+=from-pos}pos=to}},20);if(pos=1)return ranges[ranges.length-1].to;let dist=Math.floor(total*ratio);for(let i=0;;i++){let{from,to}=ranges[i],size=to-from;if(dist<=size)return from+dist;dist-=size}}function findFraction(structure,pos){let counted=0;for(let{from,to}of structure.ranges){if(pos<=to){counted+=pos-from;break}counted+=to-from}return counted/structure.total}function find(array,f){for(let val of array)if(f(val))return val;return undefined}const IdScaler={toDOM(n){return n},fromDOM(n){return n},scale:1};class BigScaler{constructor(doc,heightMap,viewports){let vpHeight=0,base=0,domBase=0;this.viewports=viewports.map(({from,to})=>{let top=heightMap.lineAt(from,QueryType.ByPos,doc,0,0).top;let bottom=heightMap.lineAt(to,QueryType.ByPos,doc,0,0).bottom;vpHeight+=bottom-top;return{from:from,to:to,top:top,bottom:bottom,domTop:0,domBottom:0}});this.scale=(7e6-vpHeight)/(heightMap.height-vpHeight);for(let obj of this.viewports){obj.domTop=domBase+(obj.top-base)*this.scale;domBase=obj.domBottom=obj.domTop+(obj.bottom-obj.top);base=obj.bottom}}toDOM(n){for(let i=0,base=0,domBase=0;;i++){let vp=iscaleBlock(b,scaler)):block.type)}const theme=Facet.define({combine:strs=>strs.join(" ")});const darkTheme=Facet.define({combine:values=>values.indexOf(true)>-1});const baseThemeID=StyleModule.newName(),baseLightID=StyleModule.newName(),baseDarkID=StyleModule.newName();const lightDarkIDs={"&light":"."+baseLightID,"&dark":"."+baseDarkID};function buildTheme(main,spec,scopes){return new StyleModule(spec,{finish(sel){return/&/.test(sel)?sel.replace(/&\w*/,m=>{if(m=="&")return main;if(!scopes||!scopes[m])throw new RangeError(`Unsupported selector: ${m}`);return scopes[m]}):main+" "+sel}})}const baseTheme$1=buildTheme("."+baseThemeID,{"&.cm-editor":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,minHeight:"100%",display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 4px"},".cm-selectionLayer":{zIndex:-1,contain:"size style"},".cm-selectionBackground":{position:"absolute"},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{zIndex:100,contain:"size style",pointerEvents:"none"},"&.cm-focused .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{position:"absolute",borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},"&.cm-focused .cm-cursor":{display:"block"},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",left:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},lightDarkIDs);class DOMChange{constructor(view,start,end,typeOver){this.typeOver=typeOver;this.bounds=null;this.text="";let{impreciseHead:iHead,impreciseAnchor:iAnchor}=view.docView;if(start>-1&&!view.state.readOnly&&(this.bounds=view.docView.domBoundsAround(start,end,0))){let selPoints=iHead||iAnchor?[]:selectionPoints(view);let reader=new DOMReader(selPoints,view.state);reader.readRange(this.bounds.startDOM,this.bounds.endDOM);this.text=reader.text;this.newSel=selectionFromPoints(selPoints,this.bounds.from)}else{let domSel=view.observer.selectionRange;let head=iHead&&iHead.node==domSel.focusNode&&iHead.offset==domSel.focusOffset||!contains(view.contentDOM,domSel.focusNode)?view.state.selection.main.head:view.docView.posFromDOM(domSel.focusNode,domSel.focusOffset);let anchor=iAnchor&&iAnchor.node==domSel.anchorNode&&iAnchor.offset==domSel.anchorOffset||!contains(view.contentDOM,domSel.anchorNode)?view.state.selection.main.anchor:view.docView.posFromDOM(domSel.anchorNode,domSel.anchorOffset);this.newSel=EditorSelection.single(anchor,head)}}}function applyDOMChange(view,domChange){let change;let{newSel}=domChange,sel=view.state.selection.main;if(domChange.bounds){let{from,to}=domChange.bounds;let preferredPos=sel.from,preferredSide=null;if(view.inputState.lastKeyCode===8&&view.inputState.lastKeyTime>Date.now()-100||browser.android&&domChange.text.length=sel.from&&change.to<=sel.to&&(change.from!=sel.from||change.to!=sel.to)&&sel.to-sel.from-(change.to-change.from)<=4){change={from:sel.from,to:sel.to,insert:view.state.doc.slice(sel.from,change.from).append(change.insert).append(view.state.doc.slice(change.to,sel.to))}}else if((browser.mac||browser.android)&&change&&change.from==change.to&&change.from==sel.head-1&&/^\. ?$/.test(change.insert.toString())){if(newSel&&change.insert.length==2)newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1);change={from:sel.from,to:sel.to,insert:Text.of([" "])}}else if(browser.chrome&&change&&change.from==change.to&&change.from==sel.head&&change.insert.toString()=="\n "&&view.lineWrapping){if(newSel)newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1);change={from:sel.from,to:sel.to,insert:Text.of([" "])}}if(change){let startState=view.state;if(browser.ios&&view.inputState.flushIOSKey(view))return true;if(browser.android&&(change.from==sel.from&&change.to==sel.to&&change.insert.length==1&&change.insert.lines==2&&dispatchKey(view.contentDOM,"Enter",13)||change.from==sel.from-1&&change.to==sel.to&&change.insert.length==0&&dispatchKey(view.contentDOM,"Backspace",8)||change.from==sel.from&&change.to==sel.to+1&&change.insert.length==0&&dispatchKey(view.contentDOM,"Delete",46)))return true;let text=change.insert.toString();if(view.state.facet(inputHandler).some(h=>h(view,change.from,change.to,text)))return true;if(view.inputState.composing>=0)view.inputState.composing++;let tr;if(change.from>=sel.from&&change.to<=sel.to&&change.to-change.from>=(sel.to-sel.from)/3&&(!newSel||newSel.main.empty&&newSel.main.from==change.from+change.insert.length)&&view.inputState.composing<0){let before=sel.fromchange.to?startState.sliceDoc(change.to,sel.to):"";tr=startState.replaceSelection(view.state.toText(before+change.insert.sliceString(0,undefined,view.state.lineBreak)+after))}else{let changes=startState.changes(change);let mainSel=newSel&&!startState.selection.main.eq(newSel.main)&&newSel.main.to<=changes.newLength?newSel.main:undefined;if(startState.selection.ranges.length>1&&view.inputState.composing>=0&&change.to<=sel.to&&change.to>=sel.to-10){let replaced=view.state.sliceDoc(change.from,change.to);let compositionRange=compositionSurroundingNode(view)||view.state.doc.lineAt(sel.head);let offset=sel.to-change.to,size=sel.to-sel.from;tr=startState.changeByRange(range=>{if(range.from==sel.from&&range.to==sel.to)return{changes:changes,range:mainSel||range.map(changes)};let to=range.to-offset,from=to-replaced.length;if(range.to-range.from!=size||view.state.sliceDoc(from,to)!=replaced||compositionRange&&range.to>=compositionRange.from&&range.from<=compositionRange.to)return{range:range};let rangeChanges=startState.changes({from:from,to:to,insert:change.insert}),selOff=range.to-sel.to;return{changes:rangeChanges,range:!mainSel?range.map(rangeChanges):EditorSelection.range(Math.max(0,mainSel.anchor+selOff),Math.max(0,mainSel.head+selOff))}})}else{tr={changes:changes,selection:mainSel&&startState.selection.replaceRange(mainSel)}}}let userEvent="input.type";if(view.composing){userEvent+=".compose";if(view.inputState.compositionFirstChange){userEvent+=".start";view.inputState.compositionFirstChange=false}}view.dispatch(tr,{scrollIntoView:true,userEvent:userEvent});return true}else if(newSel&&!newSel.main.eq(sel)){let scrollIntoView=false,userEvent="select";if(view.inputState.lastSelectionTime>Date.now()-50){if(view.inputState.lastSelectionOrigin=="select")scrollIntoView=true;userEvent=view.inputState.lastSelectionOrigin}view.dispatch({selection:newSel,scrollIntoView:scrollIntoView,userEvent:userEvent});return true}else{return false}}function findDiff(a,b,preferredPos,preferredSide){let minLen=Math.min(a.length,b.length);let from=0;while(from0&&toB>0&&a.charCodeAt(toA-1)==b.charCodeAt(toB-1)){toA--;toB--}if(preferredSide=="end"){let adjust=Math.max(0,from-Math.min(toA,toB));preferredPos-=toA+adjust-from}if(toA=toA?from-preferredPos:0;from-=move;toB=from+(toB-toA);toA=from}else if(toB=toB?from-preferredPos:0;from-=move;toA=from+(toA-toB);toB=from}return{from:from,toA:toA,toB:toB}}function selectionPoints(view){let result=[];if(view.root.activeElement!=view.contentDOM)return result;let{anchorNode,anchorOffset,focusNode,focusOffset}=view.observer.selectionRange;if(anchorNode){result.push(new DOMPoint(anchorNode,anchorOffset));if(focusNode!=anchorNode||focusOffset!=anchorOffset)result.push(new DOMPoint(focusNode,focusOffset))}return result}function selectionFromPoints(points,base){if(points.length==0)return null;let anchor=points[0].pos,head=points.length==2?points[1].pos:anchor;return anchor>-1&&head>-1?EditorSelection.single(anchor+base,head+base):null}const observeOptions={childList:true,characterData:true,subtree:true,attributes:true,characterDataOldValue:true};const useCharData=browser.ie&&browser.ie_version<=11;class DOMObserver{constructor(view){this.view=view;this.active=false;this.selectionRange=new DOMSelectionState;this.selectionChanged=false;this.delayedFlush=-1;this.resizeTimeout=-1;this.queue=[];this.delayedAndroidKey=null;this.flushingAndroidKey=-1;this.lastChange=0;this.scrollTargets=[];this.intersection=null;this.resize=null;this.intersecting=false;this.gapIntersection=null;this.gaps=[];this.parentCheck=-1;this.dom=view.contentDOM;this.observer=new MutationObserver(mutations=>{for(let mut of mutations)this.queue.push(mut);if((browser.ie&&browser.ie_version<=11||browser.ios&&view.composing)&&mutations.some(m=>m.type=="childList"&&m.removedNodes.length||m.type=="characterData"&&m.oldValue.length>m.target.nodeValue.length))this.flushSoon();else this.flush()});if(useCharData)this.onCharData=event=>{this.queue.push({target:event.target,type:"characterData",oldValue:event.prevValue});this.flushSoon()};this.onSelectionChange=this.onSelectionChange.bind(this);this.onResize=this.onResize.bind(this);this.onPrint=this.onPrint.bind(this);this.onScroll=this.onScroll.bind(this);if(typeof ResizeObserver=="function"){this.resize=new ResizeObserver(()=>{if(this.view.docView.lastUpdate{if(this.parentCheck<0)this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3);if(entries.length>0&&entries[entries.length-1].intersectionRatio>0!=this.intersecting){this.intersecting=!this.intersecting;if(this.intersecting!=this.view.inView)this.onScrollChanged(document.createEvent("Event"))}},{});this.intersection.observe(this.dom);this.gapIntersection=new IntersectionObserver(entries=>{if(entries.length>0&&entries[entries.length-1].intersectionRatio>0)this.onScrollChanged(document.createEvent("Event"))},{})}this.listenForScroll();this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runScrollHandlers(this.view,e);if(this.intersecting)this.view.measure()}onScroll(e){if(this.intersecting)this.flush(false);this.onScrollChanged(e)}onResize(){if(this.resizeTimeout<0)this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1;this.view.requestMeasure()},50)}onPrint(){this.view.viewState.printing=true;this.view.measure();setTimeout(()=>{this.view.viewState.printing=false;this.view.requestMeasure()},500)}updateGaps(gaps){if(this.gapIntersection&&(gaps.length!=this.gaps.length||this.gaps.some((g,i)=>g!=gaps[i]))){this.gapIntersection.disconnect();for(let gap of gaps)this.gapIntersection.observe(gap);this.gaps=gaps}}onSelectionChange(event){let wasChanged=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view}=this,sel=this.selectionRange;if(view.state.facet(editable)?view.root.activeElement!=this.dom:!hasSelection(view.dom,sel))return;let context=sel.anchorNode&&view.docView.nearest(sel.anchorNode);if(context&&context.ignoreEvent(event)){if(!wasChanged)this.selectionChanged=false;return}if((browser.ie&&browser.ie_version<=11||browser.android&&browser.chrome)&&!view.state.selection.main.empty&&sel.focusNode&&isEquivalentPosition(sel.focusNode,sel.focusOffset,sel.anchorNode,sel.anchorOffset))this.flushSoon();else this.flush(false)}readSelectionRange(){let{view}=this;let range=browser.safari&&view.root.nodeType==11&&deepActiveElement(this.dom.ownerDocument)==this.dom&&safariSelectionRangeHack(this.view)||getSelection(view.root);if(!range||this.selectionRange.eq(range))return false;let local=hasSelection(this.dom,range);if(local&&!this.selectionChanged&&view.inputState.lastFocusTime>Date.now()-200&&view.inputState.lastTouchTime{let key=this.delayedAndroidKey;if(key){this.clearDelayedAndroidKey();if(!this.flush()&&key.force)dispatchKey(this.dom,key.key,key.keyCode)}};this.flushingAndroidKey=this.view.win.requestAnimationFrame(flush)}if(!this.delayedAndroidKey||key=="Enter")this.delayedAndroidKey={key:key,keyCode:keyCode,force:this.lastChange{this.delayedFlush=-1;this.flush()})}forceFlush(){if(this.delayedFlush>=0){this.view.win.cancelAnimationFrame(this.delayedFlush);this.delayedFlush=-1}this.flush()}processRecords(){let records=this.queue;for(let mut of this.observer.takeRecords())records.push(mut);if(records.length)this.queue=[];let from=-1,to=-1,typeOver=false;for(let record of records){let range=this.readMutation(record);if(!range)continue;if(range.typeOver)typeOver=true;if(from==-1){({from,to}=range)}else{from=Math.min(range.from,from);to=Math.max(range.to,to)}}return{from:from,to:to,typeOver:typeOver}}readChange(){let{from,to,typeOver}=this.processRecords();let newSel=this.selectionChanged&&hasSelection(this.dom,this.selectionRange);if(from<0&&!newSel)return null;if(from>-1)this.lastChange=Date.now();this.view.inputState.lastFocusTime=0;this.selectionChanged=false;return new DOMChange(this.view,from,to,typeOver)}flush(readSelection=true){if(this.delayedFlush>=0||this.delayedAndroidKey)return false;if(readSelection)this.readSelectionRange();let domChange=this.readChange();if(!domChange)return false;let startState=this.view.state;let handled=applyDOMChange(this.view,domChange);if(this.view.state==startState)this.view.update([]);return handled}readMutation(rec){let cView=this.view.docView.nearest(rec.target);if(!cView||cView.ignoreMutation(rec))return null;cView.markDirty(rec.type=="attributes");if(rec.type=="attributes")cView.dirty|=4;if(rec.type=="childList"){let childBefore=findChild(cView,rec.previousSibling||rec.target.previousSibling,-1);let childAfter=findChild(cView,rec.nextSibling||rec.target.nextSibling,1);return{from:childBefore?cView.posAfter(childBefore):cView.posAtStart,to:childAfter?cView.posBefore(childAfter):cView.posAtEnd,typeOver:false}}else if(rec.type=="characterData"){return{from:cView.posAtStart,to:cView.posAtEnd,typeOver:rec.target.nodeValue==rec.oldValue}}else{return null}}setWindow(win){if(win!=this.win){this.removeWindowListeners(this.win);this.win=win;this.addWindowListeners(this.win)}}addWindowListeners(win){win.addEventListener("resize",this.onResize);win.addEventListener("beforeprint",this.onPrint);win.addEventListener("scroll",this.onScroll);win.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(win){win.removeEventListener("scroll",this.onScroll);win.removeEventListener("resize",this.onResize);win.removeEventListener("beforeprint",this.onPrint);win.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var _a,_b,_c;this.stop();(_a=this.intersection)===null||_a===void 0?void 0:_a.disconnect();(_b=this.gapIntersection)===null||_b===void 0?void 0:_b.disconnect();(_c=this.resize)===null||_c===void 0?void 0:_c.disconnect();for(let dom of this.scrollTargets)dom.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win);clearTimeout(this.parentCheck);clearTimeout(this.resizeTimeout);this.win.cancelAnimationFrame(this.delayedFlush);this.win.cancelAnimationFrame(this.flushingAndroidKey)}}function findChild(cView,dom,dir){while(dom){let curView=ContentView.get(dom);if(curView&&curView.parent==cView)return curView;let parent=dom.parentNode;dom=parent!=cView.dom?parent:dir>0?dom.nextSibling:dom.previousSibling}return null}function safariSelectionRangeHack(view){let found=null;function read(event){event.preventDefault();event.stopImmediatePropagation();found=event.getTargetRanges()[0]}view.contentDOM.addEventListener("beforeinput",read,true);view.dom.ownerDocument.execCommand("indent");view.contentDOM.removeEventListener("beforeinput",read,true);if(!found)return null;let anchorNode=found.startContainer,anchorOffset=found.startOffset;let focusNode=found.endContainer,focusOffset=found.endOffset;let curAnchor=view.docView.domAtPos(view.state.selection.main.anchor);if(isEquivalentPosition(curAnchor.node,curAnchor.offset,focusNode,focusOffset))[anchorNode,anchorOffset,focusNode,focusOffset]=[focusNode,focusOffset,anchorNode,anchorOffset];return{anchorNode:anchorNode,anchorOffset:anchorOffset,focusNode:focusNode,focusOffset:focusOffset}}class EditorView{constructor(config={}){this.plugins=[];this.pluginMap=new Map;this.editorAttrs={};this.contentAttrs={};this.bidiCache=[];this.destroyed=false;this.updateState=2;this.measureScheduled=-1;this.measureRequests=[];this.contentDOM=document.createElement("div");this.scrollDOM=document.createElement("div");this.scrollDOM.tabIndex=-1;this.scrollDOM.className="cm-scroller";this.scrollDOM.appendChild(this.contentDOM);this.announceDOM=document.createElement("div");this.announceDOM.style.cssText="position: absolute; top: -10000px";this.announceDOM.setAttribute("aria-live","polite");this.dom=document.createElement("div");this.dom.appendChild(this.announceDOM);this.dom.appendChild(this.scrollDOM);this._dispatch=config.dispatch||(tr=>this.update([tr]));this.dispatch=this.dispatch.bind(this);this._root=config.root||getRoot(config.parent)||document;this.viewState=new ViewState(config.state||EditorState.create(config));this.plugins=this.state.facet(viewPlugin).map(spec=>new PluginInstance(spec));for(let plugin of this.plugins)plugin.update(this);this.observer=new DOMObserver(this);this.inputState=new InputState(this);this.inputState.ensureHandlers(this,this.plugins);this.docView=new DocView(this);this.mountStyles();this.updateAttrs();this.updateState=0;this.requestMeasure();if(config.parent)config.parent.appendChild(this.dom)}get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}dispatch(...input){this._dispatch(input.length==1&&input[0]instanceof Transaction?input[0]:this.state.update(...input))}update(transactions){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let redrawn=false,attrsChanged=false,update;let state=this.state;for(let tr of transactions){if(tr.startState!=state)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");state=tr.state}if(this.destroyed){this.viewState.state=state;return}let pendingKey=this.observer.delayedAndroidKey,domChange=null;if(pendingKey){this.observer.clearDelayedAndroidKey();domChange=this.observer.readChange();if(domChange&&!this.state.doc.eq(state.doc)||!this.state.selection.eq(state.selection))domChange=null}else{this.observer.clear()}if(state.facet(EditorState.phrases)!=this.state.facet(EditorState.phrases))return this.setState(state);update=ViewUpdate.create(this,state,transactions);let scrollTarget=this.viewState.scrollTarget;try{this.updateState=2;for(let tr of transactions){if(scrollTarget)scrollTarget=scrollTarget.map(tr.changes);if(tr.scrollIntoView){let{main}=tr.state.selection;scrollTarget=new ScrollTarget(main.empty?main:EditorSelection.cursor(main.head,main.head>main.anchor?-1:1))}for(let e of tr.effects)if(e.is(scrollIntoView))scrollTarget=e.value}this.viewState.update(update,scrollTarget);this.bidiCache=CachedOrder.update(this.bidiCache,update.changes);if(!update.empty){this.updatePlugins(update);this.inputState.update(update)}redrawn=this.docView.update(update);if(this.state.facet(styleModule)!=this.styleModules)this.mountStyles();attrsChanged=this.updateAttrs();this.showAnnouncements(transactions);this.docView.updateSelection(redrawn,transactions.some(tr=>tr.isUserEvent("select.pointer")))}finally{this.updateState=0}if(update.startState.facet(theme)!=update.state.facet(theme))this.viewState.mustMeasureContent=true;if(redrawn||attrsChanged||scrollTarget||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)this.requestMeasure();if(!update.empty)for(let listener of this.state.facet(updateListener))listener(update);if(domChange){if(!applyDOMChange(this,domChange)&&pendingKey.force)dispatchKey(this.contentDOM,pendingKey.key,pendingKey.keyCode)}}setState(newState){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=newState;return}this.updateState=2;let hadFocus=this.hasFocus;try{for(let plugin of this.plugins)plugin.destroy(this);this.viewState=new ViewState(newState);this.plugins=newState.facet(viewPlugin).map(spec=>new PluginInstance(spec));this.pluginMap.clear();for(let plugin of this.plugins)plugin.update(this);this.docView=new DocView(this);this.inputState.ensureHandlers(this,this.plugins);this.mountStyles();this.updateAttrs();this.bidiCache=[]}finally{this.updateState=0}if(hadFocus)this.focus();this.requestMeasure()}updatePlugins(update){let prevSpecs=update.startState.facet(viewPlugin),specs=update.state.facet(viewPlugin);if(prevSpecs!=specs){let newPlugins=[];for(let spec of specs){let found=prevSpecs.indexOf(spec);if(found<0){newPlugins.push(new PluginInstance(spec))}else{let plugin=this.plugins[found];plugin.mustUpdate=update;newPlugins.push(plugin)}}for(let plugin of this.plugins)if(plugin.mustUpdate!=update)plugin.destroy(this);this.plugins=newPlugins;this.pluginMap.clear();this.inputState.ensureHandlers(this,this.plugins)}else{for(let p of this.plugins)p.mustUpdate=update}for(let i=0;i-1)cancelAnimationFrame(this.measureScheduled);this.measureScheduled=0;if(flush)this.observer.forceFlush();let updated=null;let{scrollHeight,scrollTop,clientHeight}=this.scrollDOM;let refHeight=scrollTop>scrollHeight-clientHeight-4?scrollHeight:scrollTop;try{for(let i=0;;i++){this.updateState=1;let oldViewport=this.viewport;let refBlock=this.viewState.lineBlockAtHeight(refHeight);let changed=this.viewState.measure(this);if(!changed&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(i>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let measuring=[];if(!(changed&4))[this.measureRequests,measuring]=[measuring,this.measureRequests];let measured=measuring.map(m=>{try{return m.read(this)}catch(e){logException(this.state,e);return BadMeasure}});let update=ViewUpdate.create(this,this.state,[]),redrawn=false,scrolled=false;update.flags|=changed;if(!updated)updated=update;else updated.flags|=changed;this.updateState=2;if(!update.empty){this.updatePlugins(update);this.inputState.update(update);this.updateAttrs();redrawn=this.docView.update(update)}for(let i=0;i1||diff<-1){this.scrollDOM.scrollTop+=diff;scrolled=true}}}if(redrawn)this.docView.updateSelection(true);if(this.viewport.from==oldViewport.from&&this.viewport.to==oldViewport.to&&!scrolled&&this.measureRequests.length==0)break}}finally{this.updateState=0;this.measureScheduled=-1}if(updated&&!updated.empty)for(let listener of this.state.facet(updateListener))listener(updated)}get themeClasses(){return baseThemeID+" "+(this.state.facet(darkTheme)?baseDarkID:baseLightID)+" "+this.state.facet(theme)}updateAttrs(){let editorAttrs=attrsFromFacet(this,editorAttributes,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses});let contentAttrs={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:!this.state.facet(editable)?"false":"true",class:"cm-content",style:`${browser.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};if(this.state.readOnly)contentAttrs["aria-readonly"]="true";attrsFromFacet(this,contentAttributes,contentAttrs);let changed=this.observer.ignore(()=>{let changedContent=updateAttrs(this.contentDOM,this.contentAttrs,contentAttrs);let changedEditor=updateAttrs(this.dom,this.editorAttrs,editorAttrs);return changedContent||changedEditor});this.editorAttrs=editorAttrs;this.contentAttrs=contentAttrs;return changed}showAnnouncements(trs){let first=true;for(let tr of trs)for(let effect of tr.effects)if(effect.is(EditorView.announce)){if(first)this.announceDOM.textContent="";first=false;let div=this.announceDOM.appendChild(document.createElement("div"));div.textContent=effect.value}}mountStyles(){this.styleModules=this.state.facet(styleModule);StyleModule.mount(this.root,this.styleModules.concat(baseTheme$1).reverse())}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");if(this.updateState==0&&this.measureScheduled>-1)this.measure(false)}requestMeasure(request){if(this.measureScheduled<0)this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure());if(request){if(request.key!=null)for(let i=0;ip.spec==plugin)||null);return known&&known.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}elementAtHeight(height){this.readMeasured();return this.viewState.elementAtHeight(height)}lineBlockAtHeight(height){this.readMeasured();return this.viewState.lineBlockAtHeight(height)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(pos){return this.viewState.lineBlockAt(pos)}get contentHeight(){return this.viewState.contentHeight}moveByChar(start,forward,by){return skipAtoms(this,start,moveByChar(this,start,forward,by))}moveByGroup(start,forward){return skipAtoms(this,start,moveByChar(this,start,forward,initial=>byGroup(this,start.head,initial)))}moveToLineBoundary(start,forward,includeWrap=true){return moveToLineBoundary(this,start,forward,includeWrap)}moveVertically(start,forward,distance){return skipAtoms(this,start,moveVertically(this,start,forward,distance))}domAtPos(pos){return this.docView.domAtPos(pos)}posAtDOM(node,offset=0){return this.docView.posFromDOM(node,offset)}posAtCoords(coords,precise=true){this.readMeasured();return posAtCoords(this,coords,precise)}coordsAtPos(pos,side=1){this.readMeasured();let rect=this.docView.coordsAt(pos,side);if(!rect||rect.left==rect.right)return rect;let line=this.state.doc.lineAt(pos),order=this.bidiSpans(line);let span=order[BidiSpan.find(order,pos-line.from,-1,side)];return flattenRect(rect,span.dir==Direction.LTR==side>0)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(pos){let perLine=this.state.facet(perLineTextDirection);if(!perLine||posthis.viewport.to)return this.textDirection;this.readMeasured();return this.docView.textDirectionAt(pos)}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(line){if(line.length>MaxBidiLine)return trivialOrder(line.length);let dir=this.textDirectionAt(line.from);for(let entry of this.bidiCache)if(entry.from==line.from&&entry.dir==dir)return entry.order;let order=computeOrder(line.text,dir);this.bidiCache.push(new CachedOrder(line.from,line.to,dir,order));return order}get hasFocus(){var _a;return(this.dom.ownerDocument.hasFocus()||browser.safari&&((_a=this.inputState)===null||_a===void 0?void 0:_a.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{focusPreventScroll(this.contentDOM);this.docView.updateSelection()})}setRoot(root){if(this._root!=root){this._root=root;this.observer.setWindow((root.nodeType==9?root:root.ownerDocument).defaultView||window);this.mountStyles()}}destroy(){for(let plugin of this.plugins)plugin.destroy(this);this.plugins=[];this.inputState.destroy();this.dom.remove();this.observer.destroy();if(this.measureScheduled>-1)cancelAnimationFrame(this.measureScheduled);this.destroyed=true}static scrollIntoView(pos,options={}){return scrollIntoView.of(new ScrollTarget(typeof pos=="number"?EditorSelection.cursor(pos):pos,options.y,options.x,options.yMargin,options.xMargin))}static domEventHandlers(handlers){return ViewPlugin.define(()=>({}),{eventHandlers:handlers})}static theme(spec,options){let prefix=StyleModule.newName();let result=[theme.of(prefix),styleModule.of(buildTheme(`.${prefix}`,spec))];if(options&&options.dark)result.push(darkTheme.of(true));return result}static baseTheme(spec){return Prec.lowest(styleModule.of(buildTheme("."+baseThemeID,spec,lightDarkIDs)))}static findFromDOM(dom){var _a;let content=dom.querySelector(".cm-content");let cView=content&&ContentView.get(content)||ContentView.get(dom);return((_a=cView===null||cView===void 0?void 0:cView.rootView)===null||_a===void 0?void 0:_a.view)||null}}EditorView.styleModule=styleModule;EditorView.inputHandler=inputHandler;EditorView.perLineTextDirection=perLineTextDirection;EditorView.exceptionSink=exceptionSink;EditorView.updateListener=updateListener;EditorView.editable=editable;EditorView.mouseSelectionStyle=mouseSelectionStyle;EditorView.dragMovesSelection=dragMovesSelection$1;EditorView.clickAddsSelectionRange=clickAddsSelectionRange;EditorView.decorations=decorations;EditorView.atomicRanges=atomicRanges;EditorView.scrollMargins=scrollMargins;EditorView.darkTheme=darkTheme;EditorView.contentAttributes=contentAttributes;EditorView.editorAttributes=editorAttributes;EditorView.lineWrapping=EditorView.contentAttributes.of({class:"cm-lineWrapping"});EditorView.announce=StateEffect.define();const MaxBidiLine=4096;const BadMeasure={};class CachedOrder{constructor(from,to,dir,order){this.from=from;this.to=to;this.dir=dir;this.order=order}static update(cache,changes){if(changes.empty)return cache;let result=[],lastDir=cache.length?cache[cache.length-1].dir:Direction.LTR;for(let i=Math.max(0,cache.length-10);i=0;i--){let source=sources[i],value=typeof source=="function"?source(view):source;if(value)combineAttrs(value,base)}return base}const currentPlatform=browser.mac?"mac":browser.windows?"win":browser.linux?"linux":"key";function normalizeKeyName(name,platform){const parts=name.split(/-(?!$)/);let result=parts[parts.length-1];if(result=="Space")result=" ";let alt,ctrl,shift,meta;for(let i=0;ia.concat(b),[])));return map}function runScopeHandlers(view,event,scope){return runHandlers(getKeymap(view.state),event,view,scope)}let storedPrefix=null;const PrefixTimeout=4e3;function buildKeymap(bindings,platform=currentPlatform){let bound=Object.create(null);let isPrefix=Object.create(null);let checkPrefix=(name,is)=>{let current=isPrefix[name];if(current==null)isPrefix[name]=is;else if(current!=is)throw new Error("Key binding "+name+" is used both as a regular binding and as a multi-stroke prefix")};let add=(scope,key,command,preventDefault)=>{var _a,_b;let scopeObj=bound[scope]||(bound[scope]=Object.create(null));let parts=key.split(/ (?!$)/).map(k=>normalizeKeyName(k,platform));for(let i=1;i{let ourObj=storedPrefix={view:view,prefix:prefix,scope:scope};setTimeout(()=>{if(storedPrefix==ourObj)storedPrefix=null},PrefixTimeout);return true}]}}let full=parts.join(" ");checkPrefix(full,false);let binding=scopeObj[full]||(scopeObj[full]={preventDefault:false,run:((_b=(_a=scopeObj._any)===null||_a===void 0?void 0:_a.run)===null||_b===void 0?void 0:_b.slice())||[]});if(command)binding.run.push(command);if(preventDefault)binding.preventDefault=true};for(let b of bindings){let scopes=b.scope?b.scope.split(" "):["editor"];if(b.any)for(let scope of scopes){let scopeObj=bound[scope]||(bound[scope]=Object.create(null));if(!scopeObj._any)scopeObj._any={preventDefault:false,run:[]};for(let key in scopeObj)scopeObj[key].run.push(b.any)}let name=b[platform]||b.key;if(!name)continue;for(let scope of scopes){add(scope,name,b.run,b.preventDefault);if(b.shift)add(scope,"Shift-"+name,b.shift,b.preventDefault)}}return bound}function runHandlers(map,event,view,scope){let name=keyName(event);let charCode=codePointAt(name,0),isChar=codePointSize(charCode)==name.length&&name!=" ";let prefix="",fallthrough=false;if(storedPrefix&&storedPrefix.view==view&&storedPrefix.scope==scope){prefix=storedPrefix.prefix+" ";if(fallthrough=modifierCodes.indexOf(event.keyCode)<0)storedPrefix=null}let ran=new Set;let runFor=binding=>{if(binding){for(let cmd of binding.run)if(!ran.has(cmd)){ran.add(cmd);if(cmd(view,event))return true}if(binding.preventDefault)fallthrough=true}return false};let scopeObj=map[scope],baseName,shiftName;if(scopeObj){if(runFor(scopeObj[prefix+modifiers(name,event,!isChar)]))return true;if(isChar&&(event.shiftKey||event.altKey||event.metaKey||charCode>127)&&(baseName=base[event.keyCode])&&baseName!=name){if(runFor(scopeObj[prefix+modifiers(baseName,event,true)]))return true;else if(event.shiftKey&&(shiftName=shift[event.keyCode])!=name&&shiftName!=baseName&&runFor(scopeObj[prefix+modifiers(shiftName,event,false)]))return true}else if(isChar&&event.shiftKey){if(runFor(scopeObj[prefix+modifiers(name,event,true)]))return true}if(runFor(scopeObj._any))return true}return fallthrough}const CanHidePrimary=!browser.ios;const selectionConfig=Facet.define({combine(configs){return combineConfig(configs,{cursorBlinkRate:1200,drawRangeCursor:true},{cursorBlinkRate:(a,b)=>Math.min(a,b),drawRangeCursor:(a,b)=>a||b})}});function drawSelection(config={}){return[selectionConfig.of(config),drawSelectionPlugin,hideNativeSelection]}class Piece{constructor(left,top,width,height,className){this.left=left;this.top=top;this.width=width;this.height=height;this.className=className}draw(){let elt=document.createElement("div");elt.className=this.className;this.adjust(elt);return elt}adjust(elt){elt.style.left=this.left+"px";elt.style.top=this.top+"px";if(this.width>=0)elt.style.width=this.width+"px";elt.style.height=this.height+"px"}eq(p){return this.left==p.left&&this.top==p.top&&this.width==p.width&&this.height==p.height&&this.className==p.className}}const drawSelectionPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view;this.rangePieces=[];this.cursors=[];this.measureReq={read:this.readPos.bind(this),write:this.drawSel.bind(this)};this.selectionLayer=view.scrollDOM.appendChild(document.createElement("div"));this.selectionLayer.className="cm-selectionLayer";this.selectionLayer.setAttribute("aria-hidden","true");this.cursorLayer=view.scrollDOM.appendChild(document.createElement("div"));this.cursorLayer.className="cm-cursorLayer";this.cursorLayer.setAttribute("aria-hidden","true");view.requestMeasure(this.measureReq);this.setBlinkRate()}setBlinkRate(){this.cursorLayer.style.animationDuration=this.view.state.facet(selectionConfig).cursorBlinkRate+"ms"}update(update){let confChanged=update.startState.facet(selectionConfig)!=update.state.facet(selectionConfig);if(confChanged||update.selectionSet||update.geometryChanged||update.viewportChanged)this.view.requestMeasure(this.measureReq);if(update.transactions.some(tr=>tr.scrollIntoView))this.cursorLayer.style.animationName=this.cursorLayer.style.animationName=="cm-blink"?"cm-blink2":"cm-blink";if(confChanged)this.setBlinkRate()}readPos(){let{state}=this.view,conf=state.facet(selectionConfig);let rangePieces=state.selection.ranges.map(r=>r.empty?[]:measureRange(this.view,r)).reduce((a,b)=>a.concat(b));let cursors=[];for(let r of state.selection.ranges){let prim=r==state.selection.main;if(r.empty?!prim||CanHidePrimary:conf.drawRangeCursor){let piece=measureCursor(this.view,r,prim);if(piece)cursors.push(piece)}}return{rangePieces:rangePieces,cursors:cursors}}drawSel({rangePieces,cursors}){if(rangePieces.length!=this.rangePieces.length||rangePieces.some((p,i)=>!p.eq(this.rangePieces[i]))){this.selectionLayer.textContent="";for(let p of rangePieces)this.selectionLayer.appendChild(p.draw());this.rangePieces=rangePieces}if(cursors.length!=this.cursors.length||cursors.some((c,i)=>!c.eq(this.cursors[i]))){let oldCursors=this.cursorLayer.children;if(oldCursors.length!==cursors.length){this.cursorLayer.textContent="";for(const c of cursors)this.cursorLayer.appendChild(c.draw())}else{cursors.forEach((c,idx)=>c.adjust(oldCursors[idx]))}this.cursors=cursors}}destroy(){this.selectionLayer.remove();this.cursorLayer.remove()}});const themeSpec={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};if(CanHidePrimary)themeSpec[".cm-line"].caretColor="transparent !important";const hideNativeSelection=Prec.highest(EditorView.theme(themeSpec));function getBase(view){let rect=view.scrollDOM.getBoundingClientRect();let left=view.textDirection==Direction.LTR?rect.left:rect.right-view.scrollDOM.clientWidth;return{left:left-view.scrollDOM.scrollLeft,top:rect.top-view.scrollDOM.scrollTop}}function wrappedLine(view,pos,inside){let range=EditorSelection.cursor(pos);return{from:Math.max(inside.from,view.moveToLineBoundary(range,false,true).from),to:Math.min(inside.to,view.moveToLineBoundary(range,true,true).from),type:BlockType.Text}}function blockAt(view,pos){let line=view.lineBlockAt(pos);if(Array.isArray(line.type))for(let l of line.type){if(l.to>pos||l.to==pos&&(l.to==line.to||l.type==BlockType.Text))return l}return line}function measureRange(view,range){if(range.to<=view.viewport.from||range.from>=view.viewport.to)return[];let from=Math.max(range.from,view.viewport.from),to=Math.min(range.to,view.viewport.to);let ltr=view.textDirection==Direction.LTR;let content=view.contentDOM,contentRect=content.getBoundingClientRect(),base=getBase(view);let lineStyle=window.getComputedStyle(content.firstChild);let leftSide=contentRect.left+parseInt(lineStyle.paddingLeft)+Math.min(0,parseInt(lineStyle.textIndent));let rightSide=contentRect.right-parseInt(lineStyle.paddingRight);let startBlock=blockAt(view,from),endBlock=blockAt(view,to);let visualStart=startBlock.type==BlockType.Text?startBlock:null;let visualEnd=endBlock.type==BlockType.Text?endBlock:null;if(view.lineWrapping){if(visualStart)visualStart=wrappedLine(view,from,visualStart);if(visualEnd)visualEnd=wrappedLine(view,to,visualEnd)}if(visualStart&&visualEnd&&visualStart.from==visualEnd.from){return pieces(drawForLine(range.from,range.to,visualStart))}else{let top=visualStart?drawForLine(range.from,null,visualStart):drawForWidget(startBlock,false);let bottom=visualEnd?drawForLine(null,range.to,visualEnd):drawForWidget(endBlock,true);let between=[];if((visualStart||startBlock).to<(visualEnd||endBlock).from-1)between.push(piece(leftSide,top.bottom,rightSide,bottom.top));else if(top.bottomstart&&r.from=endPos)break;if(spanTo>pos)addSpan(Math.max(spanFrom,pos),from==null&&spanFrom<=start,Math.min(spanTo,endPos),to==null&&spanTo>=end,span.dir)}pos=docLine.to+1;if(pos>=endPos)break}}if(horizontal.length==0)addSpan(start,from==null,end,to==null,view.textDirection);return{top:top,bottom:bottom,horizontal:horizontal}}function drawForWidget(block,top){let y=contentRect.top+(top?block.top:block.bottom);return{top:y,bottom:y,horizontal:[]}}}function measureCursor(view,cursor,primary){let pos=view.coordsAtPos(cursor.head,cursor.assoc||1);if(!pos)return null;let base=getBase(view);return new Piece(pos.left-base.left,pos.top-base.top,-1,pos.bottom-pos.top,primary?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary")}const setDropCursorPos=StateEffect.define({map(pos,mapping){return pos==null?null:mapping.mapPos(pos)}});const dropCursorPos=StateField.define({create(){return null},update(pos,tr){if(pos!=null)pos=tr.changes.mapPos(pos);return tr.effects.reduce((pos,e)=>e.is(setDropCursorPos)?e.value:pos,pos)}});const drawDropCursor=ViewPlugin.fromClass(class{constructor(view){this.view=view;this.cursor=null;this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(update){var _a;let cursorPos=update.state.field(dropCursorPos);if(cursorPos==null){if(this.cursor!=null){(_a=this.cursor)===null||_a===void 0?void 0:_a.remove();this.cursor=null}}else{if(!this.cursor){this.cursor=this.view.scrollDOM.appendChild(document.createElement("div"));this.cursor.className="cm-dropCursor"}if(update.startState.field(dropCursorPos)!=cursorPos||update.docChanged||update.geometryChanged)this.view.requestMeasure(this.measureReq)}}readPos(){let pos=this.view.state.field(dropCursorPos);let rect=pos!=null&&this.view.coordsAtPos(pos);if(!rect)return null;let outer=this.view.scrollDOM.getBoundingClientRect();return{left:rect.left-outer.left+this.view.scrollDOM.scrollLeft,top:rect.top-outer.top+this.view.scrollDOM.scrollTop,height:rect.bottom-rect.top}}drawCursor(pos){if(this.cursor){if(pos){this.cursor.style.left=pos.left+"px";this.cursor.style.top=pos.top+"px";this.cursor.style.height=pos.height+"px"}else{this.cursor.style.left="-100000px"}}}destroy(){if(this.cursor)this.cursor.remove()}setDropPos(pos){if(this.view.state.field(dropCursorPos)!=pos)this.view.dispatch({effects:setDropCursorPos.of(pos)})}},{eventHandlers:{dragover(event){this.setDropPos(this.view.posAtCoords({x:event.clientX,y:event.clientY}))},dragleave(event){if(event.target==this.view.contentDOM||!this.view.contentDOM.contains(event.relatedTarget))this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function dropCursor(){return[dropCursorPos,drawDropCursor]}function iterMatches(doc,re,from,to,f){re.lastIndex=0;for(let cursor=doc.iterRange(from,to),pos=from,m;!cursor.next().done;pos+=cursor.value.length){if(!cursor.lineBreak)while(m=re.exec(cursor.value))f(pos+m.index,m)}}function matchRanges(view,maxLength){let visible=view.visibleRanges;if(visible.length==1&&visible[0].from==view.viewport.from&&visible[0].to==view.viewport.to)return visible;let result=[];for(let{from,to}of visible){from=Math.max(view.state.doc.lineAt(from).from,from-maxLength);to=Math.min(view.state.doc.lineAt(to).to,to+maxLength);if(result.length&&result[result.length-1].to>=from)result[result.length-1].to=to;else result.push({from:from,to:to})}return result}class MatchDecorator{constructor(config){const{regexp,decoration,decorate,boundary,maxLength=1e3}=config;if(!regexp.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");this.regexp=regexp;if(decorate){this.addMatch=(match,view,from,add)=>decorate(add,from,from+match[0].length,match,view)}else if(typeof decoration=="function"){this.addMatch=(match,view,from,add)=>{let deco=decoration(match,view,from);if(deco)add(from,from+match[0].length,deco)}}else if(decoration){this.addMatch=(match,_view,from,add)=>add(from,from+match[0].length,decoration)}else{throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator")}this.boundary=boundary;this.maxLength=maxLength}createDeco(view){let build=new RangeSetBuilder,add=build.add.bind(build);for(let{from,to}of matchRanges(view,this.maxLength))iterMatches(view.state.doc,this.regexp,from,to,(from,m)=>this.addMatch(m,view,from,add));return build.finish()}updateDeco(update,deco){let changeFrom=1e9,changeTo=-1;if(update.docChanged)update.changes.iterChanges((_f,_t,from,to)=>{if(to>update.view.viewport.from&&from1e3)return this.createDeco(update.view);if(changeTo>-1)return this.updateRange(update.view,deco.map(update.changes),changeFrom,changeTo);return deco}updateRange(view,deco,updateFrom,updateTo){for(let r of view.visibleRanges){let from=Math.max(r.from,updateFrom),to=Math.min(r.to,updateTo);if(to>from){let fromLine=view.state.doc.lineAt(from),toLine=fromLine.tofromLine.from;from--)if(this.boundary.test(fromLine.text[from-1-fromLine.from])){start=from;break}for(;toranges.push(deco.range(from,to));if(fromLine==toLine){this.regexp.lastIndex=start-fromLine.from;while((m=this.regexp.exec(fromLine.text))&&m.indexthis.addMatch(m,view,from,add))}deco=deco.update({filterFrom:start,filterTo:end,filter:(from,to)=>fromend,add:ranges})}}return deco}}const UnicodeRegexpSupport=/x/.unicode!=null?"gu":"g";const Specials=new RegExp("[\0-\b\n--\u2028\u2029\ufeff-]",UnicodeRegexpSupport);const Names={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let _supportsTabSize=null;function supportsTabSize(){var _a;if(_supportsTabSize==null&&typeof document!="undefined"&&document.body){let styles=document.body.style;_supportsTabSize=((_a=styles.tabSize)!==null&&_a!==void 0?_a:styles.MozTabSize)!=null}return _supportsTabSize||false}const specialCharConfig=Facet.define({combine(configs){let config=combineConfig(configs,{render:null,specialChars:Specials,addSpecialChars:null});if(config.replaceTabs=!supportsTabSize())config.specialChars=new RegExp("\t|"+config.specialChars.source,UnicodeRegexpSupport);if(config.addSpecialChars)config.specialChars=new RegExp(config.specialChars.source+"|"+config.addSpecialChars.source,UnicodeRegexpSupport);return config}});function highlightSpecialChars(config={}){return[specialCharConfig.of(config),specialCharPlugin()]}let _plugin=null;function specialCharPlugin(){return _plugin||(_plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view;this.decorations=Decoration.none;this.decorationCache=Object.create(null);this.decorator=this.makeDecorator(view.state.facet(specialCharConfig));this.decorations=this.decorator.createDeco(view)}makeDecorator(conf){return new MatchDecorator({regexp:conf.specialChars,decoration:(m,view,pos)=>{let{doc}=view.state;let code=codePointAt(m[0],0);if(code==9){let line=doc.lineAt(pos);let size=view.state.tabSize,col=countColumn(line.text,size,pos-line.from);return Decoration.replace({widget:new TabWidget((size-col%size)*this.view.defaultCharacterWidth)})}return this.decorationCache[code]||(this.decorationCache[code]=Decoration.replace({widget:new SpecialCharWidget(conf,code)}))},boundary:conf.replaceTabs?undefined:/[^]/})}update(update){let conf=update.state.facet(specialCharConfig);if(update.startState.facet(specialCharConfig)!=conf){this.decorator=this.makeDecorator(conf);this.decorations=this.decorator.createDeco(update.view)}else{this.decorations=this.decorator.updateDeco(update,this.decorations)}}},{decorations:v=>v.decorations}))}const DefaultPlaceholder="•";function placeholder$1(code){if(code>=32)return DefaultPlaceholder;if(code==10)return"";return String.fromCharCode(9216+code)}class SpecialCharWidget extends WidgetType{constructor(options,code){super();this.options=options;this.code=code}eq(other){return other.code==this.code}toDOM(view){let ph=placeholder$1(this.code);let desc=view.state.phrase("Control character")+" "+(Names[this.code]||"0x"+this.code.toString(16));let custom=this.options.render&&this.options.render(this.code,desc,ph);if(custom)return custom;let span=document.createElement("span");span.textContent=ph;span.title=desc;span.setAttribute("aria-label",desc);span.className="cm-specialChar";return span}ignoreEvent(){return false}}class TabWidget extends WidgetType{constructor(width){super();this.width=width}eq(other){return other.width==this.width}toDOM(){let span=document.createElement("span");span.textContent="\t";span.className="cm-tab";span.style.width=this.width+"px";return span}ignoreEvent(){return false}}const plugin=ViewPlugin.fromClass(class{constructor(){this.height=1e3;this.attrs={style:"padding-bottom: 1000px"}}update(update){let{view}=update;let height=view.viewState.editorHeight-view.defaultLineHeight-view.documentPadding.top-.5;if(height!=this.height){this.height=height;this.attrs={style:`padding-bottom: ${height}px`}}}});function scrollPastEnd(){return[plugin,contentAttributes.of(view=>{var _a;return((_a=view.plugin(plugin))===null||_a===void 0?void 0:_a.attrs)||null})]}function highlightActiveLine(){return activeLineHighlighter}const lineDeco=Decoration.line({class:"cm-activeLine"});const activeLineHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){if(update.docChanged||update.selectionSet)this.decorations=this.getDeco(update.view)}getDeco(view){let lastLineStart=-1,deco=[];for(let r of view.state.selection.ranges){let line=view.lineBlockAt(r.head);if(line.from>lastLineStart){deco.push(lineDeco.range(line.from));lastLineStart=line.from}}return Decoration.set(deco)}},{decorations:v=>v.decorations});class Placeholder extends WidgetType{constructor(content){super();this.content=content}toDOM(){let wrap=document.createElement("span");wrap.className="cm-placeholder";wrap.style.pointerEvents="none";wrap.appendChild(typeof this.content=="string"?document.createTextNode(this.content):this.content);if(typeof this.content=="string")wrap.setAttribute("aria-label","placeholder "+this.content);else wrap.setAttribute("aria-hidden","true");return wrap}ignoreEvent(){return false}}function placeholder(content){return ViewPlugin.fromClass(class{constructor(view){this.view=view;this.placeholder=Decoration.set([Decoration.widget({widget:new Placeholder(content),side:1}).range(0)])}get decorations(){return this.view.state.doc.length?Decoration.none:this.placeholder}},{decorations:v=>v.decorations})}const MaxOff=2e3;function rectangleFor(state,a,b){let startLine=Math.min(a.line,b.line),endLine=Math.max(a.line,b.line);let ranges=[];if(a.off>MaxOff||b.off>MaxOff||a.col<0||b.col<0){let startOff=Math.min(a.off,b.off),endOff=Math.max(a.off,b.off);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i);if(line.length<=endOff)ranges.push(EditorSelection.range(line.from+startOff,line.to+endOff))}}else{let startCol=Math.min(a.col,b.col),endCol=Math.max(a.col,b.col);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i);let start=findColumn(line.text,startCol,state.tabSize,true);if(start<0){ranges.push(EditorSelection.cursor(line.to))}else{let end=findColumn(line.text,endCol,state.tabSize);ranges.push(EditorSelection.range(line.from+start,line.from+end))}}}return ranges}function absoluteColumn(view,x){let ref=view.coordsAtPos(view.viewport.from);return ref?Math.round(Math.abs((ref.left-x)/view.defaultCharacterWidth)):-1}function getPos(view,event){let offset=view.posAtCoords({x:event.clientX,y:event.clientY},false);let line=view.state.doc.lineAt(offset),off=offset-line.from;let col=off>MaxOff?-1:off==line.length?absoluteColumn(view,event.clientX):countColumn(line.text,view.state.tabSize,offset-line.from);return{line:line.number,col:col,off:off}}function rectangleSelectionStyle(view,event){let start=getPos(view,event),startSel=view.state.selection;if(!start)return null;return{update(update){if(update.docChanged){let newStart=update.changes.mapPos(update.startState.doc.line(start.line).from);let newLine=update.state.doc.lineAt(newStart);start={line:newLine.number,col:start.col,off:Math.min(start.off,newLine.length)};startSel=startSel.map(update.changes)}},get(event,_extend,multiple){let cur=getPos(view,event);if(!cur)return startSel;let ranges=rectangleFor(view.state,start,cur);if(!ranges.length)return startSel;if(multiple)return EditorSelection.create(ranges.concat(startSel.ranges));else return EditorSelection.create(ranges)}}}function rectangularSelection(options){let filter=(options===null||options===void 0?void 0:options.eventFilter)||(e=>e.altKey&&e.button==0);return EditorView.mouseSelectionStyle.of((view,event)=>filter(event)?rectangleSelectionStyle(view,event):null)}const keys={Alt:[18,e=>e.altKey],Control:[17,e=>e.ctrlKey],Shift:[16,e=>e.shiftKey],Meta:[91,e=>e.metaKey]};const showCrosshair={style:"cursor: crosshair"};function crosshairCursor(options={}){let[code,getter]=keys[options.key||"Alt"];let plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view;this.isDown=false}set(isDown){if(this.isDown!=isDown){this.isDown=isDown;this.view.update([])}}},{eventHandlers:{keydown(e){this.set(e.keyCode==code||getter(e))},keyup(e){if(e.keyCode==code||!getter(e))this.set(false)}}});return[plugin,EditorView.contentAttributes.of(view=>{var _a;return((_a=view.plugin(plugin))===null||_a===void 0?void 0:_a.isDown)?showCrosshair:null})]}const Outside="-10000px";class TooltipViewManager{constructor(view,facet,createTooltipView){this.facet=facet;this.createTooltipView=createTooltipView;this.input=view.state.facet(facet);this.tooltips=this.input.filter(t=>t);this.tooltipViews=this.tooltips.map(createTooltipView)}update(update){var _a;let input=update.state.facet(this.facet);let tooltips=input.filter(x=>x);if(input===this.input){for(let t of this.tooltipViews)if(t.update)t.update(update);return false}let tooltipViews=[];for(let i=0;i{var _a,_b,_c;return{position:browser.ios?"absolute":((_a=values.find(conf=>conf.position))===null||_a===void 0?void 0:_a.position)||"fixed",parent:((_b=values.find(conf=>conf.parent))===null||_b===void 0?void 0:_b.parent)||null,tooltipSpace:((_c=values.find(conf=>conf.tooltipSpace))===null||_c===void 0?void 0:_c.tooltipSpace)||windowSpace}}});const tooltipPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view;this.inView=true;this.lastTransaction=0;this.measureTimeout=-1;let config=view.state.facet(tooltipConfig);this.position=config.position;this.parent=config.parent;this.classes=view.themeClasses;this.createContainer();this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this};this.manager=new TooltipViewManager(view,showTooltip,t=>this.createTooltip(t));this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(entries=>{if(Date.now()>this.lastTransaction-50&&entries.length>0&&entries[entries.length-1].intersectionRatio<1)this.measureSoon()},{threshold:[1]}):null;this.observeIntersection();view.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this));this.maybeMeasure()}createContainer(){if(this.parent){this.container=document.createElement("div");this.container.style.position="relative";this.container.className=this.view.themeClasses;this.parent.appendChild(this.container)}else{this.container=this.view.dom}}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let tooltip of this.manager.tooltipViews)this.intersectionObserver.observe(tooltip.dom)}}measureSoon(){if(this.measureTimeout<0)this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1;this.maybeMeasure()},50)}update(update){if(update.transactions.length)this.lastTransaction=Date.now();let updated=this.manager.update(update);if(updated)this.observeIntersection();let shouldMeasure=updated||update.geometryChanged;let newConfig=update.state.facet(tooltipConfig);if(newConfig.position!=this.position){this.position=newConfig.position;for(let t of this.manager.tooltipViews)t.dom.style.position=this.position;shouldMeasure=true}if(newConfig.parent!=this.parent){if(this.parent)this.container.remove();this.parent=newConfig.parent;this.createContainer();for(let t of this.manager.tooltipViews)this.container.appendChild(t.dom);shouldMeasure=true}else if(this.parent&&this.view.themeClasses!=this.classes){this.classes=this.container.className=this.view.themeClasses}if(shouldMeasure)this.maybeMeasure()}createTooltip(tooltip){let tooltipView=tooltip.create(this.view);tooltipView.dom.classList.add("cm-tooltip");if(tooltip.arrow&&!tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let arrow=document.createElement("div");arrow.className="cm-tooltip-arrow";tooltipView.dom.appendChild(arrow)}tooltipView.dom.style.position=this.position;tooltipView.dom.style.top=Outside;this.container.appendChild(tooltipView.dom);if(tooltipView.mount)tooltipView.mount(this.view);return tooltipView}destroy(){var _a,_b;this.view.win.removeEventListener("resize",this.measureSoon);for(let tooltipView of this.manager.tooltipViews){tooltipView.dom.remove();(_a=tooltipView.destroy)===null||_a===void 0?void 0:_a.call(tooltipView)}(_b=this.intersectionObserver)===null||_b===void 0?void 0:_b.disconnect();clearTimeout(this.measureTimeout)}readMeasure(){let editor=this.view.dom.getBoundingClientRect();return{editor:editor,parent:this.parent?this.container.getBoundingClientRect():editor,pos:this.manager.tooltips.map((t,i)=>{let tv=this.manager.tooltipViews[i];return tv.getCoords?tv.getCoords(t.pos):this.view.coordsAtPos(t.pos)}),size:this.manager.tooltipViews.map(({dom})=>dom.getBoundingClientRect()),space:this.view.state.facet(tooltipConfig).tooltipSpace(this.view)}}writeMeasure(measured){let{editor,space}=measured;let others=[];for(let i=0;i=Math.min(editor.bottom,space.bottom)||pos.rightMath.min(editor.right,space.right)+.1){dom.style.top=Outside;continue}let arrow=tooltip.arrow?tView.dom.querySelector(".cm-tooltip-arrow"):null;let arrowHeight=arrow?7:0;let width=size.right-size.left,height=size.bottom-size.top;let offset=tView.offset||noOffset,ltr=this.view.textDirection==Direction.LTR;let left=size.width>space.right-space.left?ltr?space.left:space.right-size.width:ltr?Math.min(pos.left-(arrow?14:0)+offset.x,space.right-width):Math.max(space.left,pos.left-width+(arrow?14:0)-offset.x);let above=!!tooltip.above;if(!tooltip.strictSide&&(above?pos.top-(size.bottom-size.top)-offset.yspace.bottom)&&above==space.bottom-pos.bottom>pos.top-space.top)above=!above;let top=above?pos.top-height-arrowHeight-offset.y:pos.bottom+arrowHeight+offset.y;let right=left+width;if(tView.overlap!==true)for(let r of others)if(r.leftleft&&r.toptop)top=above?r.top-height-2-arrowHeight:r.bottom+arrowHeight+2;if(this.position=="absolute"){dom.style.top=top-measured.parent.top+"px";dom.style.left=left-measured.parent.left+"px"}else{dom.style.top=top+"px";dom.style.left=left+"px"}if(arrow)arrow.style.left=`${pos.left+(ltr?offset.x:-offset.x)-(left+14-7)}px`;if(tView.overlap!==true)others.push({left:left,top:top,right:right,bottom:top+height});dom.classList.toggle("cm-tooltip-above",above);dom.classList.toggle("cm-tooltip-below",!above);if(tView.positioned)tView.positioned()}}maybeMeasure(){if(this.manager.tooltips.length){if(this.view.inView)this.view.requestMeasure(this.measureReq);if(this.inView!=this.view.inView){this.inView=this.view.inView;if(!this.inView)for(let tv of this.manager.tooltipViews)tv.dom.style.top=Outside}}}},{eventHandlers:{scroll(){this.maybeMeasure()}}});const baseTheme=EditorView.baseTheme({".cm-tooltip":{zIndex:100},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:`${7}px`,width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:`${7}px solid transparent`,borderRight:`${7}px solid transparent`},".cm-tooltip-above &":{bottom:`-${7}px`,"&:before":{borderTop:`${7}px solid #bbb`},"&:after":{borderTop:`${7}px solid #f5f5f5`,bottom:"1px"}},".cm-tooltip-below &":{top:`-${7}px`,"&:before":{borderBottom:`${7}px solid #bbb`},"&:after":{borderBottom:`${7}px solid #f5f5f5`,top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}});const noOffset={x:0,y:0};const showTooltip=Facet.define({enables:[tooltipPlugin,baseTheme]});const showHoverTooltip=Facet.define();class HoverTooltipHost{constructor(view){this.view=view;this.mounted=false;this.dom=document.createElement("div");this.dom.classList.add("cm-tooltip-hover");this.manager=new TooltipViewManager(view,showHoverTooltip,t=>this.createHostedView(t))}static create(view){return new HoverTooltipHost(view)}createHostedView(tooltip){let hostedView=tooltip.create(this.view);hostedView.dom.classList.add("cm-tooltip-section");this.dom.appendChild(hostedView.dom);if(this.mounted&&hostedView.mount)hostedView.mount(this.view);return hostedView}mount(view){for(let hostedView of this.manager.tooltipViews){if(hostedView.mount)hostedView.mount(view)}this.mounted=true}positioned(){for(let hostedView of this.manager.tooltipViews){if(hostedView.positioned)hostedView.positioned()}}update(update){this.manager.update(update)}}const showHoverTooltipHost=showTooltip.compute([showHoverTooltip],state=>{let tooltips=state.facet(showHoverTooltip).filter(t=>t);if(tooltips.length===0)return null;return{pos:Math.min(...tooltips.map(t=>t.pos)),end:Math.max(...tooltips.filter(t=>t.end!=null).map(t=>t.end)),create:HoverTooltipHost.create,above:tooltips[0].above,arrow:tooltips.some(t=>t.arrow)}});class HoverPlugin{constructor(view,source,field,setHover,hoverTime){this.view=view;this.source=source;this.field=field;this.setHover=setHover;this.hoverTime=hoverTime;this.hoverTimeout=-1;this.restartTimeout=-1;this.pending=null;this.lastMove={x:0,y:0,target:view.dom,time:0};this.checkHover=this.checkHover.bind(this);view.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this));view.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){if(this.pending){this.pending=null;clearTimeout(this.restartTimeout);this.restartTimeout=setTimeout(()=>this.startHover(),20)}}get active(){return this.view.state.field(this.field)}checkHover(){this.hoverTimeout=-1;if(this.active)return;let hovered=Date.now()-this.lastMove.time;if(hoveredposCoords.bottom||lastMove.xposCoords.right+this.view.defaultCharacterWidth)return;let bidi=this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find(s=>s.from<=pos&&s.to>=pos);let rtl=bidi&&bidi.dir==Direction.RTL?-1:1;let open=this.source(this.view,pos,lastMove.x{if(this.pending==pending){this.pending=null;if(result)this.view.dispatch({effects:this.setHover.of(result)})}},e=>logException(this.view.state,e,"hover tooltip"))}else if(open){this.view.dispatch({effects:this.setHover.of(open)})}}mousemove(event){var _a;this.lastMove={x:event.clientX,y:event.clientY,target:event.target,time:Date.now()};if(this.hoverTimeout<0)this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime);let tooltip=this.active;if(tooltip&&!isInTooltip(this.lastMove.target)||this.pending){let{pos}=tooltip||this.pending,end=(_a=tooltip===null||tooltip===void 0?void 0:tooltip.end)!==null&&_a!==void 0?_a:pos;if(pos==end?this.view.posAtCoords(this.lastMove)!=pos:!isOverRange(this.view,pos,end,event.clientX,event.clientY,6)){this.view.dispatch({effects:this.setHover.of(null)});this.pending=null}}}mouseleave(){clearTimeout(this.hoverTimeout);this.hoverTimeout=-1;if(this.active)this.view.dispatch({effects:this.setHover.of(null)})}destroy(){clearTimeout(this.hoverTimeout);this.view.dom.removeEventListener("mouseleave",this.mouseleave);this.view.dom.removeEventListener("mousemove",this.mousemove)}}function isInTooltip(elt){for(let cur=elt;cur;cur=cur.parentNode)if(cur.nodeType==1&&cur.classList.contains("cm-tooltip"))return true;return false}function isOverRange(view,from,to,x,y,margin){let range=document.createRange();let fromDOM=view.domAtPos(from),toDOM=view.domAtPos(to);range.setEnd(toDOM.node,toDOM.offset);range.setStart(fromDOM.node,fromDOM.offset);let rects=range.getClientRects();range.detach();for(let i=0;ishowHoverTooltip.from(f)});return[hoverState,ViewPlugin.define(view=>new HoverPlugin(view,source,hoverState,setHover,options.hoverTime||300)),showHoverTooltipHost]}function getTooltip(view,tooltip){let plugin=view.plugin(tooltipPlugin);if(!plugin)return null;let found=plugin.manager.tooltips.indexOf(tooltip);return found<0?null:plugin.manager.tooltipViews[found]}function hasHoverTooltips(state){return state.facet(showHoverTooltip).some(x=>x)}const closeHoverTooltipEffect=StateEffect.define();const closeHoverTooltips=closeHoverTooltipEffect.of(null);function repositionTooltips(view){var _a;(_a=view.plugin(tooltipPlugin))===null||_a===void 0?void 0:_a.maybeMeasure()}const panelConfig=Facet.define({combine(configs){let topContainer,bottomContainer;for(let c of configs){topContainer=topContainer||c.topContainer;bottomContainer=bottomContainer||c.bottomContainer}return{topContainer:topContainer,bottomContainer:bottomContainer}}});function panels(config){return config?[panelConfig.of(config)]:[]}function getPanel(view,panel){let plugin=view.plugin(panelPlugin);let index=plugin?plugin.specs.indexOf(panel):-1;return index>-1?plugin.panels[index]:null}const panelPlugin=ViewPlugin.fromClass(class{constructor(view){this.input=view.state.facet(showPanel);this.specs=this.input.filter(s=>s);this.panels=this.specs.map(spec=>spec(view));let conf=view.state.facet(panelConfig);this.top=new PanelGroup(view,true,conf.topContainer);this.bottom=new PanelGroup(view,false,conf.bottomContainer);this.top.sync(this.panels.filter(p=>p.top));this.bottom.sync(this.panels.filter(p=>!p.top));for(let p of this.panels){p.dom.classList.add("cm-panel");if(p.mount)p.mount()}}update(update){let conf=update.state.facet(panelConfig);if(this.top.container!=conf.topContainer){this.top.sync([]);this.top=new PanelGroup(update.view,true,conf.topContainer)}if(this.bottom.container!=conf.bottomContainer){this.bottom.sync([]);this.bottom=new PanelGroup(update.view,false,conf.bottomContainer)}this.top.syncClasses();this.bottom.syncClasses();let input=update.state.facet(showPanel);if(input!=this.input){let specs=input.filter(x=>x);let panels=[],top=[],bottom=[],mount=[];for(let spec of specs){let known=this.specs.indexOf(spec),panel;if(known<0){panel=spec(update.view);mount.push(panel)}else{panel=this.panels[known];if(panel.update)panel.update(update)}panels.push(panel);(panel.top?top:bottom).push(panel)}this.specs=specs;this.panels=panels;this.top.sync(top);this.bottom.sync(bottom);for(let p of mount){p.dom.classList.add("cm-panel");if(p.mount)p.mount()}}else{for(let p of this.panels)if(p.update)p.update(update)}}destroy(){this.top.sync([]);this.bottom.sync([])}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);return value&&{top:value.top.scrollMargin(),bottom:value.bottom.scrollMargin()}})});class PanelGroup{constructor(view,top,container){this.view=view;this.top=top;this.container=container;this.dom=undefined;this.classes="";this.panels=[];this.syncClasses()}sync(panels){for(let p of this.panels)if(p.destroy&&panels.indexOf(p)<0)p.destroy();this.panels=panels;this.syncDOM()}syncDOM(){if(this.panels.length==0){if(this.dom){this.dom.remove();this.dom=undefined}return}if(!this.dom){this.dom=document.createElement("div");this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom";this.dom.style[this.top?"top":"bottom"]="0";let parent=this.container||this.view.dom;parent.insertBefore(this.dom,this.top?parent.firstChild:null)}let curDOM=this.dom.firstChild;for(let panel of this.panels){if(panel.dom.parentNode==this.dom){while(curDOM!=panel.dom)curDOM=rm(curDOM);curDOM=curDOM.nextSibling}else{this.dom.insertBefore(panel.dom,curDOM)}}while(curDOM)curDOM=rm(curDOM)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!this.container||this.classes==this.view.themeClasses)return;for(let cls of this.classes.split(" "))if(cls)this.container.classList.remove(cls);for(let cls of(this.classes=this.view.themeClasses).split(" "))if(cls)this.container.classList.add(cls)}}function rm(node){let next=node.nextSibling;node.remove();return next}const showPanel=Facet.define({enables:panelPlugin});class GutterMarker extends RangeValue{compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}eq(other){return false}destroy(dom){}}GutterMarker.prototype.elementClass="";GutterMarker.prototype.toDOM=undefined;GutterMarker.prototype.mapMode=MapMode.TrackBefore;GutterMarker.prototype.startSide=GutterMarker.prototype.endSide=-1;GutterMarker.prototype.point=true;const gutterLineClass=Facet.define();const defaults={class:"",renderEmptyElements:false,elementStyle:"",markers:()=>RangeSet.empty,lineMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}};const activeGutters=Facet.define();function gutter(config){return[gutters(),activeGutters.of(Object.assign(Object.assign({},defaults),config))]}const unfixGutters=Facet.define({combine:values=>values.some(x=>x)});function gutters(config){let result=[gutterView];if(config&&config.fixed===false)result.push(unfixGutters.of(true));return result}const gutterView=ViewPlugin.fromClass(class{constructor(view){this.view=view;this.prevViewport=view.viewport;this.dom=document.createElement("div");this.dom.className="cm-gutters";this.dom.setAttribute("aria-hidden","true");this.dom.style.minHeight=this.view.contentHeight+"px";this.gutters=view.state.facet(activeGutters).map(conf=>new SingleGutterView(view,conf));for(let gutter of this.gutters)this.dom.appendChild(gutter.dom);this.fixed=!view.state.facet(unfixGutters);if(this.fixed){this.dom.style.position="sticky"}this.syncGutters(false);view.scrollDOM.insertBefore(this.dom,view.contentDOM)}update(update){if(this.updateGutters(update)){let vpA=this.prevViewport,vpB=update.view.viewport;let vpOverlap=Math.min(vpA.to,vpB.to)-Math.max(vpA.from,vpB.from);this.syncGutters(vpOverlap<(vpB.to-vpB.from)*.8)}if(update.geometryChanged)this.dom.style.minHeight=this.view.contentHeight+"px";if(this.view.state.facet(unfixGutters)!=!this.fixed){this.fixed=!this.fixed;this.dom.style.position=this.fixed?"sticky":""}this.prevViewport=update.view.viewport}syncGutters(detach){let after=this.dom.nextSibling;if(detach)this.dom.remove();let lineClasses=RangeSet.iter(this.view.state.facet(gutterLineClass),this.view.viewport.from);let classSet=[];let contexts=this.gutters.map(gutter=>new UpdateContext(gutter,this.view.viewport,-this.view.documentPadding.top));for(let line of this.view.viewportLineBlocks){let text;if(Array.isArray(line.type)){for(let b of line.type)if(b.type==BlockType.Text){text=b;break}}else{text=line.type==BlockType.Text?line:undefined}if(!text)continue;if(classSet.length)classSet=[];advanceCursor(lineClasses,classSet,line.from);for(let cx of contexts)cx.line(this.view,text,classSet)}for(let cx of contexts)cx.finish();if(detach)this.view.scrollDOM.insertBefore(this.dom,after)}updateGutters(update){let prev=update.startState.facet(activeGutters),cur=update.state.facet(activeGutters);let change=update.docChanged||update.heightChanged||update.viewportChanged||!RangeSet.eq(update.startState.facet(gutterLineClass),update.state.facet(gutterLineClass),update.view.viewport.from,update.view.viewport.to);if(prev==cur){for(let gutter of this.gutters)if(gutter.update(update))change=true}else{change=true;let gutters=[];for(let conf of cur){let known=prev.indexOf(conf);if(known<0){gutters.push(new SingleGutterView(this.view,conf))}else{this.gutters[known].update(update);gutters.push(this.gutters[known])}}for(let g of this.gutters){g.dom.remove();if(gutters.indexOf(g)<0)g.destroy()}for(let g of gutters)this.dom.appendChild(g.dom);this.gutters=gutters}return change}destroy(){for(let view of this.gutters)view.destroy();this.dom.remove()}},{provide:plugin=>EditorView.scrollMargins.of(view=>{let value=view.plugin(plugin);if(!value||value.gutters.length==0||!value.fixed)return null;return view.textDirection==Direction.LTR?{left:value.dom.offsetWidth}:{right:value.dom.offsetWidth}})});function asArray(val){return Array.isArray(val)?val:[val]}function advanceCursor(cursor,collect,pos){while(cursor.value&&cursor.from<=pos){if(cursor.from==pos)collect.push(cursor.value);cursor.next()}}class UpdateContext{constructor(gutter,viewport,height){this.gutter=gutter;this.height=height;this.localMarkers=[];this.i=0;this.cursor=RangeSet.iter(gutter.markers,viewport.from)}line(view,line,extraMarkers){if(this.localMarkers.length)this.localMarkers=[];advanceCursor(this.cursor,this.localMarkers,line.from);let localMarkers=extraMarkers.length?this.localMarkers.concat(extraMarkers):this.localMarkers;let forLine=this.gutter.config.lineMarker(view,line,localMarkers);if(forLine)localMarkers.unshift(forLine);let gutter=this.gutter;if(localMarkers.length==0&&!gutter.config.renderEmptyElements)return;let above=line.top-this.height;if(this.i==gutter.elements.length){let newElt=new GutterElement(view,line.height,above,localMarkers);gutter.elements.push(newElt);gutter.dom.appendChild(newElt.dom)}else{gutter.elements[this.i].update(view,line.height,above,localMarkers)}this.height=line.bottom;this.i++}finish(){let gutter=this.gutter;while(gutter.elements.length>this.i){let last=gutter.elements.pop();gutter.dom.removeChild(last.dom);last.destroy()}}}class SingleGutterView{constructor(view,config){this.view=view;this.config=config;this.elements=[];this.spacer=null;this.dom=document.createElement("div");this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let prop in config.domEventHandlers){this.dom.addEventListener(prop,event=>{let line=view.lineBlockAtHeight(event.clientY-view.documentTop);if(config.domEventHandlers[prop](view,line,event))event.preventDefault()})}this.markers=asArray(config.markers(view));if(config.initialSpacer){this.spacer=new GutterElement(view,0,0,[config.initialSpacer(view)]);this.dom.appendChild(this.spacer.dom);this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none"}}update(update){let prevMarkers=this.markers;this.markers=asArray(this.config.markers(update.view));if(this.spacer&&this.config.updateSpacer){let updated=this.config.updateSpacer(this.spacer.markers[0],update);if(updated!=this.spacer.markers[0])this.spacer.update(update.view,0,0,[updated])}let vp=update.view.viewport;return!RangeSet.eq(this.markers,prevMarkers,vp.from,vp.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(update):false)}destroy(){for(let elt of this.elements)elt.destroy()}}class GutterElement{constructor(view,height,above,markers){this.height=-1;this.above=0;this.markers=[];this.dom=document.createElement("div");this.dom.className="cm-gutterElement";this.update(view,height,above,markers)}update(view,height,above,markers){if(this.height!=height)this.dom.style.height=(this.height=height)+"px";if(this.above!=above)this.dom.style.marginTop=(this.above=above)?above+"px":"";if(!sameMarkers(this.markers,markers))this.setMarkers(view,markers)}setMarkers(view,markers){let cls="cm-gutterElement",domPos=this.dom.firstChild;for(let iNew=0,iOld=0;;){let skipTo=iOld,marker=iNewexists(view,line,event)||add(view,line,event):add}return result}})}});class NumberMarker extends GutterMarker{constructor(number){super();this.number=number}eq(other){return this.number==other.number}toDOM(){return document.createTextNode(this.number)}}function formatNumber(view,number){return view.state.facet(lineNumberConfig).formatNumber(number,view.state)}const lineNumberGutter=activeGutters.compute([lineNumberConfig],state=>({class:"cm-lineNumbers",renderEmptyElements:false,markers(view){return view.state.facet(lineNumberMarkers)},lineMarker(view,line,others){if(others.some(m=>m.toDOM))return null;return new NumberMarker(formatNumber(view,view.state.doc.lineAt(line.from).number))},lineMarkerChange:update=>update.startState.facet(lineNumberConfig)!=update.state.facet(lineNumberConfig),initialSpacer(view){return new NumberMarker(formatNumber(view,maxLineNumber(view.state.doc.lines)))},updateSpacer(spacer,update){let max=formatNumber(update.view,maxLineNumber(update.view.state.doc.lines));return max==spacer.number?spacer:new NumberMarker(max)},domEventHandlers:state.facet(lineNumberConfig).domEventHandlers}));function lineNumbers(config={}){return[lineNumberConfig.of(config),gutters(),lineNumberGutter]}function maxLineNumber(lines){let last=9;while(last{let marks=[],last=-1;for(let range of state.selection.ranges){let linePos=state.doc.lineAt(range.head).from;if(linePos>last){last=linePos;marks.push(activeLineGutterMarker.range(linePos))}}return RangeSet.of(marks)});function highlightActiveLineGutter(){return activeLineGutterHighlighter}const __test={HeightMap:HeightMap,HeightOracle:HeightOracle,MeasuredHeights:MeasuredHeights,QueryType:QueryType,ChangedRange:ChangedRange,computeOrder:computeOrder,moveVisually:moveVisually};export{BidiSpan,BlockInfo,BlockType,Decoration,Direction,EditorView,GutterMarker,MatchDecorator,ViewPlugin,ViewUpdate,WidgetType,__test,closeHoverTooltips,crosshairCursor,drawSelection,dropCursor,getPanel,getTooltip,gutter,gutterLineClass,gutters,hasHoverTooltips,highlightActiveLine,highlightActiveLineGutter,highlightSpecialChars,hoverTooltip,keymap,lineNumberMarkers,lineNumbers,logException,panels,placeholder,rectangularSelection,repositionTooltips,runScopeHandlers,scrollPastEnd,showPanel,showTooltip,tooltips};
\ No newline at end of file
diff --git a/public/js/@lezer/common.js b/public/js/@lezer/common.js
new file mode 100755
index 0000000..7fe4093
--- /dev/null
+++ b/public/js/@lezer/common.js
@@ -0,0 +1 @@
+const DefaultBufferLength=1024;let nextPropID=0;class Range{constructor(from,to){this.from=from;this.to=to}}class NodeProp{constructor(config={}){this.id=nextPropID++;this.perNode=!!config.perNode;this.deserialize=config.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(match){if(this.perNode)throw new RangeError("Can't add per-node props to node types");if(typeof match!="function")match=NodeType.match(match);return type=>{let result=match(type);return result===undefined?null:[this,result]}}}NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")});NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")});NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")});NodeProp.contextHash=new NodeProp({perNode:true});NodeProp.lookAhead=new NodeProp({perNode:true});NodeProp.mounted=new NodeProp({perNode:true});class MountedTree{constructor(tree,overlay,parser){this.tree=tree;this.overlay=overlay;this.parser=parser}}const noProps=Object.create(null);class NodeType{constructor(name,props,id,flags=0){this.name=name;this.props=props;this.id=id;this.flags=flags}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps;let flags=(spec.top?1:0)|(spec.skipped?2:0)|(spec.error?4:0)|(spec.name==null?8:0);let type=new NodeType(spec.name||"",props,spec.id,flags);if(spec.props)for(let src of spec.props){if(!Array.isArray(src))src=src(type);if(src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1]}}return type}prop(prop){return this.props[prop.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(name){if(typeof name=="string"){if(this.name==name)return true;let group=this.prop(NodeProp.group);return group?group.indexOf(name)>-1:false}return this.id==name}static match(map){let direct=Object.create(null);for(let prop in map)for(let name of prop.split(" "))direct[name]=map[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(types){this.types=types;for(let i=0;i