diff --git a/dist/render.js b/dist/render.js index d50d626..1ee30a5 100644 --- a/dist/render.js +++ b/dist/render.js @@ -4,6 +4,7 @@ import stripAnsi from "strip-ansi"; import { hyperlinkSupported, osc8 } from "./hyperlink.js"; import { parse } from "./parser.js"; import { convertLatexToUnicode } from "./latex.js"; +import { renderDisplayLatex } from "./txm.js"; import { createStyler, themes } from "./theme.js"; import { visibleWidth, wrapText, wrapWithPrefix } from "./wrap.js"; function dedent(markdown) { @@ -461,8 +462,8 @@ function renderCodeBlock(node, ctx) { return [`${top}\n${boxLines.join("\n")}\n${bottom}\n\n`]; } function renderDisplayMath(node, ctx) { - const converted = convertLatexToUnicode(node.value); - const styled = ctx.style(converted, ctx.options.theme.math || ctx.options.theme.inlineCode); + const rendered = renderDisplayLatex(node.value); + const styled = ctx.style(rendered, ctx.options.theme.math || ctx.options.theme.inlineCode); const lines = styled.split("\n"); return [`\n${lines.map((l) => ` ${l}`).join("\n")}\n`]; } diff --git a/dist/txm-wasm/package.json b/dist/txm-wasm/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/dist/txm-wasm/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/dist/txm-wasm/txm.d.ts b/dist/txm-wasm/txm.d.ts new file mode 100644 index 0000000..b9b5a16 --- /dev/null +++ b/dist/txm-wasm/txm.d.ts @@ -0,0 +1,4 @@ +/* tslint:disable */ +/* eslint-disable */ + +export function render_latex(latex: string): string; diff --git a/dist/txm-wasm/txm.js b/dist/txm-wasm/txm.js new file mode 100644 index 0000000..7775be4 --- /dev/null +++ b/dist/txm-wasm/txm.js @@ -0,0 +1,134 @@ +/* @ts-self-types="./txm.d.ts" */ + +/** + * @param {string} latex + * @returns {string} + */ +function render_latex(latex) { + let deferred3_0; + let deferred3_1; + try { + const ptr0 = passStringToWasm0(latex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.render_latex(ptr0, len0); + var ptr2 = ret[0]; + var len2 = ret[1]; + if (ret[3]) { + ptr2 = 0; len2 = 0; + throw takeFromExternrefTable0(ret[2]); + } + deferred3_0 = ptr2; + deferred3_1 = len2; + return getStringFromWasm0(ptr2, len2); + } finally { + wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); + } +} +exports.render_latex = render_latex; + +function __wbg_get_imports() { + const import0 = { + __proto__: null, + __wbindgen_cast_0000000000000001: function(arg0, arg1) { + // Cast intrinsic for `Ref(String) -> Externref`. + const ret = getStringFromWasm0(arg0, arg1); + return ret; + }, + __wbindgen_init_externref_table: function() { + const table = wasm.__wbindgen_externrefs; + const offset = table.grow(4); + table.set(0, undefined); + table.set(offset + 0, undefined); + table.set(offset + 1, null); + table.set(offset + 2, true); + table.set(offset + 3, false); + }, + }; + return { + __proto__: null, + "./txm_bg.js": import0, + }; +} + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return decodeText(ptr, len); +} + +let cachedUint8ArrayMemory0 = null; +function getUint8ArrayMemory0() { + if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; +} + +function passStringToWasm0(arg, malloc, realloc) { + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = cachedTextEncoder.encodeInto(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +function takeFromExternrefTable0(idx) { + const value = wasm.__wbindgen_externrefs.get(idx); + wasm.__externref_table_dealloc(idx); + return value; +} + +let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); +cachedTextDecoder.decode(); +function decodeText(ptr, len) { + return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); +} + +const cachedTextEncoder = new TextEncoder(); + +if (!('encodeInto' in cachedTextEncoder)) { + cachedTextEncoder.encodeInto = function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; + }; +} + +let WASM_VECTOR_LEN = 0; + +const wasmPath = `${__dirname}/txm_bg.wasm`; +const wasmBytes = require('fs').readFileSync(wasmPath); +const wasmModule = new WebAssembly.Module(wasmBytes); +let wasm = new WebAssembly.Instance(wasmModule, __wbg_get_imports()).exports; +wasm.__wbindgen_start(); diff --git a/dist/txm-wasm/txm_bg.wasm b/dist/txm-wasm/txm_bg.wasm new file mode 100644 index 0000000..aaec9ac Binary files /dev/null and b/dist/txm-wasm/txm_bg.wasm differ diff --git a/dist/txm-wasm/txm_bg.wasm.d.ts b/dist/txm-wasm/txm_bg.wasm.d.ts new file mode 100644 index 0000000..2d0b227 --- /dev/null +++ b/dist/txm-wasm/txm_bg.wasm.d.ts @@ -0,0 +1,10 @@ +/* tslint:disable */ +/* eslint-disable */ +export const memory: WebAssembly.Memory; +export const render_latex: (a: number, b: number) => [number, number, number, number]; +export const __wbindgen_externrefs: WebAssembly.Table; +export const __wbindgen_malloc: (a: number, b: number) => number; +export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number; +export const __externref_table_dealloc: (a: number) => void; +export const __wbindgen_free: (a: number, b: number, c: number) => void; +export const __wbindgen_start: () => void; diff --git a/dist/txm.d.ts b/dist/txm.d.ts new file mode 100644 index 0000000..49ed953 --- /dev/null +++ b/dist/txm.d.ts @@ -0,0 +1 @@ +export declare function renderDisplayLatex(latex: string): string; diff --git a/dist/txm.js b/dist/txm.js new file mode 100644 index 0000000..7029138 --- /dev/null +++ b/dist/txm.js @@ -0,0 +1,17 @@ +import { createRequire } from "node:module"; +import { convertLatexToUnicode } from "./latex.js"; +const require = createRequire(import.meta.url); +const txm = require("./txm-wasm/txm.js"); +export function renderDisplayLatex(latex) { + try { + return txm + .render_latex(latex) + .trimEnd() + .split("\n") + .map((line) => line.trimEnd()) + .join("\n"); + } + catch { + return convertLatexToUnicode(latex); + } +} diff --git a/package.json b/package.json index ddd6cae..ea96617 100644 --- a/package.json +++ b/package.json @@ -46,14 +46,14 @@ "scripts": { "build": "pnpm lint && pnpm typecheck && pnpm test && pnpm compile", "clean": "rm -rf dist", - "format": "oxfmt --write .", - "format:check": "oxfmt --check .", + "format": "oxfmt --write src/*.ts test scripts package.json", + "format:check": "oxfmt --check src/*.ts test scripts package.json", "lint": "rm -rf dist coverage && pnpm format:check && oxlint --deny-warnings src test", "test": "vitest run", "test:coverage": "vitest run --coverage", "typecheck": "tsc -p tsconfig.json --noEmit", "types": "tsc -p tsconfig.json --emitDeclarationOnly", - "compile": "tsc -p tsconfig.json", + "compile": "tsc -p tsconfig.json && node scripts/copy-txm-wasm.mjs", "markdansi": "tsx src/cli.ts", "release": "node scripts/release.mjs" }, diff --git a/scripts/copy-txm-wasm.mjs b/scripts/copy-txm-wasm.mjs new file mode 100644 index 0000000..27861a7 --- /dev/null +++ b/scripts/copy-txm-wasm.mjs @@ -0,0 +1,9 @@ +import { cp } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +await cp(path.join(projectRoot, "src", "txm-wasm"), path.join(projectRoot, "dist", "txm-wasm"), { + recursive: true, +}); diff --git a/src/render.ts b/src/render.ts index 7786ed7..e21f7df 100644 --- a/src/render.ts +++ b/src/render.ts @@ -16,6 +16,7 @@ import { hyperlinkSupported, osc8 } from "./hyperlink.js"; import { parse } from "./parser.js"; import { convertLatexToUnicode } from "./latex.js"; import type { Styler } from "./theme.js"; +import { renderDisplayLatex } from "./txm.js"; import { createStyler, themes } from "./theme.js"; import type { RenderOptions, StyleIntent, Theme } from "./types.js"; import { visibleWidth, wrapText, wrapWithPrefix } from "./wrap.js"; @@ -590,8 +591,8 @@ function renderCodeBlock(node: Code, ctx: RenderContext): string[] { } function renderDisplayMath(node: { value: string }, ctx: RenderContext): string[] { - const converted = convertLatexToUnicode(node.value); - const styled = ctx.style(converted, ctx.options.theme.math || ctx.options.theme.inlineCode); + const rendered = renderDisplayLatex(node.value); + const styled = ctx.style(rendered, ctx.options.theme.math || ctx.options.theme.inlineCode); const lines = styled.split("\n"); return [`\n${lines.map((l) => ` ${l}`).join("\n")}\n`]; } diff --git a/src/txm-wasm/package.json b/src/txm-wasm/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/src/txm-wasm/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/src/txm-wasm/txm.d.ts b/src/txm-wasm/txm.d.ts new file mode 100644 index 0000000..b9b5a16 --- /dev/null +++ b/src/txm-wasm/txm.d.ts @@ -0,0 +1,4 @@ +/* tslint:disable */ +/* eslint-disable */ + +export function render_latex(latex: string): string; diff --git a/src/txm-wasm/txm.js b/src/txm-wasm/txm.js new file mode 100644 index 0000000..7775be4 --- /dev/null +++ b/src/txm-wasm/txm.js @@ -0,0 +1,134 @@ +/* @ts-self-types="./txm.d.ts" */ + +/** + * @param {string} latex + * @returns {string} + */ +function render_latex(latex) { + let deferred3_0; + let deferred3_1; + try { + const ptr0 = passStringToWasm0(latex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.render_latex(ptr0, len0); + var ptr2 = ret[0]; + var len2 = ret[1]; + if (ret[3]) { + ptr2 = 0; len2 = 0; + throw takeFromExternrefTable0(ret[2]); + } + deferred3_0 = ptr2; + deferred3_1 = len2; + return getStringFromWasm0(ptr2, len2); + } finally { + wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); + } +} +exports.render_latex = render_latex; + +function __wbg_get_imports() { + const import0 = { + __proto__: null, + __wbindgen_cast_0000000000000001: function(arg0, arg1) { + // Cast intrinsic for `Ref(String) -> Externref`. + const ret = getStringFromWasm0(arg0, arg1); + return ret; + }, + __wbindgen_init_externref_table: function() { + const table = wasm.__wbindgen_externrefs; + const offset = table.grow(4); + table.set(0, undefined); + table.set(offset + 0, undefined); + table.set(offset + 1, null); + table.set(offset + 2, true); + table.set(offset + 3, false); + }, + }; + return { + __proto__: null, + "./txm_bg.js": import0, + }; +} + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return decodeText(ptr, len); +} + +let cachedUint8ArrayMemory0 = null; +function getUint8ArrayMemory0() { + if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; +} + +function passStringToWasm0(arg, malloc, realloc) { + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = cachedTextEncoder.encodeInto(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +function takeFromExternrefTable0(idx) { + const value = wasm.__wbindgen_externrefs.get(idx); + wasm.__externref_table_dealloc(idx); + return value; +} + +let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); +cachedTextDecoder.decode(); +function decodeText(ptr, len) { + return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); +} + +const cachedTextEncoder = new TextEncoder(); + +if (!('encodeInto' in cachedTextEncoder)) { + cachedTextEncoder.encodeInto = function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; + }; +} + +let WASM_VECTOR_LEN = 0; + +const wasmPath = `${__dirname}/txm_bg.wasm`; +const wasmBytes = require('fs').readFileSync(wasmPath); +const wasmModule = new WebAssembly.Module(wasmBytes); +let wasm = new WebAssembly.Instance(wasmModule, __wbg_get_imports()).exports; +wasm.__wbindgen_start(); diff --git a/src/txm-wasm/txm_bg.wasm b/src/txm-wasm/txm_bg.wasm new file mode 100644 index 0000000..aaec9ac Binary files /dev/null and b/src/txm-wasm/txm_bg.wasm differ diff --git a/src/txm-wasm/txm_bg.wasm.d.ts b/src/txm-wasm/txm_bg.wasm.d.ts new file mode 100644 index 0000000..2d0b227 --- /dev/null +++ b/src/txm-wasm/txm_bg.wasm.d.ts @@ -0,0 +1,10 @@ +/* tslint:disable */ +/* eslint-disable */ +export const memory: WebAssembly.Memory; +export const render_latex: (a: number, b: number) => [number, number, number, number]; +export const __wbindgen_externrefs: WebAssembly.Table; +export const __wbindgen_malloc: (a: number, b: number) => number; +export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number; +export const __externref_table_dealloc: (a: number) => void; +export const __wbindgen_free: (a: number, b: number, c: number) => void; +export const __wbindgen_start: () => void; diff --git a/src/txm.ts b/src/txm.ts new file mode 100644 index 0000000..710362d --- /dev/null +++ b/src/txm.ts @@ -0,0 +1,23 @@ +import { createRequire } from "node:module"; + +import { convertLatexToUnicode } from "./latex.js"; + +type Txm = { + render_latex(latex: string): string; +}; + +const require = createRequire(import.meta.url); +const txm = require("./txm-wasm/txm.js") as Txm; + +export function renderDisplayLatex(latex: string): string { + try { + return txm + .render_latex(latex) + .trimEnd() + .split("\n") + .map((line) => line.trimEnd()) + .join("\n"); + } catch { + return convertLatexToUnicode(latex); + } +} diff --git a/test/render.test.ts b/test/render.test.ts index b174371..5484033 100644 --- a/test/render.test.ts +++ b/test/render.test.ts @@ -50,17 +50,26 @@ describe("inline formatting", () => { expect(out).not.toContain("\\mathrm"); }); - it("renders display LaTeX math as an indented block", () => { - const out = strip( - "Before\n\n$$\n\\partial\\Gamma\\coloneqq\\Gamma\\times(\\Gamma\\to\\Gamma)\\tag{5}\n$$\n\nAfter", - noColor, - ); + it("renders display LaTeX math as an indented two-dimensional Unicode grid", () => { + const out = strip("Before\n\n$$\n\\frac{a}{b}\n$$\n\nAfter", noColor); expect(out).toContain("Before"); - expect(out).toContain(" ∂Γ≔Γ×(Γ→Γ) (5)"); + expect(out).toContain(" a\n ───\n b"); expect(out).toContain("After"); expect(out).not.toContain("$$"); }); + it("renders display matrices as a two-dimensional Unicode grid", () => { + const out = strip("$$\\begin{bmatrix}a&b\\\\c&d\\end{bmatrix}$$", noColor); + expect(out).toContain(" ⎡ a b ⎤"); + expect(out).toContain(" ⎢"); + expect(out).toContain(" ⎣ c d ⎦"); + }); + + it("falls back to inline Unicode conversion for unsupported display LaTeX", () => { + const out = strip("$$\\unknown{x}$$", noColor); + expect(out).toContain(" unknownx"); + }); + it("leaves code spans, fenced code, and dollar amounts unchanged", () => { const out = strip("Use `$PATH` and pay $100.\n\n```ts\nconst formula = '$x$'\n```", noColor); expect(out).toContain("Use $PATH and pay $100."); diff --git a/vendor/txm-wasm/Cargo.lock b/vendor/txm-wasm/Cargo.lock new file mode 100644 index 0000000..923afe8 --- /dev/null +++ b/vendor/txm-wasm/Cargo.lock @@ -0,0 +1,231 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "logos" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f" +dependencies = [ + "logos-derive", +] + +[[package]] +name = "logos-codegen" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970" +dependencies = [ + "fnv", + "proc-macro2", + "quote", + "regex-automata", + "regex-syntax", + "syn 2.0.119", +] + +[[package]] +name = "logos-derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31" +dependencies = [ + "logos-codegen", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "txm" +version = "0.1.5" +dependencies = [ + "logos", + "thiserror", + "unicode-width", +] + +[[package]] +name = "txm-wasm" +version = "0.1.0" +dependencies = [ + "txm", + "wasm-bindgen", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "wasm-bindgen" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b" +dependencies = [ + "unicode-ident", +] diff --git a/vendor/txm-wasm/Cargo.toml b/vendor/txm-wasm/Cargo.toml new file mode 100644 index 0000000..d1208ef --- /dev/null +++ b/vendor/txm-wasm/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "txm-wasm" +version = "0.1.0" +edition = "2024" +publish = false + +[lib] +crate-type = ["cdylib"] + +[dependencies] +txm = { path = "../txm" } +wasm-bindgen = "=0.2.117" diff --git a/vendor/txm-wasm/src/lib.rs b/vendor/txm-wasm/src/lib.rs new file mode 100644 index 0000000..cc3fa23 --- /dev/null +++ b/vendor/txm-wasm/src/lib.rs @@ -0,0 +1,39 @@ +use wasm_bindgen::prelude::wasm_bindgen; + +#[wasm_bindgen] +pub fn render_latex(latex: &str) -> Result { + txm::render(latex) + .map(|rendered| strip_sgr(&rendered)) + .map_err(|error| error.to_string()) +} + +fn strip_sgr(text: &str) -> String { + let mut result = String::with_capacity(text.len()); + let mut chars = text.chars(); + + while let Some(ch) = chars.next() { + if ch == '\u{1b}' && chars.next() == Some('[') { + for parameter in chars.by_ref() { + if parameter == 'm' { + break; + } + } + } else { + result.push(ch); + } + } + + result +} + +#[cfg(test)] +mod tests { + use super::render_latex; + + #[test] + fn renders_plain_unicode_grid() { + let rendered = render_latex(r"\color{red}{\frac{a}{b}}").unwrap(); + assert_eq!(rendered, " a \n───\n b \n"); + assert!(!rendered.contains('\u{1b}')); + } +} diff --git a/vendor/txm/Cargo.lock b/vendor/txm/Cargo.lock new file mode 100644 index 0000000..fee40f2 --- /dev/null +++ b/vendor/txm/Cargo.lock @@ -0,0 +1,340 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "either" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "kasuari" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899" +dependencies = [ + "hashbrown 0.16.1", + "thiserror", +] + +[[package]] +name = "logos" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f" +dependencies = [ + "logos-derive", +] + +[[package]] +name = "logos-codegen" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970" +dependencies = [ + "fnv", + "proc-macro2", + "quote", + "regex-automata", + "regex-syntax", + "syn", +] + +[[package]] +name = "logos-derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31" +dependencies = [ + "logos-codegen", +] + +[[package]] +name = "lru" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b6180140927ee907000b0aa540091f6ea512ead4447c92b8fc35bc72788a5a6" +dependencies = [ + "hashbrown 0.17.1", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" +dependencies = [ + "bitflags", + "compact_str", + "hashbrown 0.17.1", + "itertools", + "kasuari", + "lru", + "strum", + "thiserror", + "unicode-segmentation", + "unicode-truncate", + "unicode-width", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "txm" +version = "0.1.5" +dependencies = [ + "logos", + "ratatui-core", + "thiserror", + "unicode-width", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" diff --git a/vendor/txm/Cargo.toml b/vendor/txm/Cargo.toml new file mode 100644 index 0000000..d69d90a --- /dev/null +++ b/vendor/txm/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "txm" +version = "0.1.5" +edition = "2024" +license = "MIT OR Apache-2.0" +description = "Terminal math rendering engine" +authors = ["thatmagicalcat "] +repository = "https://github.com/thatmagicalcat/txm" +readme = "README.md" + +[dependencies] +logos = "0.16" +thiserror = "2" +unicode-width = "0.2" + +ratatui-core = { version = "0.1", optional = true } + +[features] +default = [] +ratatui = ["dep:ratatui-core"] diff --git a/vendor/txm/LICENSE-APACHE b/vendor/txm/LICENSE-APACHE new file mode 100644 index 0000000..79b85c0 --- /dev/null +++ b/vendor/txm/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 thatmagicalcat + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/txm/LICENSE-MIT b/vendor/txm/LICENSE-MIT new file mode 100644 index 0000000..6d20923 --- /dev/null +++ b/vendor/txm/LICENSE-MIT @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2026 thatmagicalcat + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/txm/README.md b/vendor/txm/README.md new file mode 100644 index 0000000..42c742f --- /dev/null +++ b/vendor/txm/README.md @@ -0,0 +1,57 @@ +
+

TXM

+

TXM (Terminal TeX Math) is a math rendering engine with LaTeX support.

+
+ +# Screenshots: +![s0](./screenshots/0.png) +![s1](./screenshots/1.png) +![s2](./screenshots/2.png) +![s3](./screenshots/3.png) +![s4](./screenshots/4.png) +![s5](./screenshots/5.png) + +### Quick run using nix +``` +nix run github:thatmagicalcat/txm -- "E = mc^2" +``` +Requires [Nix](https://nix.dev/install-nix) with flakes enabled. + +# Installation +### Arch Linux (AUR) +Install `txm-git` using an AUR helper like `yay` or `paru`: +```bash +yay -S txm-git +``` + +Or install it manually: +```bash +git clone https://aur.archlinux.org/txm-git.git +cd txm-git +makepkg -si +``` + +### Gentoo Linux (GURU) +```bash +emerge -a app-text/txm +``` + +### Cargo (Rust) +``` +$ cargo install txm +``` +Or +``` +$ cargo install --git https://github.com/thatmagicalcat/txm +``` + +### Bindings +- C/C++ bindings live in [`bindings/c/`](./bindings/c/). +- Python bindings live in [`bindings/py/`](./bindings/py/). + +# Projects using TXM: +- [**txm.nvim**](https://github.com/rv178/txm.nvim/): LaTeX preview inside NeoVim using + +## License +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE)) +- MIT license ([LICENSE-MIT](LICENSE-MIT)) diff --git a/vendor/txm/UPSTREAM.md b/vendor/txm/UPSTREAM.md new file mode 100644 index 0000000..edc39fb --- /dev/null +++ b/vendor/txm/UPSTREAM.md @@ -0,0 +1,2 @@ +Upstream: https://github.com/thatmagicalcat/txm +Revision: 26e6d3cfef4d5d040711f4c49d9147aabd350d4d diff --git a/vendor/txm/src/ast.rs b/vendor/txm/src/ast.rs new file mode 100644 index 0000000..159f694 --- /dev/null +++ b/vendor/txm/src/ast.rs @@ -0,0 +1,36 @@ +#[derive(Debug, Clone, PartialEq)] +pub enum Expr { + Ident(String), + Number(String), + Delimiter { + left: char, + right: char, + inner: Box, + }, + Neg(Box), + Command { + name: String, + opts: Vec, + args: Vec, + }, + Superscript(Box, Box), + Subscript(Box, Box), + BothScripts(Box, Box, Box), + Prime(Box, usize), + BinOp(Box, BinOp, Box), + Juxtapose(Vec), + Escape(String), + Empty, + Matrix { + name: String, + rows: Vec>, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BinOp { + Add, + Sub, + Eq, + Mul, +} diff --git a/vendor/txm/src/backend.rs b/vendor/txm/src/backend.rs new file mode 100644 index 0000000..bb732fd --- /dev/null +++ b/vendor/txm/src/backend.rs @@ -0,0 +1,14 @@ +use crate::layout_tree::LayoutNode; +use crate::style::Style; + +pub trait Backend { + type Output; + type Error: std::error::Error; + + fn render(&self, tree: &LayoutNode) -> Result; +} + +pub trait RenderTarget { + fn set(&mut self, x: usize, y: usize, ch: char, style: Style); + fn fill_row(&mut self, y: usize, x_start: usize, x_end: usize, ch: char, style: Style); +} diff --git a/vendor/txm/src/backends/generic_backend.rs b/vendor/txm/src/backends/generic_backend.rs new file mode 100644 index 0000000..32f41d5 --- /dev/null +++ b/vendor/txm/src/backends/generic_backend.rs @@ -0,0 +1,495 @@ +use crate::ast::BinOp; +use crate::backend::RenderTarget; +use crate::layout_tree::{LayoutNode, LineStyle, NodeKind}; +use crate::style::Style; + +pub(crate) fn render_node(node: &LayoutNode, buf: &mut impl RenderTarget, x: usize, y: usize) { + render_inner(node, buf, x, y, Style::new()) +} + +fn render_inner( + node: &LayoutNode, + buf: &mut impl RenderTarget, + x: usize, + y: usize, + inherited: Style, +) { + let style = inherited.merge(node.style); + + match &node.kind { + NodeKind::Text { content } => { + for (i, &c) in content.iter().enumerate() { + buf.set(x + i, y, c, style); + } + } + + NodeKind::HStack { children, spacing } => { + let mut cx = x; + for child in children { + let cy = y + (node.baseline - child.baseline); + render_inner(child, buf, cx, cy, style); + cx += child.width + spacing; + } + } + + NodeKind::VStack { top, bottom, line } => { + let max_h = top.height.max(bottom.height); + let inner_w = top.width.max(bottom.width); + let pad = 1; + let top_x = x + pad + (inner_w.saturating_sub(top.width)) / 2; + let bot_x = x + pad + (inner_w.saturating_sub(bottom.width)) / 2; + + render_inner(top, buf, top_x, max_h - top.height + y, style); + render_inner(bottom, buf, bot_x, y + max_h + 1, style); + + if *line == LineStyle::Solid { + let w = node.width; + buf.fill_row(y + max_h, x, x + w, '─', style); + } + } + + NodeKind::Infix { lhs, op, rhs } => { + let baseline = lhs.baseline.max(rhs.baseline); + let lhs_y = y + (baseline - lhs.baseline); + let rhs_y = y + (baseline - rhs.baseline); + + render_inner(lhs, buf, x, lhs_y, style); + + let op_char = match op { + BinOp::Add => '+', + BinOp::Sub => '-', + BinOp::Eq => '=', + BinOp::Mul => '·', + }; + buf.set(x + lhs.width + 1, y + baseline, op_char, style); + + render_inner(rhs, buf, x + lhs.width + 3, rhs_y, style); + } + + NodeKind::Superscript { inline, base, exp } => { + let inline_shift = if !inline { exp.height } else { 0 }; + + render_inner(exp, buf, x + base.width, y, style); + render_inner(base, buf, x, y + inline_shift, style); + } + + NodeKind::Subscript { inline, base, sub } => { + let inline_shift = if !inline { base.height } else { 0 }; + + render_inner(base, buf, x, y, style); + render_inner(sub, buf, x + base.width, y + inline_shift, style); + } + + NodeKind::BothScripts { base, sub, sup } => { + render_inner(sup, buf, x + base.width, y, style); + render_inner(base, buf, x, y + sup.height, style); + let sub_y = y + sup.height + base.baseline + 1; + render_inner(sub, buf, x + base.width, sub_y, style); + } + + NodeKind::StretchyDelim { + inner, + left, + right, + fill, + } => { + if inner.height <= 1 { + let resolved_left = resolve_delimiter_single(*left); + let resolved_right = resolve_delimiter_single(*right); + buf.set(x, y, resolved_left, style); + render_inner(inner, buf, x + 1, y, style); + buf.set(x + node.width - 1, y, resolved_right, style); + } else { + let resolved = + resolve_delimiters(*left, *right, inner.height, *fill, inner.baseline); + for (row, (l, r)) in resolved.iter().enumerate().take(inner.height) { + buf.set(x, y + row, *l, style); + buf.set(x + node.width - 1, y + row, *r, style); + } + render_inner(inner, buf, x + 2, y, style); + } + } + + NodeKind::Accent { + inner, + mark, + stretch, + } => { + if *stretch { + for i in 0..node.width { + buf.set(x + i, y, *mark, style); + } + } else { + buf.set(x + node.width / 2, y, *mark, style); + } + render_inner(inner, buf, x, y + 1, style); + } + + NodeKind::Limits { base, lower, upper } => { + let max_h = upper.height.max(lower.height); + render_inner(upper, buf, x, y + (max_h - upper.height), style); + render_inner(base, buf, x, y + max_h, style); + render_inner(lower, buf, x, y + max_h + base.height, style); + } + + NodeKind::Sqrt { inner, index } => { + buf.set(x + 1, y, '┌', style); + for i in 2..node.width { + buf.set(x + i, y, '─', style); + } + for row in 1..node.height { + buf.set(x + 1, y + row, '│', style); + } + buf.set(x, y + node.height - 1, '╲', style); + render_inner(inner, buf, x + 3, y + 1, style); + + if let Some(idx) = index { + render_inner(idx, buf, x, y, style); + } + } + + NodeKind::Summation { inner } => { + render_summation(inner.as_deref(), buf, x, y, node.height, style); + } + + NodeKind::Product { inner } => { + render_product(inner.as_deref(), buf, x, y, node.height, style); + } + + NodeKind::Integral { inner } => { + render_integral(inner.as_deref(), buf, x, y, node.height, style); + } + + NodeKind::Matrix { .. } => { + render_matrix(node, buf, x, y, style); + } + + NodeKind::Neg { inner } => { + buf.set(x, y + inner.baseline, '-', style); + render_inner(inner, buf, x + 1, y, style); + } + + NodeKind::Prime { base, count } => { + render_inner(base, buf, x, y, style); + for i in 0..*count { + buf.set(x + base.width + i, y + base.baseline, '\'', style); + } + } + + NodeKind::Empty => {} + } +} + +fn resolve_delimiter_single(c: char) -> char { + match c { + '|' => '│', + _ => c, + } +} + +fn resolve_delimiters( + left: char, + right: char, + height: usize, + fill: bool, + baseline: usize, +) -> Vec<(char, char)> { + let (tl, tr, bl, br, ml, mr) = match (left, right) { + ('(', ')') => ('⎛', '⎞', '⎝', '⎠', '⎜', '⎟'), + ('[', ']') => ('⎡', '⎤', '⎣', '⎦', '⎢', '⎥'), + ('{', '}') => ('⎧', '⎫', '⎩', '⎭', '⎪', '⎪'), + ('|', '|') => ('⎪', '⎪', '⎪', '⎪', '⎪', '⎪'), + _ if fill => (left, right, left, right, left, right), + _ => (left, right, left, right, '│', '│'), + }; + + let mut result = Vec::with_capacity(height); + for row in 0..height { + let (l, r) = if row == 0 { + (tl, tr) + } else if row == height - 1 { + (bl, br) + } else if left == '{' && row == baseline { + ('⎨', '⎬') + } else { + (ml, mr) + }; + result.push((l, r)); + } + result +} + +fn render_summation( + inner: Option<&LayoutNode>, + buf: &mut impl RenderTarget, + x: usize, + y: usize, + h: usize, + style: Style, +) { + let inner = match inner { + Some(i) => i, + None => { + buf.set(x, y, '━', style); + buf.set(x + 1, y, '━', style); + buf.set(x + 2, y, '━', style); + buf.set(x + 3, y, '┓', style); + buf.set(x, y + 1, '⟩', style); + buf.set(x, y + 2, '━', style); + buf.set(x + 1, y + 2, '━', style); + buf.set(x + 2, y + 2, '━', style); + buf.set(x + 3, y + 2, '┛', style); + + return; + } + }; + + if inner.height <= 2 { + let w_sigma = 4; + buf.set(x, y, '━', style); + buf.set(x + 1, y, '━', style); + buf.set(x + 2, y, '━', style); + buf.set(x + 3, y, '┓', style); + buf.set(x, y + 1, '⟩', style); + buf.set(x, y + 2, '━', style); + buf.set(x + 1, y + 2, '━', style); + buf.set(x + 2, y + 2, '━', style); + buf.set(x + 3, y + 2, '┛', style); + let inner_y = y + (h.saturating_sub(inner.height)) / 2; + render_inner(inner, buf, x + w_sigma + 1, inner_y, style); + return; + } + + let w_sigma = ((1.5 * h as f32) as usize).max(h / 2 + 2); + + buf.fill_row(y, x, x + w_sigma - 1, '━', style); + buf.set(x + w_sigma - 1, y, '┓', style); + + buf.fill_row(y + h - 1, x, x + w_sigma - 1, '━', style); + buf.set(x + w_sigma - 1, y + h - 1, '┛', style); + + for r in 1..h - 1 { + let d = r.min(h - 1 - r); + let col = d.saturating_sub(1); + + let ch = if !h.is_power_of_two() && r == h / 2 { + '⟩' + } else if r < h / 2 { + '╲' + } else { + '╱' + }; + + buf.set(x + col, y + r, ch, style); + } + + render_inner(inner, buf, x + w_sigma + 1, y, style); +} + +fn render_product( + inner: Option<&LayoutNode>, + buf: &mut impl RenderTarget, + x: usize, + y: usize, + h: usize, + style: Style, +) { + let inner = match inner { + Some(i) => i, + None => { + buf.set(x, y, '┳', style); + buf.set(x + 1, y, '━', style); + buf.set(x + 2, y, '┳', style); + buf.set(x, y + 1, '┃', style); + buf.set(x + 2, y + 1, '┃', style); + return; + } + }; + + let w_pi = if h <= 2 { 3 } else { (h / 2 + 2).max(3) }; + + buf.set(x, y, '┳', style); + if w_pi > 2 { + buf.fill_row(y, x + 1, x + w_pi - 1, '━', style); + } + buf.set(x + w_pi - 1, y, '┳', style); + + for row in 1..h { + buf.set(x, y + row, '┃', style); + buf.set(x + w_pi - 1, y + row, '┃', style); + } + + let inner_y = y + (h.saturating_sub(inner.height)) / 2; + render_inner(inner, buf, x + w_pi + 1, inner_y, style); +} + +fn render_integral( + inner: Option<&LayoutNode>, + buf: &mut impl RenderTarget, + x: usize, + y: usize, + _h: usize, + style: Style, +) { + let inner = match inner { + Some(i) => i, + None => { + buf.set(x, y, '⎛', style); + buf.set(x, y + 1, '⎜', style); + buf.set(x, y + 2, '⎠', style); + return; + } + }; + + if inner.height <= 3 { + buf.set(x, y, '⎛', style); + buf.set(x, y + 1, '⎜', style); + buf.set(x, y + 2, '⎠', style); + let inner_y = if inner.height == 1 { y + 1 } else { y }; + render_inner(inner, buf, x + 2, inner_y, style); + } else { + buf.set(x, y, '⎛', style); + for row in 1..inner.height - 1 { + buf.set(x, y + row, '⎜', style); + } + buf.set(x, y + inner.height - 1, '⎠', style); + render_inner(inner, buf, x + 2, y, style); + } +} + +fn render_matrix( + node: &LayoutNode, + buf: &mut impl RenderTarget, + x: usize, + y: usize, + inherited: Style, +) { + let NodeKind::Matrix { name: _, rows } = &node.kind else { + return; + }; + + if rows.is_empty() || rows[0].is_empty() { + return; + } + + let num_rows = rows.len(); + + let mut row_max_depths = vec![0; num_rows]; + let mut row_max_baselines = vec![0; num_rows]; + let mut max_item_width = 0; + + for (i, row) in rows.iter().enumerate() { + let mut max_b = 0; + let mut max_d = 0; + for item in row { + max_item_width = max_item_width.max(item.width); + max_b = max_b.max(item.baseline); + max_d = max_d.max(item.height.saturating_sub(item.baseline)); + } + row_max_baselines[i] = max_b; + row_max_depths[i] = max_d; + } + + let cell_width = max_item_width; + let mut cell_height = 0; + for i in 0..num_rows { + let row_content_height = row_max_baselines[i] + row_max_depths[i]; + cell_height = cell_height.max(row_content_height); + } + + let row_padding = 1; + cell_height = cell_height.max(1); + + let active_cell_height = if num_rows > 1 { + cell_height + row_padding + } else { + cell_height + }; + + let hspacing = 4; + + let inner_x = x; + let inner_y = y; + + for (i, row) in rows.iter().enumerate() { + let row_content_height = row_max_baselines[i] + row_max_depths[i]; + let row_padding_top = (active_cell_height - row_content_height) / 2; + let row_cell_baseline = row_padding_top + row_max_baselines[i]; + + for (j, item) in row.iter().enumerate() { + let cell_x = inner_x + j * (cell_width + hspacing); + let cell_y = inner_y + i * active_cell_height; + + let item_x_in_cell = (cell_width - item.width) / 2; + let item_y_in_cell = row_cell_baseline - item.baseline; + + render_inner( + item, + buf, + cell_x + item_x_in_cell, + cell_y + item_y_in_cell, + inherited, + ); + } + } +} + +#[cfg(test)] +mod tests { + use super::render_node; + use crate::backend::RenderTarget; + use crate::style::{Color, Style}; + + struct StyleBuf { + cells: Vec<(char, Style)>, + width: usize, + } + + impl StyleBuf { + fn new(width: usize, height: usize) -> Self { + Self { + cells: vec![(' ', Style::new()); width * height], + width, + } + } + } + + impl RenderTarget for StyleBuf { + fn set(&mut self, x: usize, y: usize, ch: char, style: Style) { + let index = y * self.width + x; + self.cells[index] = (ch, style); + } + + fn fill_row(&mut self, y: usize, x_start: usize, x_end: usize, ch: char, style: Style) { + for x in x_start..x_end { + self.set(x, y, ch, style); + } + } + } + + #[test] + fn current_color_reaches_generated_renderer_cells() { + for input in [ + r"\color{red}{x+y}", + r"\color{red}{-x}", + r"\color{red}{x'}", + r"\color{red}{\int_a^b{f'\left(x\right) dx}}", + ] { + let tree = crate::layout(input).unwrap(); + let mut buf = StyleBuf::new(tree.width, tree.height); + render_node(&tree, &mut buf, 0, 0); + + let uncolored: String = buf + .cells + .iter() + .filter(|(ch, style)| *ch != ' ' && Color::new(style.fg_color()) != Color::RED) + .map(|(ch, _)| *ch) + .collect(); + + assert!( + uncolored.is_empty(), + "expected all cells in {input:?} to be red, uncolored: {uncolored:?}" + ); + } + } +} diff --git a/vendor/txm/src/backends/mod.rs b/vendor/txm/src/backends/mod.rs new file mode 100644 index 0000000..83d5c73 --- /dev/null +++ b/vendor/txm/src/backends/mod.rs @@ -0,0 +1,2 @@ +pub(crate) mod generic_backend; +pub mod terminal; diff --git a/vendor/txm/src/backends/terminal.rs b/vendor/txm/src/backends/terminal.rs new file mode 100644 index 0000000..c1ea5f3 --- /dev/null +++ b/vendor/txm/src/backends/terminal.rs @@ -0,0 +1,104 @@ +use std::fmt; +use std::fmt::Write; + +use crate::backend::Backend; +use crate::backend::RenderTarget; +use crate::layout_tree::LayoutNode; +use crate::style::Style; + +use super::generic_backend; + +pub struct TerminalBackend; + +impl TerminalBackend { + pub fn new() -> Self { + Self + } +} + +impl Default for TerminalBackend { + fn default() -> Self { + Self::new() + } +} + +impl Backend for TerminalBackend { + type Output = String; + type Error = fmt::Error; + + fn render(&self, tree: &LayoutNode) -> Result { + let mut buf = CharBuf::new(tree.width, tree.height); + generic_backend::render_node(tree, &mut buf, 0, 0); + Ok(buf.to_string()) + } +} + +#[derive(Debug, Clone)] +pub(crate) struct CharBuf { + pub data: Vec, + pub styles: Vec