Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: support markdown syntax (#422)

Myles Scolnicka354c773e799
diff --git a/frontend/package.json b/frontend/package.json
index 834cdaa2d9..e138cd75be 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -14,7 +14,9 @@
"dependencies": {
"@codemirror/autocomplete": "^6.11.1",
"@codemirror/commands": "^6.3.2",
+ "@codemirror/lang-markdown": "^6.2.3",
"@codemirror/lang-python": "^6.1.3",
+ "@codemirror/language-data": "^6.3.1",
"@codemirror/language": "^6.9.3",
"@codemirror/lint": "^6.4.2",
"@codemirror/search": "^6.5.5",
@@ -71,6 +73,7 @@
"codemirror-languageserver": "^1.11.0",
"cssnano": "^6.0.1",
"date-fns": "^2.30.0",
+ "dedent": "^1.5.1",
"dequal": "^2.0.3",
"eslint-plugin-header": "^3.1.1",
"htm": "^3.1.1",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index d199d2932b..8625470d66 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -11,12 +11,18 @@ dependencies:
'@codemirror/commands':
specifier: ^6.3.2
version: 6.3.2
+ '@codemirror/lang-markdown':
+ specifier: ^6.2.3
+ version: 6.2.3
'@codemirror/lang-python':
specifier: ^6.1.3
version: 6.1.3(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
'@codemirror/language':
specifier: ^6.9.3
version: 6.9.3
+ '@codemirror/language-data':
+ specifier: ^6.3.1
+ version: 6.3.1(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
'@codemirror/lint':
specifier: ^6.4.2
version: 6.4.2
@@ -182,6 +188,9 @@ dependencies:
date-fns:
specifier: ^2.30.0
version: 2.30.0
+ dedent:
+ specifier: ^1.5.1
+ version: 1.5.1
dequal:
specifier: ^2.0.3
version: 2.0.3
@@ -1964,6 +1973,109 @@ packages:
'@lezer/common': 1.1.1
dev: false
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-Nq7lmx9SU+JyoaRcs6SaJs7uAmW2W06HpgJVQYeZptVGNWDzDvzhjwVb/ZuG1rwTlOocY4Y9GwNOBuKCeJbKtw==}
+ dependencies:
+ '@codemirror/lang-html': 6.4.7
+ '@codemirror/lang-javascript': 6.2.1
+ '@codemirror/language': 6.9.3
+ '@lezer/common': 1.1.1
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-6oYEYUKHvrnacXxWxYa6t4puTlbN3dgV662BDfSH8+MfjQjVmP697/KYTDOqpxgerkvoNm7q5wlFMBeX8ZMocg==}
+ dependencies:
+ '@codemirror/language': 6.9.3
+ '@lezer/cpp': 1.1.1
+ dev: false
+
+ /@codemirror/[email protected](@codemirror/[email protected]):
+ resolution: {integrity: sha512-/UNWDNV5Viwi/1lpr/dIXJNWiwDxpw13I4pTUAsNxZdg6E0mI2kTQb0P2iHczg1Tu+H4EBgJR+hYhKiHKko7qg==}
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/language': 6.9.3
+ '@codemirror/state': 6.3.2
+ '@lezer/common': 1.1.1
+ '@lezer/css': 1.1.4
+ transitivePeerDependencies:
+ - '@codemirror/view'
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-y9hWSSO41XlcL4uYwWyk0lEgTHcelWWfRuqmvcAmxfCs0HNWZdriWo/EU43S63SxEZpc1Hd50Itw7ktfQvfkUg==}
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/lang-css': 6.2.1(@codemirror/[email protected])
+ '@codemirror/lang-javascript': 6.2.1
+ '@codemirror/language': 6.9.3
+ '@codemirror/state': 6.3.2
+ '@codemirror/view': 6.22.1
+ '@lezer/common': 1.1.1
+ '@lezer/css': 1.1.4
+ '@lezer/html': 1.3.7
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-OOnmhH67h97jHzCuFaIEspbmsT98fNdhVhmA3zCxW0cn7l8rChDhZtwiwJ/JOKXgfm4J+ELxQihxaI7bj7mJRg==}
+ dependencies:
+ '@codemirror/language': 6.9.3
+ '@lezer/java': 1.1.0
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-jlFOXTejVyiQCW3EQwvKH0m99bUYIw40oPmFjSX2VS78yzfe0HELZ+NEo9Yfo1MkGRpGlj3Gnu4rdxV1EnAs5A==}
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/language': 6.9.3
+ '@codemirror/lint': 6.4.2
+ '@codemirror/state': 6.3.2
+ '@codemirror/view': 6.22.1
+ '@lezer/common': 1.1.1
+ '@lezer/javascript': 1.4.9
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-+T1flHdgpqDDlJZ2Lkil/rLiRy684WMLc74xUnjJH48GQdfJo/pudlTRreZmKwzP8/tGdKf83wlbAdOCzlJOGQ==}
+ dependencies:
+ '@codemirror/language': 6.9.3
+ '@lezer/json': 1.0.1
+ dev: false
+
+ /@codemirror/[email protected](@codemirror/[email protected]):
+ resolution: {integrity: sha512-ABcsKBjLbyPZwPR5gePpc8jEKCQrFF4pby2WlMVdmJOOr7OWwwyz8DZonPx/cKDE00hfoSLc8F7yAcn/d6+rTQ==}
+ dependencies:
+ '@codemirror/lang-css': 6.2.1(@codemirror/[email protected])
+ '@codemirror/language': 6.9.3
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ transitivePeerDependencies:
+ - '@codemirror/view'
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-wCewRLWpdefWi7uVkHIDiE8+45Fe4buvMDZkihqEom5uRUQrl76Zb13emjeK3W+8pcRgRfAmwelURBbxNEKCIg==}
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/lang-html': 6.4.7
+ '@codemirror/language': 6.9.3
+ '@codemirror/state': 6.3.2
+ '@codemirror/view': 6.22.1
+ '@lezer/common': 1.1.1
+ '@lezer/markdown': 1.1.1
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-ublojMdw/PNWa7qdN5TMsjmqkNuTBD3k6ndZ4Z0S25SBAiweFGyY68AS3xNcIOlb6DDFDvKlinLQ40vSLqf8xA==}
+ dependencies:
+ '@codemirror/lang-html': 6.4.7
+ '@codemirror/language': 6.9.3
+ '@codemirror/state': 6.3.2
+ '@lezer/common': 1.1.1
+ '@lezer/php': 1.0.1
+ dev: false
+
/@codemirror/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected]):
resolution: {integrity: sha512-S9w2Jl74hFlD5nqtUMIaXAq9t5WlM0acCkyuQWUUSvZclk1sV+UfnpFiZzuZSG+hfEaOmxKR5UxY/Uxswn7EhQ==}
dependencies:
@@ -1976,6 +2088,97 @@ packages:
- '@lezer/common'
dev: false
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-344EMWFBzWArHWdZn/NcgkwMvZIWUR1GEBdwG8FEp++6o6vT6KL9V7vGs2ONsKxxFUPXKI0SPcWhyYyl2zPYxQ==}
+ dependencies:
+ '@codemirror/language': 6.9.3
+ '@lezer/rust': 1.0.1
+ dev: false
+
+ /@codemirror/[email protected](@codemirror/[email protected]):
+ resolution: {integrity: sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q==}
+ dependencies:
+ '@codemirror/lang-css': 6.2.1(@codemirror/[email protected])
+ '@codemirror/language': 6.9.3
+ '@codemirror/state': 6.3.2
+ '@lezer/common': 1.1.1
+ '@lezer/sass': 1.0.3
+ transitivePeerDependencies:
+ - '@codemirror/view'
+ dev: false
+
+ /@codemirror/[email protected](@codemirror/[email protected])(@lezer/[email protected]):
+ resolution: {integrity: sha512-5Gq7fYtT/5HbNyIG7a8vYaqOYQU3JbgtBe3+derkrFUXRVcjkf8WVgz++PIbMFAQsOFMDdDR+uiNM8ZRRuXH+w==}
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/language': 6.9.3
+ '@codemirror/state': 6.3.2
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ transitivePeerDependencies:
+ - '@codemirror/view'
+ - '@lezer/common'
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-D4YrefiRBAr+CfEIM4S3yvGSbYW+N69mttIfGMEf7diHpRbmygDxS+R/5xSqjgtkY6VO6qmUrre1GkRcWeZa9A==}
+ dependencies:
+ '@codemirror/lang-html': 6.4.7
+ '@codemirror/lang-javascript': 6.2.1
+ '@codemirror/language': 6.9.3
+ '@lezer/common': 1.1.1
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-sQLsqhRjl2MWG3rxZysX+2XAyed48KhLBHLgq9xcKxIJu3npH/G+BIXW5NM5mHeDUjG0jcGh9BcjP0NfMStuzA==}
+ dependencies:
+ '@codemirror/language': 6.9.3
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ /@codemirror/[email protected](@codemirror/[email protected]):
+ resolution: {integrity: sha512-JQYZjHL2LAfpiZI2/qZ/qzDuSqmGKMwyApYmEUUCTxLM4MWS7sATUEfIguZQr9Zjx/7gcdnewb039smF6nC2zw==}
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/language': 6.9.3
+ '@codemirror/state': 6.3.2
+ '@lezer/common': 1.1.1
+ '@lezer/xml': 1.0.3
+ transitivePeerDependencies:
+ - '@codemirror/view'
+ dev: false
+
+ /@codemirror/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected]):
+ resolution: {integrity: sha512-p6jhJmvhGe1TG1EGNhwH7nFWWFSTJ8NDKnB2fVx5g3t+PpO0+63R7GJNxjS0TmmH3cdMxZbzejsik+rlEh1EyQ==}
+ dependencies:
+ '@codemirror/lang-angular': 0.1.2
+ '@codemirror/lang-cpp': 6.0.2
+ '@codemirror/lang-css': 6.2.1(@codemirror/[email protected])
+ '@codemirror/lang-html': 6.4.7
+ '@codemirror/lang-java': 6.0.1
+ '@codemirror/lang-javascript': 6.2.1
+ '@codemirror/lang-json': 6.0.1
+ '@codemirror/lang-less': 6.0.1(@codemirror/[email protected])
+ '@codemirror/lang-markdown': 6.2.3
+ '@codemirror/lang-php': 6.0.1
+ '@codemirror/lang-python': 6.1.3(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/lang-rust': 6.0.1
+ '@codemirror/lang-sass': 6.0.2(@codemirror/[email protected])
+ '@codemirror/lang-sql': 6.5.4(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/lang-vue': 0.1.2
+ '@codemirror/lang-wast': 6.0.1
+ '@codemirror/lang-xml': 6.0.2(@codemirror/[email protected])
+ '@codemirror/language': 6.9.3
+ '@codemirror/legacy-modes': 6.3.3
+ transitivePeerDependencies:
+ - '@codemirror/state'
+ - '@codemirror/view'
+ - '@lezer/common'
+ dev: false
+
/@codemirror/[email protected]:
resolution: {integrity: sha512-qq48pYzoi6ldYWV/52+Z9Ou6QouVI+8YwvxFbUypI33NbjG2UeRHKENRyhwljTTiOqjQ33FjyZj6EREQ9apAOQ==}
dependencies:
@@ -1987,6 +2190,12 @@ packages:
style-mod: 4.1.0
dev: false
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-X0Z48odJ0KIoh/HY8Ltz75/4tDYc9msQf1E/2trlxFaFFhgjpVHjZ/BCXe1Lk7s4Gd67LL/CeEEHNI+xHOiESg==}
+ dependencies:
+ '@codemirror/language': 6.9.3
+ dev: false
+
/@codemirror/[email protected]:
resolution: {integrity: sha512-wzRkluWb1ptPKdzlsrbwwjYCPLgzU6N88YBAmlZi8WFyuiEduSd05MnJYNogzyc8rPK7pj6m95ptUApc8sHKVA==}
dependencies:
@@ -2635,18 +2844,75 @@ packages:
resolution: {integrity: sha512-aAPB9YbvZHqAW+bIwiuuTDGB4DG0sYNRObGLxud8cW7osw1ZQxfDuTZ8KQiqfZ0QJGcR34CvpTMDXEyo/+Htgg==}
dev: false
+ resolution: {integrity: sha512-eS1M3L3U2mDowoFVPG7tEp01SWu9/68Nx3HEBgLJVn3N9ku7g5S7WdFv0jzmcTipAyONYfZJ+7x4WRkfdB2Ung==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ resolution: {integrity: sha512-CuUwjidrU7FOBokqASRJc72SmJ9g1PsHXDOWMoKg4md6+2u/Zxzwx5YsYrAFxRDsLrjLlsIyEF1rZHK3gFEJbw==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
resolution: {integrity: sha512-WrS5Mw51sGrpqjlh3d4/fOwpEV2Hd3YOkp9DBt4k8XZQcoTHZFB7sx030A6OcahF4J1nDQAa3jXlTVVYH50IFA==}
dependencies:
'@lezer/common': 1.1.1
dev: false
+ resolution: {integrity: sha512-Wo+rZ5UjLP0VqUTyXjzgmTYRW5bvTJUFn4Uw0K3HCQjX2/+f+zRo9GLN5BCAojwHQISPvaQk8BWSv2SSKx/UcQ==}
+ dependencies:
+ '@lezer/common': 1.1.1
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ resolution: {integrity: sha512-RmBS+P9LJ4P9SU7ZewahMkBUNOEz1zQTMOKLq8OEa7ge8FZxz7mKjoEIGewRSn9kom1z5GKQjtxNE++m6u8SYw==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ resolution: {integrity: sha512-7Uv8mBBE6l44spgWEZvEMdDqGV+FIuY7kJ1o5TFm+jxIuxydO3PcKJYiINij09igd1D/9P7l2KDqpkN8c3bM6A==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ resolution: {integrity: sha512-nkVC27qiEZEjySbi6gQRuMwa2sDu2PtfjSgz0A4QF81QyRGm3kb2YRzLcOPcTEtmcwvrX/cej7mlhbwViA4WJw==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
resolution: {integrity: sha512-z5mY4LStlA3yL7aHT/rqgG614cfcvklS+8oFRFBYrs4YaWLJyKKM4+nN6KopToX0o9Hj6zmH6M5kinOYuy06ug==}
dependencies:
'@lezer/common': 1.1.1
dev: false
+ resolution: {integrity: sha512-kmxvLnXCogUx2mexslWwVME1W2GQP76pwUODcFXLsuubuK41TcEJhKRm2FTKugNfEkUIspJNq9+jNo6b7dxVLA==}
+ dependencies:
+ '@lezer/common': 1.1.1
+ '@lezer/highlight': 1.2.0
+ dev: false
+
+ resolution: {integrity: sha512-aqdCQJOXJ66De22vzdwnuC502hIaG9EnPK2rSi+ebXyUd+j7GAX1mRjWZOVOmf3GST1YUfUCu6WXDiEgDGOVwA==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
resolution: {integrity: sha512-RbhKQ9+Y/r/Xv6OcJmETEM5tBFdpdAJRqrgi3akJkWBLCuiAaLP/jKdYzu+ICljaSXPCQeznrv+r9HUEnjq3HQ==}
dependencies:
@@ -2654,6 +2920,27 @@ packages:
'@lezer/lr': 1.3.14
dev: false
+ resolution: {integrity: sha512-j+ToFKM6Wpglv3OQ4ebHYdYIMT2dh0ziCCV0rTf47AWiHOVhR0WjaKrBq+yuvDQNEhr5sxPxVI7+naJIgpqcsQ==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ resolution: {integrity: sha512-n4l2nVOB7gWiGU/Cg2IVxpt2Ic9Hgfgy/7gk+p/XJibAsPXs0lSbsfGwQgwsAw9B/euYo3oS6lEFr9WytoqcZg==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ resolution: {integrity: sha512-lYT+0TKiDW4jQyz+R/JXQpbWavjIKqyFMvJ73JklyxFmAUnD6Iford98dk0OeVZG0j4MNnR7JQlmwTMpJGrU6A==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
resolution: {integrity: sha512-tJaT+RbYGJYStt7wI3cq4Nl4SXxG8W7JDG5DMJu97V25RnbNg3QtQtf+KD+VLjNpWKYsRvXDNmNrBgEETr1ifA==}
hasBin: true
@@ -8414,6 +8701,15 @@ packages:
resolution: {integrity: sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==}
dev: true
+ resolution: {integrity: sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg==}
+ peerDependencies:
+ babel-plugin-macros: ^3.1.0
+ peerDependenciesMeta:
+ babel-plugin-macros:
+ optional: true
+ dev: false
+
resolution: {integrity: sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==}
engines: {node: '>=6'}
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 0930858cd6..8b9378b047 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -1,7 +1,5 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { closeCompletion, completionStatus } from "@codemirror/autocomplete";
-import { historyField } from "@codemirror/commands";
-import { EditorState, StateEffect } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import {
memo,
@@ -9,18 +7,16 @@ import {
KeyboardEvent,
forwardRef,
useCallback,
- useEffect,
useImperativeHandle,
useRef,
- useLayoutEffect,
} from "react";
import { sendRun } from "@/core/network/requests";
-import { autocompletionKeymap, setupCodeMirror } from "@/core/codemirror/cm";
+import { autocompletionKeymap } from "@/core/codemirror/cm";
import { clearTooltips } from "@/core/codemirror/completion/hints";
import { UserConfig } from "../../core/config/config-schema";
import { CellData, CellRuntimeState } from "../../core/cells/types";
-import { CellActions, useCellActions } from "../../core/cells/cells";
+import { CellActions } from "../../core/cells/cells";
import { derefNotNull } from "../../utils/dereference";
import { OutputArea } from "./Output";
import { ConsoleOutput } from "./output/ConsoleOutput";
@@ -41,6 +37,8 @@ import { CellActionsDropdown } from "./cell/cell-actions";
import { CellActionsContextMenu } from "./cell/cell-context-menu";
import { AppMode } from "@/core/mode";
import useEvent from "react-use-event-hook";
+import { CellEditor } from "./cell/code/cell-editor";
+import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";
/**
* Imperative interface of the cell.
@@ -50,10 +48,6 @@ export interface CellHandle {
* The CodeMirror editor view.
*/
editorView: EditorView;
- /**
- * Get the serialized editor state.
- */
- editorStateJSON: () => Record<string, unknown>;
/**
* Register the cell to run.
*/
@@ -137,8 +131,6 @@ const CellComponent = (
Logger.debug("Rendering Cell", cellId);
const cellRef = useRef<HTMLDivElement>(null);
const editorView = useRef<EditorView | null>(null);
- // DOM node where the editorView will be mounted
- const editorViewParentRef = useRef<HTMLDivElement>(null);
const needsRun = edited || interrupted;
const loading = status === "running" || status === "queued";
@@ -159,15 +151,13 @@ const CellComponent = (
const consoleOutputStale =
(status === "queued" || edited || status === "stale") && !interrupted;
const editing = mode === "edit";
- const reading = mode === "read";
- const { sendToTop, sendToBottom } = useCellActions();
// Performs side-effects that must run whenever the cell is run, but doesn't
// actually run the cell.
//
// Returns the code to run.
const prepareToRunEffects = useCallback(() => {
- const code = derefNotNull(editorView).state.doc.toString();
+ const code = getEditorCodeAsPython(derefNotNull(editorView));
closeCompletion(derefNotNull(editorView));
prepareForRun({ cellId });
return code;
@@ -180,9 +170,6 @@ const CellComponent = (
get editorView() {
return derefNotNull(editorView);
},
- editorStateJSON: () => {
- return derefNotNull(editorView).state.toJSON({ history: historyField });
- },
registerRun: prepareToRunEffects,
}),
[editorView, prepareToRunEffects]
@@ -198,16 +185,6 @@ const CellComponent = (
sendRun([cellId], [code]);
});
- const handleDelete = useEvent(() => {
- // Cannot delete running cells, since we're waiting for their output.
- if (loading) {
- return false;
- }
-
- deleteCell({ cellId });
- return true;
- });
-
const createBelow = useCallback(
() => createNewCell({ cellId, before: false }),
[cellId, createNewCell]
@@ -216,138 +193,6 @@ const CellComponent = (
() => createNewCell({ cellId, before: true }),
[cellId, createNewCell]
);
- const moveDown = useCallback(
- () => moveCell({ cellId, before: false }),
- [cellId, moveCell]
- );
- const moveUp = useCallback(
- () => moveCell({ cellId, before: true }),
- [cellId, moveCell]
- );
- const focusDown = useCallback(
- () => focusCell({ cellId, before: false }),
- [cellId, focusCell]
- );
- const focusUp = useCallback(
- () => focusCell({ cellId, before: true }),
- [cellId, focusCell]
- );
-
- useEffect(() => {
- if (reading) {
- return;
- }
-
- const extensions = setupCodeMirror({
- cellId,
- showPlaceholder,
- cellCodeCallbacks: {
- updateCellCode,
- },
- cellMovementCallbacks: {
- onRun: handleRun,
- deleteCell: handleDelete,
- createAbove,
- createBelow,
- moveUp,
- moveDown,
- focusUp,
- focusDown,
- sendToTop,
- sendToBottom,
- moveToNextCell,
- },
- completionConfig: userConfig.completion,
- keymapConfig: userConfig.keymap,
- theme,
- });
-
- // Should focus will be true if its a newly created editor
- let shouldFocus: boolean;
- if (serializedEditorState === null) {
- // If the editor already exists, reconfigure it with the new extensions.
- // Triggered when, e.g., placeholder changes.
- if (editorView.current === null) {
- // Otherwise, create a new editor.
- editorView.current = new EditorView({
- state: EditorState.create({
- doc: code,
- extensions: extensions,
- }),
- });
- shouldFocus = true;
- } else {
- editorView.current.dispatch({
- effects: [StateEffect.reconfigure.of([extensions])],
- });
- shouldFocus = false;
- }
- } else {
- editorView.current = new EditorView({
- state: EditorState.fromJSON(
- serializedEditorState,
- {
- doc: code,
- extensions: extensions,
- },
- { history: historyField }
- ),
- });
- shouldFocus = true;
- }
-
- if (editorView.current !== null && editorViewParentRef.current !== null) {
- // Always replace the children in case the editor view was re-created.
- editorViewParentRef.current.replaceChildren(editorView.current.dom);
- }
-
- if (shouldFocus && allowFocus) {
- // Focus and scroll into view; request an animation frame to
- // avoid a race condition when new editors are created
- // very rapidly by holding a hotkey
- requestAnimationFrame(() => {
- editorView.current?.focus();
- editorView.current?.dom.scrollIntoView({
- behavior: "smooth",
- block: "center",
- });
- });
- }
-
- // We don't want to re-run this effect when `allowFocus` or `code` changes
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [
- reading,
- cellId,
- userConfig.completion.activate_on_typing,
- userConfig.keymap,
- theme,
- showPlaceholder,
- createAbove,
- createBelow,
- focusUp,
- focusDown,
- moveUp,
- moveDown,
- moveToNextCell,
- updateCellCode,
- handleDelete,
- handleRun,
- serializedEditorState,
- ]);
-
- useLayoutEffect(() => {
- if (editorView.current === null) {
- return;
- }
- if (
- editing &&
- editorViewParentRef.current !== null &&
- editorView.current !== null
- ) {
- editorViewParentRef.current.replaceChildren(editorView.current.dom);
- }
- }, [editing]);
// Close completion when focus leaves the cell's subtree.
const closeCompletionHandler = useCallback((e: FocusEvent) => {
@@ -436,8 +281,6 @@ const CellComponent = (
}
};
- const editor = <div className="cm" ref={editorViewParentRef} />;
-
return (
<CellActionsContextMenu
cellId={cellId}
@@ -475,7 +318,25 @@ const CellComponent = (
/>
</div>
</div>
- {editor}
+ <CellEditor
+ theme={theme}
+ showPlaceholder={showPlaceholder}
+ allowFocus={allowFocus}
+ id={cellId}
+ code={code}
+ status={status}
+ serializedEditorState={serializedEditorState}
+ mode={mode}
+ runCell={handleRun}
+ updateCellCode={updateCellCode}
+ createNewCell={createNewCell}
+ deleteCell={deleteCell}
+ focusCell={focusCell}
+ moveCell={moveCell}
+ moveToNextCell={moveToNextCell}
+ userConfig={userConfig}
+ editorViewRef={editorView}
+ />
<div className="shoulder-right">
<CellStatusComponent
status={status}
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
new file mode 100644
index 0000000000..ade4f9865c
--- /dev/null
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -0,0 +1,274 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { historyField } from "@codemirror/commands";
+import { EditorState, StateEffect } from "@codemirror/state";
+import { EditorView, ViewPlugin } from "@codemirror/view";
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useRef,
+ useLayoutEffect,
+ useState,
+} from "react";
+
+import { setupCodeMirror } from "@/core/codemirror/cm";
+import { AppMode } from "@/core/mode";
+import useEvent from "react-use-event-hook";
+import { CellActions, useCellActions } from "@/core/cells/cells";
+import { CellRuntimeState, CellData } from "@/core/cells/types";
+import { SerializedEditorState } from "@/core/codemirror/types";
+import { UserConfig } from "@/core/config/config-schema";
+import { Theme } from "@/theme/useTheme";
+import {
+ LanguageAdapters,
+ languageAdapterState,
+ reconfigureLanguageEffect,
+} from "@/core/codemirror/language/extension";
+import { derefNotNull } from "@/utils/dereference";
+import { LanguageToggle } from "./language-toggle";
+
+export interface CellEditorProps
+ extends Pick<CellRuntimeState, "status">,
+ Pick<CellData, "id" | "code">,
+ Pick<
+ CellActions,
+ | "updateCellCode"
+ | "createNewCell"
+ | "deleteCell"
+ | "focusCell"
+ | "moveCell"
+ | "moveToNextCell"
+ > {
+ runCell: () => void;
+ theme: Theme;
+ showPlaceholder: boolean;
+ serializedEditorState: SerializedEditorState | null;
+ mode: AppMode;
+ editorViewRef: React.MutableRefObject<EditorView | null>;
+ /**
+ * If true, the cell is allowed to be focus on.
+ * This is false when the app is initially loading.
+ */
+ allowFocus: boolean;
+ userConfig: UserConfig;
+}
+
+const CellEditorInternal = ({
+ theme,
+ showPlaceholder,
+ allowFocus,
+ id: cellId,
+ code,
+ status,
+ serializedEditorState,
+ mode,
+ runCell,
+ updateCellCode,
+ createNewCell,
+ deleteCell,
+ focusCell,
+ moveCell,
+ moveToNextCell,
+ userConfig,
+ editorViewRef,
+}: CellEditorProps) => {
+ const [canUseMarkdown, setCanUseMarkdown] = useState(false);
+
+ // DOM node where the editorView will be mounted
+ const editorViewParentRef = useRef<HTMLDivElement>(null);
+
+ const loading = status === "running" || status === "queued";
+ const editing = mode === "edit";
+ const reading = mode === "read";
+ const { sendToTop, sendToBottom } = useCellActions();
+
+ const handleDelete = useEvent(() => {
+ // Cannot delete running cells, since we're waiting for their output.
+ if (loading) {
+ return false;
+ }
+
+ deleteCell({ cellId });
+ return true;
+ });
+
+ const createBelow = useCallback(
+ () => createNewCell({ cellId, before: false }),
+ [cellId, createNewCell]
+ );
+ const createAbove = useCallback(
+ () => createNewCell({ cellId, before: true }),
+ [cellId, createNewCell]
+ );
+ const moveDown = useCallback(
+ () => moveCell({ cellId, before: false }),
+ [cellId, moveCell]
+ );
+ const moveUp = useCallback(
+ () => moveCell({ cellId, before: true }),
+ [cellId, moveCell]
+ );
+ const focusDown = useCallback(
+ () => focusCell({ cellId, before: false }),
+ [cellId, focusCell]
+ );
+ const focusUp = useCallback(
+ () => focusCell({ cellId, before: true }),
+ [cellId, focusCell]
+ );
+
+ useEffect(() => {
+ if (reading) {
+ return;
+ }
+
+ const extensions = setupCodeMirror({
+ cellId,
+ showPlaceholder,
+ cellCodeCallbacks: {
+ updateCellCode,
+ },
+ cellMovementCallbacks: {
+ onRun: runCell,
+ deleteCell: handleDelete,
+ createAbove,
+ createBelow,
+ moveUp,
+ moveDown,
+ focusUp,
+ focusDown,
+ sendToTop,
+ sendToBottom,
+ moveToNextCell,
+ },
+ completionConfig: userConfig.completion,
+ keymapConfig: userConfig.keymap,
+ theme,
+ });
+
+ // listen to code changes if we can use markdown
+ extensions.push(
+ ViewPlugin.define(() => ({
+ update(view) {
+ const code = view.state.doc.toString();
+ const languageAdapter = view.state.field(languageAdapterState);
+ // If its not markdown, set if we can use markdown
+ if (languageAdapter.type !== "markdown") {
+ setCanUseMarkdown(LanguageAdapters.markdown().isSupported(code));
+ }
+ },
+ }))
+ );
+
+ // Should focus will be true if its a newly created editor
+ let shouldFocus: boolean;
+ if (serializedEditorState === null) {
+ // If the editor already exists, reconfigure it with the new extensions.
+ // Triggered when, e.g., placeholder changes.
+ if (editorViewRef.current === null) {
+ // Otherwise, create a new editor.
+ editorViewRef.current = new EditorView({
+ state: EditorState.create({
+ doc: code,
+ extensions: extensions,
+ }),
+ });
+ shouldFocus = true;
+ } else {
+ editorViewRef.current.dispatch({
+ effects: [
+ StateEffect.reconfigure.of([extensions]),
+ reconfigureLanguageEffect(
+ editorViewRef.current,
+ userConfig.completion
+ ),
+ ],
+ });
+ shouldFocus = false;
+ }
+ } else {
+ editorViewRef.current = new EditorView({
+ state: EditorState.fromJSON(
+ serializedEditorState,
+ {
+ doc: code,
+ extensions: extensions,
+ },
+ { history: historyField }
+ ),
+ });
+ shouldFocus = true;
+ }
+
+ if (
+ editorViewRef.current !== null &&
+ editorViewParentRef.current !== null
+ ) {
+ // Always replace the children in case the editor view was re-created.
+ editorViewParentRef.current.replaceChildren(editorViewRef.current.dom);
+ }
+
+ if (shouldFocus && allowFocus) {
+ // Focus and scroll into view; request an animation frame to
+ // avoid a race condition when new editors are created
+ // very rapidly by holding a hotkey
+ requestAnimationFrame(() => {
+ editorViewRef.current?.focus();
+ editorViewRef.current?.dom.scrollIntoView({
+ behavior: "smooth",
+ block: "center",
+ });
+ });
+ }
+
+ // We don't want to re-run this effect when `allowFocus` or `code` changes
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ reading,
+ cellId,
+ userConfig.completion.activate_on_typing,
+ userConfig.keymap,
+ theme,
+ showPlaceholder,
+ createAbove,
+ createBelow,
+ focusUp,
+ focusDown,
+ moveUp,
+ moveDown,
+ moveToNextCell,
+ updateCellCode,
+ handleDelete,
+ runCell,
+ serializedEditorState,
+ ]);
+
+ useLayoutEffect(() => {
+ if (editorViewRef.current === null) {
+ return;
+ }
+ if (
+ editing &&
+ editorViewParentRef.current !== null &&
+ editorViewRef.current !== null
+ ) {
+ editorViewParentRef.current.replaceChildren(editorViewRef.current.dom);
+ }
+ }, [editing, editorViewRef]);
+
+ return (
+ <>
+ {canUseMarkdown && (
+ <div className="absolute top-1 right-1">
+ <LanguageToggle
+ editorView={derefNotNull(editorViewRef)}
+ canUseMarkdown={canUseMarkdown}
+ />
+ </div>
+ )}
+ <div className="cm" ref={editorViewParentRef} />
+ </>
+ );
+};
+
+export const CellEditor = memo(CellEditorInternal);
diff --git a/frontend/src/components/editor/cell/code/icons.tsx b/frontend/src/components/editor/cell/code/icons.tsx
new file mode 100644
index 0000000000..d6d6466409
--- /dev/null
+++ b/frontend/src/components/editor/cell/code/icons.tsx
@@ -0,0 +1,27 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+import { SVGProps } from "react";
+
+export const PythonIcon = (props: SVGProps<SVGSVGElement>) => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="1em"
+ height="1em"
+ viewBox="0 0 448 512"
+ {...props}
+ >
+ <path d="M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z" />
+ </svg>
+);
+
+export const MarkdownIcon = (props: SVGProps<SVGSVGElement>) => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="1em"
+ height="1em"
+ viewBox="0 0 640 512"
+ {...props}
+ >
+ <path d="M593.8 59.1H46.2C20.7 59.1 0 79.8 0 105.2v301.5c0 25.5 20.7 46.2 46.2 46.2h547.7c25.5 0 46.2-20.7 46.1-46.1V105.2c0-25.4-20.7-46.1-46.2-46.1zM338.5 360.6H277v-120l-61.5 76.9-61.5-76.9v120H92.3V151.4h61.5l61.5 76.9 61.5-76.9h61.5v209.2zm135.3 3.1L381.5 256H443V151.4h61.5V256H566z" />
+ </svg>
+);
diff --git a/frontend/src/components/editor/cell/code/language-toggle.tsx b/frontend/src/components/editor/cell/code/language-toggle.tsx
new file mode 100644
index 0000000000..4db2ebfd11
--- /dev/null
+++ b/frontend/src/components/editor/cell/code/language-toggle.tsx
@@ -0,0 +1,50 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import {
+ languageAdapterState,
+ switchLanguage,
+} from "@/core/codemirror/language/extension";
+import { EditorView } from "@codemirror/view";
+import React, { useState } from "react";
+import { MarkdownIcon, PythonIcon } from "./icons";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
+import { startCase } from "lodash-es";
+
+interface Props {
+ editorView: EditorView;
+ canUseMarkdown: boolean;
+}
+
+export const LanguageToggle: React.FC<Props> = ({
+ editorView,
+ canUseMarkdown,
+}) => {
+ const [languageAdapter, setLanguageAdapter] = useState(
+ editorView.state.field(languageAdapterState).type
+ );
+
+ if (!canUseMarkdown && languageAdapter !== "markdown") {
+ return null;
+ }
+
+ const otherLanguage = languageAdapter === "markdown" ? "python" : "markdown";
+ const Icon = languageAdapter === "markdown" ? PythonIcon : MarkdownIcon;
+
+ return (
+ <div className="absolute top-0 right-5 z-20 hover-action">
+ <Tooltip content={`View as ${startCase(otherLanguage)}`}>
+ <Button variant="text" size="xs" className="opacity-80">
+ <Icon
+ className="cursor-pointer"
+ fill={"var(--sky-11)"}
+ fontSize={20}
+ onClick={() => {
+ setLanguageAdapter(otherLanguage);
+ switchLanguage(editorView, otherLanguage);
+ }}
+ />
+ </Button>
+ </Tooltip>
+ </div>
+ );
+};
diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.ts
index 5d67cc7200..06210022d8 100644
--- a/frontend/src/components/editor/cell/useRunCells.ts
+++ b/frontend/src/components/editor/cell/useRunCells.ts
@@ -5,6 +5,7 @@ import { sendRun } from "@/core/network/requests";
import { staleCellIds, useNotebook } from "@/core/cells/cells";
import { derefNotNull } from "@/utils/dereference";
import useEvent from "react-use-event-hook";
+import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";
/**
* Creates a function that runs all cells that have been edited or interrupted.
@@ -41,7 +42,7 @@ function useRunCells() {
const codes: string[] = [];
for (const cellId of cellIds) {
const ref = derefNotNull(cellHandles[cellId]);
- codes.push(ref.editorView.state.doc.toString());
+ codes.push(getEditorCodeAsPython(ref.editorView));
ref.registerRun();
}
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index fc5e2f8dd5..c01f6484c5 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -30,6 +30,8 @@ import { splitAtom, selectAtom } from "jotai/utils";
import { isStaticNotebook, parseStaticState } from "../static/static-state";
import { CellLog, getCellLogsForMessage } from "./logs";
import { deserializeBase64ToJson } from "@/utils/json/base64";
+import { historyField } from "@codemirror/commands";
+import { clamp } from "@/utils/math";
/**
* The state of the notebook.
@@ -181,7 +183,7 @@ const { reducer, createActions } = createReducer(initialNotebookState, {
const index = state.cellIds.indexOf(cellId);
let focusIndex = before ? index - 1 : index + 1;
// clamp
- focusIndex = Math.max(0, Math.min(focusIndex, state.cellIds.length - 1));
+ focusIndex = clamp(focusIndex, 0, state.cellIds.length - 1);
const focusCellId = state.cellIds[focusIndex];
// can scroll immediately, without setting scrollKey in state, because
// CellArray won't need to re-render
@@ -245,6 +247,9 @@ const { reducer, createActions } = createReducer(initialNotebookState, {
const focusIndex = index === 0 ? 1 : index - 1;
const scrollKey = state.cellIds[focusIndex];
+ const serializedEditorState = state.cellHandles[
+ cellKey
+ ].current?.editorView.state.toJSON({ history: historyField });
return {
...state,
cellIds: arrayDelete(state.cellIds, index),
@@ -252,8 +257,7 @@ const { reducer, createActions } = createReducer(initialNotebookState, {
...state.history,
{
name: state.cellData[cellKey].name,
- serializedEditorState:
- state.cellHandles[cellKey].current?.editorStateJSON(),
+ serializedEditorState: serializedEditorState,
index: index,
},
],
diff --git a/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap b/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap
index 3ad02b7df7..2e48911db4 100644
--- a/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap
+++ b/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap
@@ -54,11 +54,11 @@ exports[`snapshot all duplicate keymaps > default keymaps 2`] = `
"Escape": [
{
"key": "Escape",
- "run": "closeCompletion",
+ "run": "clearTooltips",
},
{
"key": "Escape",
- "run": "clearTooltips",
+ "run": "closeCompletion",
},
{
"key": "Escape",
@@ -166,11 +166,11 @@ exports[`snapshot all duplicate keymaps > vim keymaps 2`] = `
"Escape": [
{
"key": "Escape",
- "run": "closeCompletion",
+ "run": "clearTooltips",
},
{
"key": "Escape",
- "run": "clearTooltips",
+ "run": "closeCompletion",
},
{
"key": "Escape",
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index 81cd1c3485..0d8d1dbad0 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -5,6 +5,8 @@ import { CellId } from "@/core/cells/ids";
import { Extension, Prec } from "@codemirror/state";
import { formatKeymapExtension } from "../extensions";
import { CellActions } from "@/core/cells/cells";
+import { getEditorCodeAsPython } from "../language/utils";
+import { formattingChangeEffect } from "../format";
export interface MovementCallbacks
extends Pick<CellActions, "sendToTop" | "sendToBottom" | "moveToNextCell"> {
@@ -170,9 +172,18 @@ export function cellCodeEditingBundle(
const { updateCellCode } = callbacks;
const onChangePlugin = EditorView.updateListener.of((update) => {
+ // Check if the doc update was a formatting change
+ // e.g. changing from python to markdown
+ const isFormattingChange = update.transactions.some((tr) =>
+ tr.effects.some((effect) => effect.is(formattingChangeEffect))
+ );
if (update.docChanged) {
- const nextCode = update.state.doc.toString();
- updateCellCode({ cellId, code: nextCode, formattingChange: false });
+ const nextCode = getEditorCodeAsPython(update.view);
+ updateCellCode({
+ cellId,
+ code: nextCode,
+ formattingChange: isFormattingChange,
+ });
}
});
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.ts
index d8b4c422d5..ca6280bec4 100644
--- a/frontend/src/core/codemirror/cm.ts
+++ b/frontend/src/core/codemirror/cm.ts
@@ -1,7 +1,6 @@
/* Copyright 2023 Marimo. All rights reserved. */
import {
acceptCompletion,
- autocompletion,
closeBrackets,
closeBracketsKeymap,
} from "@codemirror/autocomplete";
@@ -11,19 +10,11 @@ import {
indentWithTab,
indentMore,
} from "@codemirror/commands";
-import {
- pythonLanguage,
- localCompletionSource,
- globalCompletion,
-} from "@codemirror/lang-python";
import {
bracketMatching,
defaultHighlightStyle,
foldGutter,
- foldInside,
foldKeymap,
- foldNodeProp,
- LanguageSupport,
indentOnInput,
indentUnit,
syntaxHighlighting,
@@ -48,7 +39,6 @@ import { oneDark } from "@codemirror/theme-one-dark";
import { CompletionConfig, KeymapConfig } from "../config/config-schema";
import { Theme } from "../../theme/useTheme";
-import { completer } from "@/core/codemirror/completion/completer";
import { findReplaceBundle } from "./find-replace/extension";
import {
CodeCallbacks,
@@ -64,6 +54,8 @@ import {
} from "./extensions";
import { copilotBundle } from "./copilot/extension";
import { hintTooltip } from "./completion/hints";
+import { adaptiveLanguageConfiguration } from "./language/extension";
+import { historyCompartment } from "./editing/extensions";
export interface CodeMirrorSetupOpts {
cellId: CellId;
@@ -101,17 +93,6 @@ export const setupCodeMirror = ({
];
};
-// Customize python to support folding some additional syntax nodes
-const customizedPython = pythonLanguage.configure({
- props: [
- foldNodeProp.add({
- ParenthesizedExpression: foldInside,
- // Fold function calls whose arguments are split over multiple lines
- ArgList: foldInside,
- }),
- ],
-});
-
// Based on codemirror's basicSetup extension
export const basicBundle = (
completionConfig: CompletionConfig,
@@ -135,20 +116,6 @@ export const basicBundle = (
scrollActiveLineIntoView(),
theme === "dark" ? oneDark : [],
- ///// Language Support
- // Whether or not to require keypress to activate autocompletion (default
- // keymap is Ctrl+Space)
- autocompletion({
- activateOnTyping: completionConfig.activate_on_typing,
- // The Cell component handles the blur event. `closeOnBlur` is too
- // aggressive and doesn't let the user click into the completion info
- // element (which contains the docstring/type --- users might want to
- // copy paste from the docstring). The main issue is that the completion
- // tooltip is not part of the editable DOM tree:
- // https://discuss.codemirror.net/t/adding-click-event-listener-to-autocomplete-tooltip-info-panel-is-not-working/4741
- closeOnBlur: false,
- override: [completer],
- }),
hintTooltip(),
copilotBundle(),
foldGutter(),
@@ -161,14 +128,11 @@ export const basicBundle = (
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
keymap.of([...foldKeymap, ...lintKeymap]),
- ///// Python Support
- new LanguageSupport(customizedPython, [
- customizedPython.data.of({ autocomplete: localCompletionSource }),
- customizedPython.data.of({ autocomplete: globalCompletion }),
- ]),
+ ///// Language Support
+ adaptiveLanguageConfiguration(completionConfig),
///// Editing
- history(),
+ historyCompartment.of(history()),
EditorState.allowMultipleSelections.of(true),
findReplaceBundle(),
keymap.of([
diff --git a/frontend/src/core/codemirror/completion/hints.ts b/frontend/src/core/codemirror/completion/hints.ts
index 263d5f98e3..6955771fca 100644
--- a/frontend/src/core/codemirror/completion/hints.ts
+++ b/frontend/src/core/codemirror/completion/hints.ts
@@ -87,13 +87,14 @@ export function dispatchShowTooltip(
}
export function clearTooltips(view: EditorView): boolean {
- const hasCompletionTooltip = view.state.field(cursorTooltipField).length > 0;
- if (hasCompletionTooltip) {
- view.dispatch({
- effects: TooltipFromCompletionApi.of([]),
- });
- return true;
- }
+ // We stopped showing cursorTooltipField
+ // const hasCompletionTooltip = view.state.field(cursorTooltipField).length > 0;
+ // if (hasCompletionTooltip) {
+ // view.dispatch({
+ // effects: TooltipFromCompletionApi.of([]),
+ // });
+ // return true;
+ // }
return false;
}
@@ -101,7 +102,7 @@ export function clearTooltips(view: EditorView): boolean {
const TooltipFromCompletionApi = StateEffect.define<Tooltip[]>();
// Field that stores the current tooltips
-const cursorTooltipField = StateField.define<Tooltip[]>({
+export const cursorTooltipField = StateField.define<Tooltip[]>({
create: () => {
return [];
},
diff --git a/frontend/src/core/codemirror/config/extension.ts b/frontend/src/core/codemirror/config/extension.ts
new file mode 100644
index 0000000000..ae808deea7
--- /dev/null
+++ b/frontend/src/core/codemirror/config/extension.ts
@@ -0,0 +1,10 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { CompletionConfig } from "@/core/config/config-schema";
+import { Facet } from "@codemirror/state";
+
+export const completionConfigState = Facet.define<
+ CompletionConfig,
+ CompletionConfig
+>({
+ combine: (values) => values[0],
+});
diff --git a/frontend/src/core/codemirror/copilot/getCodes.ts b/frontend/src/core/codemirror/copilot/getCodes.ts
index b201030305..cd3006fe8d 100644
--- a/frontend/src/core/codemirror/copilot/getCodes.ts
+++ b/frontend/src/core/codemirror/copilot/getCodes.ts
@@ -1,5 +1,6 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { getAllEditorViews } from "@/core/cells/cells";
+import { getEditorCodeAsPython } from "../language/utils";
export function getCodes(otherCode: string) {
// Get all other cells' code
@@ -7,10 +8,11 @@ export function getCodes(otherCode: string) {
// TODO: we should sort this topologically
const codes = getAllEditorViews()
.map((editorView) => {
- if (editorView.state.doc.toString() === otherCode) {
+ const code = getEditorCodeAsPython(editorView);
+ if (code === otherCode) {
return null;
}
- return editorView.state.doc.toString();
+ return code;
})
.filter(Boolean)
.sort((a, b) => {
diff --git a/frontend/src/core/codemirror/editing/extensions.ts b/frontend/src/core/codemirror/editing/extensions.ts
new file mode 100644
index 0000000000..b37a1359e4
--- /dev/null
+++ b/frontend/src/core/codemirror/editing/extensions.ts
@@ -0,0 +1,4 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { Compartment } from "@codemirror/state";
+
+export const historyCompartment = new Compartment();
diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.ts
index 1e2c12fe74..4653a8096f 100644
--- a/frontend/src/core/codemirror/format.ts
+++ b/frontend/src/core/codemirror/format.ts
@@ -8,6 +8,13 @@ import {
getNotebook,
notebookCellEditorViews,
} from "../cells/cells";
+import {
+ getEditorCodeAsPython,
+ updateEditorCodeFromPython,
+} from "./language/utils";
+import { StateEffect } from "@codemirror/state";
+
+export const formattingChangeEffect = StateEffect.define<boolean>();
/**
* Format the code in the editor views via the marimo server,
@@ -17,7 +24,7 @@ export async function formatEditorViews(
views: Record<CellId, EditorView>,
updateCellCode: CellActions["updateCellCode"]
) {
- const codes = Objects.mapValues(views, (view) => view.state.doc.toString());
+ const codes = Objects.mapValues(views, (view) => getEditorCodeAsPython(view));
const formatResponse = await sendFormat(codes);
@@ -35,16 +42,8 @@ export async function formatEditorViews(
continue;
}
+ updateEditorCodeFromPython(view, formattedCode);
updateCellCode({ cellId, code: formattedCode, formattingChange: true });
-
- view.dispatch({
- changes: {
- from: 0,
- // overwrite the entire document
- to: view.state.doc.length,
- insert: formattedCode,
- },
- });
}
}
diff --git a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts b/frontend/src/core/codemirror/language/__tests__/markdown.test.ts
new file mode 100644
index 0000000000..e4a6998645
--- /dev/null
+++ b/frontend/src/core/codemirror/language/__tests__/markdown.test.ts
@@ -0,0 +1,215 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { expect, describe, it } from "vitest";
+import { MarkdownLanguageAdapter } from "../markdown";
+
+const adapter = new MarkdownLanguageAdapter();
+
+describe("MarkdownLanguageAdapter", () => {
+ describe("transformIn", () => {
+ it("should extract inner Markdown from triple double-quoted strings", () => {
+ const pythonCode = 'mo.md("""# Markdown Title\n\nSome content here.""")';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("# Markdown Title\n\nSome content here.");
+ expect(offset).toBe(9);
+ });
+
+ it("should handle single double-quoted strings", () => {
+ const pythonCode = 'mo.md("Some *markdown* content")';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("Some *markdown* content");
+ expect(offset).toBe(7);
+ });
+
+ it("should handle triple single-quoted strings", () => {
+ const pythonCode = "mo.md('''# Another Title\nContent''')";
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("# Another Title\nContent");
+ expect(offset).toBe(9);
+ });
+
+ it("should throw if no markdown is detected", () => {
+ const pythonCode = 'print("Hello, World!")';
+ expect(() =>
+ adapter.transformIn(pythonCode)
+ ).toThrowErrorMatchingInlineSnapshot('"Not supported"');
+ });
+
+ it("should handle an empty string", () => {
+ const pythonCode = 'mo.md("")';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("");
+ expect(offset).toBe(0);
+ });
+
+ it("should unescape code blocks", () => {
+ // f"""
+ const pythonCode = 'mo.md(f"""This is some \\"""content\\"""!""")';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe(`This is some """content"""!`);
+ expect(offset).toBe(10);
+
+ // """
+ const pythonCode2 = 'mo.md("""This is some \\"""content\\"""!""")';
+ const [innerCode2, offset2] = adapter.transformIn(pythonCode2);
+ expect(innerCode2).toBe(`This is some """content"""!`);
+ expect(offset2).toBe(9);
+
+ // "
+ const pythonCode3 = 'mo.md("This is some \\"content\\"!")';
+ const [innerCode3, offset3] = adapter.transformIn(pythonCode3);
+ expect(innerCode3).toBe(`This is some "content"!`);
+ expect(offset3).toBe(7);
+
+ // '
+ const pythonCode4 = "mo.md('This is some \\'content\\'!')";
+ const [innerCode4, offset4] = adapter.transformIn(pythonCode4);
+ expect(innerCode4).toBe(`This is some 'content'!`);
+ expect(offset4).toBe(7);
+ });
+
+ it("should handle strings with escaped quotes", () => {
+ const pythonCode = 'mo.md("""Markdown with an escaped \\"quote\\"""")';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe('Markdown with an escaped \\"quote\\"');
+ expect(offset).toBe('mo.md("""'.length);
+ });
+
+ it("should handle strings with nested markdown", () => {
+ const pythonCode =
+ 'mo.md("""# Title\n\n```python\nprint("Hello, Markdown!")\n```""")';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe(
+ '# Title\n\n```python\nprint("Hello, Markdown!")\n```'
+ );
+ expect(offset).toBe('mo.md("""'.length);
+ });
+
+ it("should return the original string if no markdown delimiters are present", () => {
+ const pythonCode = 'print("No markdown here")';
+ expect(() =>
+ adapter.transformIn(pythonCode)
+ ).toThrowErrorMatchingInlineSnapshot('"Not supported"');
+ });
+
+ it("should handle multiple markdown blocks in a single string", () => {
+ const pythonCode = `mo.md("""
+ # Hello, Markdown!
+ mo.md(
+ '''
+ # Hello, Markdown!
+ Use marimo's "md" function to embed rich text into your marimo
+ '''
+ )
+ """)`;
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe(
+ `# Hello, Markdown!\nmo.md(\n '''\n # Hello, Markdown!\n Use marimo's "md" function to embed rich text into your marimo\n '''\n)`
+ );
+ expect(offset).toBe(18);
+ });
+
+ it("simple markdown", () => {
+ const pythonCode = 'mo.md("# Title without proper delimiters")';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("# Title without proper delimiters");
+ expect(offset).toBe(7);
+ });
+
+ it("should trim strings with leading and trailing whitespace", () => {
+ const pythonCode = 'mo.md(""" \n# Title\nContent\n """)';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("# Title\nContent");
+ expect(offset).toBe(13);
+ });
+
+ it("should handle space around the f=strings", () => {
+ const pythonCode = 'mo.md(\n\t"""\n# Title\nContent\n"""\n)';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("# Title\nContent");
+ expect(offset).toBe(12);
+ });
+
+ it("should dedent indented strings", () => {
+ const pythonCode =
+ 'mo.md(\n\t"""\n\t- item 1\n\t-item 2\n\t-item3\n\t"""\n)';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("- item 1\n-item 2\n-item3");
+ expect(offset).toBe(13);
+ });
+ });
+
+ describe("transformOut", () => {
+ it("should wrap Markdown code with triple double-quoted string format", () => {
+ const code = "# Markdown Title\n\nSome content here.";
+ const [wrappedCode, offset] = adapter.transformOut(code);
+ expect(wrappedCode).toMatchInlineSnapshot(`
+ "mo.md(
+ \\"\\"\\"
+ # Markdown Title
+
+ Some content here.
+ \\"\\"\\"
+ )"
+ `);
+ expect(offset).toBe(16);
+ });
+
+ it("should escape triple quotes in the Markdown code", () => {
+ const code = 'Markdown with an escaped """quote"""!!';
+ const [wrappedCode, offset] = adapter.transformOut(code);
+ expect(wrappedCode).toBe(
+ `mo.md("Markdown with an escaped \\"\\"\\"quote\\"\\"\\"!!")`
+ );
+ expect(offset).toBe(7);
+ });
+
+ it.skip("should upgrade to an f-string if the code contains {}", () => {
+ const code = "Markdown with an {foo} f-string";
+ const [wrappedCode, offset] = adapter.transformOut(code);
+ expect(wrappedCode).toBe(`mo.md(f"Markdown with an {foo} f-string")`);
+ expect(offset).toBe(8);
+ });
+
+ it.skip("should upgrade to an f-string from r-string if the code contains {}", () => {
+ const code = "Markdown with an {foo} f-string";
+ adapter.lastQuotePrefix = "r";
+ const [wrappedCode, offset] = adapter.transformOut(code);
+ expect(wrappedCode).toBe(`mo.md(rf"Markdown with an {foo} f-string")`);
+ expect(offset).toBe(9);
+ });
+
+ it("should not downgrade a f-string", () => {
+ const code = "Normal markdown";
+ adapter.lastQuotePrefix = "f";
+ const [wrappedCode, offset] = adapter.transformOut(code);
+ expect(wrappedCode).toBe('mo.md(f"Normal markdown")');
+ expect(offset).toBe(8);
+ });
+
+ it("should not downgrade a rf-string", () => {
+ const code = "Normal markdown";
+ adapter.lastQuotePrefix = "rf";
+ const [wrappedCode, offset] = adapter.transformOut(code);
+ expect(wrappedCode).toBe('mo.md(rf"Normal markdown")');
+ expect(offset).toBe(9);
+ });
+ });
+
+ describe("isSupported", () => {
+ it("should return true for supported markdown string formats", () => {
+ const pythonCode = 'mo.md("""# Markdown Title\n\nSome content here.""")';
+ expect(adapter.isSupported(pythonCode)).toBe(true);
+ });
+
+ it("should return false for unsupported string formats", () => {
+ const pythonCode = 'print("Hello, World!")';
+ expect(adapter.isSupported(pythonCode)).toBe(false);
+ });
+
+ it("should return false sequences that look like markdown but are not", () => {
+ const once = 'mo.md("""# Markdown Title\n\nSome content here""")';
+ const pythonCode = [once, once].join("\n");
+ expect(adapter.isSupported(pythonCode)).toBe(false);
+ });
+ });
+});
diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.ts
new file mode 100644
index 0000000000..8b6e5681a3
--- /dev/null
+++ b/frontend/src/core/codemirror/language/extension.ts
@@ -0,0 +1,187 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import {
+ Compartment,
+ EditorSelection,
+ StateEffect,
+ StateField,
+} from "@codemirror/state";
+import { LanguageAdapter } from "./types";
+import { PythonLanguageAdapter } from "./python";
+import { EditorView, Panel, keymap, showPanel } from "@codemirror/view";
+import { MarkdownLanguageAdapter } from "./markdown";
+import { clamp } from "@/utils/math";
+import { CompletionConfig } from "@/core/config/config-schema";
+import { completionConfigState } from "../config/extension";
+import { historyCompartment } from "../editing/extensions";
+import { history } from "@codemirror/commands";
+import { formattingChangeEffect } from "../format";
+
+export const LanguageAdapters: Record<
+ LanguageAdapter["type"],
+ () => LanguageAdapter
+> = {
+ python: () => new PythonLanguageAdapter(),
+ markdown: () => new MarkdownLanguageAdapter(),
+};
+
+const LANGUAGES: LanguageAdapter[] = [
+ LanguageAdapters.python(),
+ LanguageAdapters.markdown(),
+];
+
+const languageCompartment = new Compartment();
+
+const setLanguageAdapter = StateEffect.define<LanguageAdapter>();
+
+/**
+ * State field to keep track of the current language adapter.
+ */
+export const languageAdapterState = StateField.define<LanguageAdapter>({
+ create() {
+ return LanguageAdapters.python();
+ },
+ update(value, tr) {
+ for (const effect of tr.effects) {
+ if (effect.is(setLanguageAdapter)) {
+ return effect.value;
+ }
+ }
+ return value;
+ },
+ provide: (field) =>
+ showPanel.from(field, (value) =>
+ value.type === "python" ? null : createLanguagePanel
+ ),
+});
+
+// Keymap to toggle between languages
+function languageToggle(completionConfig: CompletionConfig) {
+ // Cycle through the language to find the next one that supports the code
+ const findNextLanguage = (code: string, index: number): LanguageAdapter => {
+ const language = LANGUAGES[index % LANGUAGES.length];
+ if (language.isSupported(code)) {
+ return language;
+ }
+ return findNextLanguage(code, index + 1);
+ };
+
+ return [
+ keymap.of([
+ {
+ key: "F4",
+ preventDefault: true,
+ run: (cm) => {
+ // Find the next language
+ const currentLanguage = cm.state.field(languageAdapterState);
+ const currentLanguageIndex = LANGUAGES.findIndex(
+ (l) => l.type === currentLanguage.type
+ );
+ const code = cm.state.doc.toString();
+ const nextLanguage = findNextLanguage(code, currentLanguageIndex + 1);
+
+ if (currentLanguage === nextLanguage) {
+ return false;
+ }
+
+ updateLanguageAdapterAndCode(cm, nextLanguage);
+ return true;
+ },
+ },
+ ]),
+ ];
+}
+
+function updateLanguageAdapterAndCode(
+ view: EditorView,
+ nextLanguage: LanguageAdapter
+) {
+ const currentLanguage = view.state.field(languageAdapterState);
+ const code = view.state.doc.toString();
+ const completionConfig = view.state.facet(completionConfigState);
+
+ // Update the code
+ const [codeOut, cursorDiff1] = currentLanguage.transformOut(code);
+ const [newCode, cursorDiff2] = nextLanguage.transformIn(codeOut);
+
+ // Update the cursor position
+ let cursor = view.state.selection.main.head;
+ cursor += cursorDiff1;
+ cursor -= cursorDiff2;
+ cursor = clamp(cursor, 0, newCode.length);
+
+ // Update the state
+ view.dispatch({
+ effects: [
+ setLanguageAdapter.of(nextLanguage),
+ languageCompartment.reconfigure(
+ nextLanguage.getExtension(completionConfig)
+ ),
+ // Clear history
+ historyCompartment.reconfigure([]),
+ // Let downstream extensions know that this is a formatting change
+ formattingChangeEffect.of(true),
+ ],
+ changes: {
+ from: 0,
+ to: view.state.doc.length,
+ insert: newCode,
+ },
+ selection: EditorSelection.cursor(cursor),
+ });
+
+ // Add history back
+ view.dispatch({
+ effects: [historyCompartment.reconfigure([history()])],
+ });
+}
+
+function createLanguagePanel(view: EditorView): Panel {
+ const dom = document.createElement("div");
+ dom.textContent = view.state.field(languageAdapterState).type;
+ dom.style.padding = "0.2rem 0.5rem";
+ dom.style.display = "flex";
+ dom.style.justifyContent = "flex-end";
+ return {
+ dom,
+ update(update) {
+ dom.textContent = update.state.field(languageAdapterState).type;
+ },
+ };
+}
+
+/**
+ * Set of extensions to enable adaptive language configuration.
+ */
+export function adaptiveLanguageConfiguration(
+ completionConfig: CompletionConfig
+) {
+ return [
+ completionConfigState.of(completionConfig),
+ languageToggle(completionConfig),
+ languageCompartment.of(
+ LanguageAdapters.python().getExtension(completionConfig)
+ ),
+ languageAdapterState,
+ ];
+}
+
+/**
+ * Switch the language of the editor.
+ */
+export function switchLanguage(
+ view: EditorView,
+ language: LanguageAdapter["type"]
+) {
+ const newLanguage = LanguageAdapters[language];
+ updateLanguageAdapterAndCode(view, newLanguage());
+}
+
+export function reconfigureLanguageEffect(
+ view: EditorView,
+ completionConfig: CompletionConfig
+) {
+ const language = view.state.field(languageAdapterState);
+ return languageCompartment.reconfigure(
+ language.getExtension(completionConfig)
+ );
+}
diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.ts
new file mode 100644
index 0000000000..7eacc8305c
--- /dev/null
+++ b/frontend/src/core/codemirror/language/markdown.ts
@@ -0,0 +1,180 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { Extension } from "@codemirror/state";
+import { LanguageAdapter } from "./types";
+import { markdown } from "@codemirror/lang-markdown";
+import { languages } from "@codemirror/language-data";
+import { parseMixed } from "@lezer/common";
+import { python, pythonLanguage } from "@codemirror/lang-python";
+import dedent from "dedent";
+import { logNever } from "@/utils/assertNever";
+
+const prefixKinds = ["", "f", "r", "fr", "rf"] as const;
+type PrefixKind = (typeof prefixKinds)[number];
+
+const quoteKinds = [
+ ['"""', '"""'],
+ ["'''", "'''"],
+ ['"', '"'],
+ ["'", "'"],
+];
+// explode into all combinations
+const pairs = prefixKinds.flatMap((prefix) =>
+ quoteKinds.map(([start, end]) => [prefix + start, end])
+);
+
+const regexes = pairs.map(
+ ([start, end]) =>
+ // mo.md( + any number of spaces + start + capture + any number of spaces + end)
+ [
+ start,
+ new RegExp(`^mo\\.md\\(\\s*${start}(.*)${end}\\s*\\)$`, "s"),
+ ] as const
+);
+
+/**
+ * Language adapter for Markdown.
+ */
+export class MarkdownLanguageAdapter implements LanguageAdapter {
+ type = "markdown" as const;
+
+ lastQuotePrefix: PrefixKind = "";
+
+ transformIn(pythonCode: string): [string, number] {
+ if (!this.isSupported(pythonCode)) {
+ throw new Error("Not supported");
+ }
+
+ for (const [start, regex] of regexes) {
+ const match = pythonCode.match(regex);
+ if (match) {
+ const innerCode = match[1].trim();
+
+ const [quotePrefix, quoteType] = splitQuotePrefix(start);
+ // store the quote prefix for later when we transform out
+ this.lastQuotePrefix = quotePrefix;
+ const unescapedCode = innerCode.replaceAll(`\\${quoteType}`, quoteType);
+
+ const offset = pythonCode.indexOf(innerCode);
+ return [dedent(unescapedCode), offset];
+ }
+ }
+
+ return [pythonCode, 0];
+ }
+
+ transformOut(code: string): [string, number] {
+ // Get the quote type from the last transformIn
+ // const prefix = upgradePrefixKind(this.lastQuotePrefix, code);
+ const prefix = this.lastQuotePrefix;
+
+ const isOneLine = !code.includes("\n");
+ if (isOneLine) {
+ const escapedCode = code.replaceAll('"', '\\"');
+ const start = `mo.md(${prefix}"`;
+ const end = `")`;
+ return [start + escapedCode + end, start.length];
+ }
+
+ // Multiline code
+ const start = `mo.md(\n ${prefix}"""\n`;
+ const escapedCode = code.replaceAll('"""', '\\"""');
+ const end = `\n """\n)`;
+ return [start + indentOneTab(escapedCode) + end, start.length + 1];
+ }
+
+ isSupported(pythonCode: string): boolean {
+ const markdownLines = pythonCode
+ .split("\n")
+ .map((line) => line.startsWith("mo.md("))
+ .filter(Boolean);
+ if (markdownLines.length > 1) {
+ // more than line starting with mo.md(; as a heuristic,
+ // don't show "view as markdown"
+ return false;
+ }
+ return regexes.some(([, regex]) => regex.test(pythonCode));
+ }
+
+ getExtension(): Extension {
+ return [
+ markdown({
+ codeLanguages: languages,
+ extensions: [
+ // Wrapper extension to handle f-string substitutions
+ {
+ wrap: parseMixed((node, input) => {
+ const text = input.read(node.from, node.to);
+ const overlays: Array<{ from: number; to: number }> = [];
+
+ // Find all { } groupings
+ const pattern = /{(.*?)}/g;
+ let match;
+
+ while ((match = pattern.exec(text)) !== null) {
+ const start = match.index + 1;
+ const end = pattern.lastIndex - 1;
+ overlays.push({ from: start, to: end });
+ }
+
+ if (overlays.length === 0) {
+ return null;
+ }
+
+ return {
+ parser: pythonLanguage.parser,
+ overlays,
+ };
+ }),
+ },
+ ],
+ }),
+ python().support,
+ ];
+ }
+}
+
+// Remove the f, r, fr, rf prefixes from the quote
+function splitQuotePrefix(quote: string): [PrefixKind, string] {
+ // start with the longest prefix
+ const prefixKindsByLength = [...prefixKinds].sort(
+ (a, b) => b.length - a.length
+ );
+ for (const prefix of prefixKindsByLength) {
+ if (quote.startsWith(prefix)) {
+ return [prefix, quote.slice(prefix.length)];
+ }
+ }
+ return ["", quote];
+}
+
+export function upgradePrefixKind(kind: PrefixKind, code: string): PrefixKind {
+ const containsSubstitution = code.includes("{") && code.includes("}");
+
+ // If there is no substitution, keep the same prefix
+ if (!containsSubstitution) {
+ return kind;
+ }
+
+ // If there is a substitution, upgrade to an f-string
+ switch (kind) {
+ case "":
+ return "f";
+ case "r":
+ return "rf";
+ case "f":
+ case "rf":
+ case "fr":
+ return kind;
+ default:
+ logNever(kind);
+ return "f";
+ }
+}
+
+// Indent each line by one tab
+function indentOneTab(code: string): string {
+ return code
+ .split("\n")
+ .map((line) => (line.trim() === "" ? line : ` ${line}`))
+ .join("\n");
+}
diff --git a/frontend/src/core/codemirror/language/python.ts b/frontend/src/core/codemirror/language/python.ts
new file mode 100644
index 0000000000..4f85a0f2ea
--- /dev/null
+++ b/frontend/src/core/codemirror/language/python.ts
@@ -0,0 +1,68 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { Extension } from "@codemirror/state";
+import { LanguageAdapter } from "./types";
+import {
+ pythonLanguage,
+ localCompletionSource,
+ globalCompletion,
+} from "@codemirror/lang-python";
+import {
+ foldNodeProp,
+ foldInside,
+ LanguageSupport,
+} from "@codemirror/language";
+import { CompletionConfig } from "@/core/config/config-schema";
+import { autocompletion } from "@codemirror/autocomplete";
+import { completer } from "../completion/completer";
+
+/**
+ * Language adapter for Python.
+ */
+export class PythonLanguageAdapter implements LanguageAdapter {
+ type = "python" as const;
+
+ transformIn(code: string): [string, number] {
+ return [code, 0];
+ }
+
+ transformOut(code: string): [string, number] {
+ return [code, 0];
+ }
+
+ isSupported(_code: string): boolean {
+ return true;
+ }
+
+ getExtension(completionConfig: CompletionConfig): Extension {
+ return [
+ // Whether or not to require keypress to activate autocompletion (default
+ // keymap is Ctrl+Space)
+ autocompletion({
+ activateOnTyping: completionConfig.activate_on_typing,
+ // The Cell component handles the blur event. `closeOnBlur` is too
+ // aggressive and doesn't let the user click into the completion info
+ // element (which contains the docstring/type --- users might want to
+ // copy paste from the docstring). The main issue is that the completion
+ // tooltip is not part of the editable DOM tree:
+ // https://discuss.codemirror.net/t/adding-click-event-listener-to-autocomplete-tooltip-info-panel-is-not-working/4741
+ closeOnBlur: false,
+ override: [completer],
+ }),
+ new LanguageSupport(customizedPython, [
+ customizedPython.data.of({ autocomplete: localCompletionSource }),
+ customizedPython.data.of({ autocomplete: globalCompletion }),
+ ]),
+ ];
+ }
+}
+
+// Customize python to support folding some additional syntax nodes
+const customizedPython = pythonLanguage.configure({
+ props: [
+ foldNodeProp.add({
+ ParenthesizedExpression: foldInside,
+ // Fold function calls whose arguments are split over multiple lines
+ ArgList: foldInside,
+ }),
+ ],
+});
diff --git a/frontend/src/core/codemirror/language/types.ts b/frontend/src/core/codemirror/language/types.ts
new file mode 100644
index 0000000000..786930f133
--- /dev/null
+++ b/frontend/src/core/codemirror/language/types.ts
@@ -0,0 +1,16 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { CompletionConfig } from "@/core/config/config-schema";
+import { Extension } from "@codemirror/state";
+
+/**
+ * A language adapter is a class that can transform code from one language to
+ * another. For example, a Markdown language adapter can make it feel like
+ * you're writing Markdown, but it will actually be transformed into Python.
+ */
+export interface LanguageAdapter {
+ type: "python" | "markdown";
+ transformIn(code: string): [string, number];
+ transformOut(code: string): [string, number];
+ isSupported(code: string): boolean;
+ getExtension(completionConfig: CompletionConfig): Extension;
+}
diff --git a/frontend/src/core/codemirror/language/utils.ts b/frontend/src/core/codemirror/language/utils.ts
new file mode 100644
index 0000000000..6d534c0d30
--- /dev/null
+++ b/frontend/src/core/codemirror/language/utils.ts
@@ -0,0 +1,28 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { EditorView } from "@codemirror/view";
+import { languageAdapterState } from "./extension";
+
+/**
+ * Get the editor code as Python
+ * Handles when the editor has a different language adapter
+ */
+export function getEditorCodeAsPython(editor: EditorView): string {
+ const languageAdapter = editor.state.field(languageAdapterState);
+ return languageAdapter.transformOut(editor.state.doc.toString())[0];
+}
+
+export function updateEditorCodeFromPython(
+ editor: EditorView,
+ pythonCode: string
+) {
+ const languageAdapter = editor.state.field(languageAdapterState);
+ const [code] = languageAdapter.transformIn(pythonCode);
+ editor.dispatch({
+ changes: {
+ from: 0,
+ to: editor.state.doc.length,
+ insert: code,
+ },
+ });
+ return code;
+}
diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.ts
index fdf27371da..3524b31086 100644
--- a/frontend/src/core/hotkeys/hotkeys.ts
+++ b/frontend/src/core/hotkeys/hotkeys.ts
@@ -216,6 +216,11 @@ const DEFAULT_HOT_KEY = {
group: "Editing",
key: "Mod-Shift-b",
},
+ "global.toggleLanguage": {
+ name: "Toggle language to markdown (if supported)",
+ group: "Editing",
+ key: "F4",
+ },
// Global Navigation
"global.focusTop": {
diff --git a/frontend/src/css/codemirror.css b/frontend/src/css/codemirror.css
index 60fc7f0550..61fb360b0e 100644
--- a/frontend/src/css/codemirror.css
+++ b/frontend/src/css/codemirror.css
@@ -168,3 +168,13 @@
.cm .cm-completionIcon-keyword::after {
content: "κ";
}
+
+/* -- Panels -- */
+
+.cm .cm-panels {
+ background: transparent;
+ color: var(--sky-11);
+ font-weight: 700;
+
+ @apply text-xs;
+}