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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: latex syntax highlighting (#4346)
Myles Scolnick1dcaac15c5c9
diff --git a/frontend/package.json b/frontend/package.jsonindex bd2f4bb370..f5af35f7c6 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -21,6 +21,7 @@"@codemirror/lang-sql": "^6.8.0","@codemirror/language": "^6.10.8","@codemirror/language-data": "^6.5.1",+ "@codemirror/legacy-modes": "^6.5.0","@codemirror/lint": "^6.8.4","@codemirror/search": "^6.5.10","@codemirror/state": "^6.5.2",@@ -39,6 +40,7 @@"@lezer/common": "^1.2.3","@lezer/highlight": "^1.2.1","@lezer/lr": "^1.4.2",+ "@lezer/markdown": "^1.4.2","@lezer/python": "^1.1.16","@marimo-team/codemirror-ai": "^0.1.11","@marimo-team/codemirror-languageserver": "^1.15.6",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 1783b8fcfc..f2dcb81229 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -39,6 +39,9 @@ importers:'@codemirror/language-data':specifier: ^6.5.1version: 6.5.1+ '@codemirror/legacy-modes':+ specifier: ^6.5.0+ version: 6.5.0'@codemirror/lint':specifier: ^6.8.4version: 6.8.5@@ -93,6 +96,9 @@ importers:'@lezer/lr':specifier: ^1.4.2version: 1.4.2+ '@lezer/markdown':+ specifier: ^1.4.2+ version: 1.4.2'@lezer/python':specifier: ^1.1.16version: 1.1.16@@ -224,7 +230,7 @@ importers:'@uiw/codemirror-extensions-langs':specifier: ^4.23.10- version: 4.23.10(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])+ version: 4.23.10(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])'@uiw/react-codemirror':specifier: ^4.23.10version: 4.23.10(@babel/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -1009,8 +1015,8 @@ packages:'@codemirror/[email protected]':resolution: {integrity: sha512-A7+f++LodNNc1wGgoRDTt78cOwWm9KVezApgjOMp1W4hM0898nsqBXwF+sbePE7ZRcjN7Sa1Z5m2oN27XkmEjQ==}- '@codemirror/[email protected]':- resolution: {integrity: sha512-vdg3XY7OAs5uLDx2Iw+cGfnwtd7kM+Et/eMsqAGTfT/JKiVBQZXosTzjEbWAi/FrY6DcQIz8mQjBozFHZEUWQA==}+ '@codemirror/[email protected]':+ resolution: {integrity: sha512-dNw5pwTqtR1giYjaJyEajunLqxGavZqV0XRtVZyMJnNOD2HmK9DMUmuCAr6RMFGRJ4l8OeQDjpI/us+R09mQsw==}'@codemirror/[email protected]':resolution: {integrity: sha512-s3n3KisH7dx3vsoeGMxsbRAgKe4O1vbrnKBClm99PU0fWxmxsx5rR2PfqQgIt+2MMJBHbiJ5rfIdLYfB9NNvsA==}@@ -1492,8 +1498,8 @@ packages:'@lezer/[email protected]':resolution: {integrity: sha512-pu0K1jCIdnQ12aWNaAVU5bzi7Bd1w54J3ECgANPmYLtQKP0HBj2cE/5coBD66MT10xbtIuUr7tg0Shbsvk0mDA==}- '@lezer/[email protected]':- resolution: {integrity: sha512-kmxvLnXCogUx2mexslWwVME1W2GQP76pwUODcFXLsuubuK41TcEJhKRm2FTKugNfEkUIspJNq9+jNo6b7dxVLA==}+ '@lezer/[email protected]':+ resolution: {integrity: sha512-iYewCigG/517D0xJPQd7RGaCjZAFwROiH8T9h7OTtz0bRVtkxzFhGBFJ9JGKgBBs4uuo1cvxzyQ5iKhDLMcLUQ==}'@lezer/[email protected]':resolution: {integrity: sha512-aqdCQJOXJ66De22vzdwnuC502hIaG9EnPK2rSi+ebXyUd+j7GAX1mRjWZOVOmf3GST1YUfUCu6WXDiEgDGOVwA==}@@ -9649,7 +9655,7 @@ snapshots:'@codemirror/state': 6.5.2'@codemirror/view': 6.36.5'@lezer/common': 1.2.3- '@lezer/markdown': 1.1.1+ '@lezer/markdown': 1.4.2'@codemirror/[email protected]':dependencies:@@ -9743,7 +9749,7 @@ snapshots:'@codemirror/lang-xml': 6.0.2'@codemirror/lang-yaml': 6.0.0'@codemirror/language': 6.11.0- '@codemirror/legacy-modes': 6.4.1+ '@codemirror/legacy-modes': 6.5.0'@codemirror/[email protected]':dependencies:@@ -9754,7 +9760,7 @@ snapshots:'@lezer/lr': 1.4.2style-mod: 4.1.2- '@codemirror/[email protected]':+ '@codemirror/[email protected]':dependencies:'@codemirror/language': 6.11.0@@ -10262,7 +10268,7 @@ snapshots:dependencies:'@lezer/common': 1.2.3- '@lezer/[email protected]':+ '@lezer/[email protected]':dependencies:'@lezer/common': 1.2.3'@lezer/highlight': 1.2.1@@ -13261,7 +13267,7 @@ snapshots:'@codemirror/state': 6.5.2'@codemirror/view': 6.36.5- '@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':+ '@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':dependencies:'@codemirror/lang-angular': 0.1.2'@codemirror/lang-cpp': 6.0.2@@ -13283,7 +13289,7 @@ snapshots:'@codemirror/lang-wast': 6.0.1'@codemirror/lang-xml': 6.0.2'@codemirror/language-data': 6.5.1- '@codemirror/legacy-modes': 6.4.1+ '@codemirror/legacy-modes': 6.5.0'@nextjournal/lang-clojure': 1.0.0'@replit/codemirror-lang-csharp': 6.2.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])'@replit/codemirror-lang-nix': 6.0.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])diff --git a/frontend/src/core/codemirror/language/latex.ts b/frontend/src/core/codemirror/language/latex.tsnew file mode 100644index 0000000000..87f1d06bac--- /dev/null+++ b/frontend/src/core/codemirror/language/latex.ts@@ -0,0 +1,249 @@+/* Copyright 2024 Marimo. All rights reserved. */++// This file has been adapted from https://github.com/jupyterlab/jupyterlab/blob/0dbe74708be66cb9ac423c0fb47c66418c037a8f/packages/codemirror/src/extensions/ipython-md.ts+// Copyright (c) 2015-2025 Project Jupyter Contributors+// All rights reserved.++// Redistribution and use in source and binary forms, with or without+// modification, are permitted provided that the following conditions are met:++// 1. Redistributions of source code must retain the above copyright notice, this+// list of conditions and the following disclaimer.++// 2. Redistributions in binary form must reproduce the above copyright notice,+// this list of conditions and the following disclaimer in the documentation+// and/or other materials provided with the distribution.++// 3. Neither the name of the copyright holder nor the names of its+// contributors may be used to endorse or promote products derived from+// this software without specific prior written permission.++// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++import { parseMixed, type Parser } from "@lezer/common";+import { tags } from "@lezer/highlight";+import type {+ DelimiterType,+ InlineContext,+ MarkdownConfig,+ NodeSpec,+} from "@lezer/markdown";++// Mathematical expression delimiters+const INLINE_MATH_DOLLAR = "InlineMathDollar";+const INLINE_MATH_BRACKET = "InlineMathBracket";+const BLOCK_MATH_DOLLAR = "BlockMathDollar";+const BLOCK_MATH_BRACKET = "BlockMathBracket";++/**+ * Length of the delimiter for a math expression+ */+const DELIMITER_LENGTH: Record<string, number> = {+ [INLINE_MATH_DOLLAR]: 1,+ [INLINE_MATH_BRACKET]: 3,+ [BLOCK_MATH_DOLLAR]: 2,+ [BLOCK_MATH_BRACKET]: 3,+};++const CHARS_CODES = {+ DOLLAR: 36, // $+ BACKSLASH: 92, // \+ OPEN_PAREN: 40, // (+ CLOSE_PAREN: 41, // )+ OPEN_BRACKET: 91, // [+ CLOSE_BRACKET: 93, // ]+};++/**+ * Delimiters for math expressions+ */+// Delimiters must be defined as constant because they are used in object match tests+const DELIMITERS = Object.keys(DELIMITER_LENGTH).reduce<+ Record<string, DelimiterType>+>((agg, name) => {+ agg[name] = { mark: `${name}Mark`, resolve: name };+ return agg;+}, {});++/**+ * Define a LaTeX mathematical expression parser for Markdown.+ *+ * @param latexParser CodeMirror {@link Parser} for LaTeX mathematical expression+ * @returns Markdown extension+ */+export function parseLatex(latexParser: Parser): MarkdownConfig {+ const defineNodes = new Array<NodeSpec>();+ Object.keys(DELIMITER_LENGTH).forEach((name) => {+ defineNodes.push(+ {+ name,+ style: tags.emphasis,+ },+ { name: `${name}Mark`, style: tags.processingInstruction },+ );+ });+ return {+ defineNodes,+ parseInline: [+ {+ name: BLOCK_MATH_DOLLAR,+ parse(cx: InlineContext, next: number, pos: number): number {+ if (+ next !== CHARS_CODES.DOLLAR ||+ cx.char(pos + 1) !== CHARS_CODES.DOLLAR+ ) {+ return -1;+ }++ return cx.addDelimiter(+ DELIMITERS[BLOCK_MATH_DOLLAR],+ pos,+ pos + DELIMITER_LENGTH[BLOCK_MATH_DOLLAR],+ true,+ true,+ );+ },+ },+ {+ name: INLINE_MATH_DOLLAR,+ parse(cx: InlineContext, next: number, pos: number): number {+ if (+ next !== CHARS_CODES.DOLLAR ||+ cx.char(pos + 1) === CHARS_CODES.DOLLAR+ ) {+ return -1;+ }++ return cx.addDelimiter(+ DELIMITERS[INLINE_MATH_DOLLAR],+ pos,+ pos + DELIMITER_LENGTH[INLINE_MATH_DOLLAR],+ true,+ true,+ );+ },+ },+ // Inline expression wrapped in \\( ... \\)+ {+ name: INLINE_MATH_BRACKET,+ before: "Escape", // Search for this delimiter before the escape character+ parse(cx: InlineContext, next: number, pos: number): number {+ if (+ next !== CHARS_CODES.BACKSLASH ||+ cx.char(pos + 1) !== CHARS_CODES.BACKSLASH ||+ ![CHARS_CODES.OPEN_PAREN, CHARS_CODES.CLOSE_PAREN].includes(+ cx.char(pos + 2),+ )+ ) {+ return -1;+ }++ return cx.addDelimiter(+ DELIMITERS[INLINE_MATH_BRACKET],+ pos,+ pos + DELIMITER_LENGTH[INLINE_MATH_BRACKET],+ cx.char(pos + 2) === CHARS_CODES.OPEN_PAREN,+ cx.char(pos + 2) === CHARS_CODES.CLOSE_PAREN,+ );+ },+ },+ // Block expression wrapped in \\[ ... \\]+ {+ name: BLOCK_MATH_BRACKET,+ before: "Escape", // Search for this delimiter before the escape character+ parse(cx: InlineContext, next: number, pos: number): number {+ if (+ next !== CHARS_CODES.BACKSLASH ||+ cx.char(pos + 1) !== CHARS_CODES.BACKSLASH ||+ ![CHARS_CODES.OPEN_BRACKET, CHARS_CODES.CLOSE_BRACKET].includes(+ cx.char(pos + 2),+ )+ ) {+ return -1;+ }++ return cx.addDelimiter(+ DELIMITERS[BLOCK_MATH_BRACKET],+ pos,+ pos + DELIMITER_LENGTH[BLOCK_MATH_BRACKET],+ cx.char(pos + 2) === CHARS_CODES.OPEN_BRACKET,+ cx.char(pos + 2) === CHARS_CODES.CLOSE_BRACKET,+ );+ },+ },+ // Inline expression wrapped in \( ... \)+ {+ name: INLINE_MATH_BRACKET,+ before: "Escape",+ parse(cx: InlineContext, next: number, pos: number): number {+ if (+ next !== CHARS_CODES.BACKSLASH ||+ ![CHARS_CODES.OPEN_PAREN, CHARS_CODES.CLOSE_PAREN].includes(+ cx.char(pos + 1),+ )+ ) {+ return -1;+ }++ return cx.addDelimiter(+ DELIMITERS[INLINE_MATH_BRACKET],+ pos,+ pos + 2, // Length of \( or \)+ cx.char(pos + 1) === CHARS_CODES.OPEN_PAREN,+ cx.char(pos + 1) === CHARS_CODES.CLOSE_PAREN,+ );+ },+ },+ // Block expression wrapped in \[ ... \]+ {+ name: BLOCK_MATH_BRACKET,+ before: "Escape",+ parse(cx: InlineContext, next: number, pos: number): number {+ if (+ next !== CHARS_CODES.BACKSLASH ||+ ![CHARS_CODES.OPEN_BRACKET, CHARS_CODES.CLOSE_BRACKET].includes(+ cx.char(pos + 1),+ )+ ) {+ return -1;+ }++ return cx.addDelimiter(+ DELIMITERS[BLOCK_MATH_BRACKET],+ pos,+ pos + 2, // Length of \[ or \]+ cx.char(pos + 1) === CHARS_CODES.OPEN_BRACKET,+ cx.char(pos + 1) === CHARS_CODES.CLOSE_BRACKET,+ );+ },+ },+ ],+ wrap: parseMixed((node) => {+ // Test if the node type is one of the math expression+ const delimiterLength = DELIMITER_LENGTH[node.type.name];+ if (delimiterLength) {+ return {+ parser: latexParser,+ // Remove delimiter from LaTeX parser otherwise it won't be highlighted+ overlay: [+ {+ from: node.from + delimiterLength,+ to: node.to - delimiterLength,+ },+ ],+ };+ }++ return null;+ }),+ };+}diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.tsindex f1034797e3..7a48e36abd 100644--- a/frontend/src/core/codemirror/language/markdown.ts+++ b/frontend/src/core/codemirror/language/markdown.ts@@ -1,18 +1,18 @@/* Copyright 2024 Marimo. All rights reserved. */import type { Extension } from "@codemirror/state";import type { LanguageAdapter } from "./types";-import { markdown } from "@codemirror/lang-markdown";-import { languages } from "@codemirror/language-data";-import { parseMixed } from "@lezer/common";+import { markdown, markdownLanguage } from "@codemirror/lang-markdown";import { python, pythonLanguage } from "@codemirror/lang-python";+import { languages } from "@codemirror/language-data";+import { stexMath } from "@codemirror/legacy-modes/mode/stex";// @ts-expect-error: no declaration fileimport dedent from "string-dedent";import {+ autocompletion,type Completion,type CompletionContext,type CompletionResult,type CompletionSource,- autocompletion,} from "@codemirror/autocomplete";import { once } from "lodash-es";import { enhancedMarkdownExtension } from "../markdown/extension";@@ -23,6 +23,9 @@ import { type QuotePrefixKind, splitQuotePrefix } from "./utils/quotes";import { markdownAutoRunExtension } from "../cells/extensions";import type { PlaceholderType } from "../config/extension";import type { CellId } from "@/core/cells/ids";+import { parseMixed } from "@lezer/common";+import { parseLatex } from "./latex";+import { StreamLanguage } from "@codemirror/language";const quoteKinds = [['"""', '"""'],@@ -166,8 +169,10 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {): Extension[] {return [markdown({+ base: markdownLanguage,codeLanguages: languages,extensions: [+ parseLatex(StreamLanguage.define(stexMath).parser),// Wrapper extension to handle f-string substitutions{wrap: parseMixed((node, input) => {diff --git a/marimo/_smoke_tests/markdown/latex_highlighting.py b/marimo/_smoke_tests/markdown/latex_highlighting.pynew file mode 100644index 0000000000..81c8a2c5a1--- /dev/null+++ b/marimo/_smoke_tests/markdown/latex_highlighting.py@@ -0,0 +1,52 @@+import marimo++__generated_with = "0.11.31"+app = marimo.App(width="medium")+++def _(mo):+ mo.md(+ """+ ## Markdown / Latex Highlighting++ ```ts+ console.log("highlight code fences")+ ```++ ```python+ def lang_python():+ pass+ ```++ ```+ def no_language():+ pass+ ```++ **bold**++ _italic_++ $\sigma\sqrt{100}$++ $$+ \sigma\sqrt{100}+ $$++ \[ \sigma\sqrt{100} \]++ \( \sigma\sqrt{100} \)+ """+ )+ return+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()