From 8a9733d8a93c9b45390ff91b2fa50c139a56ee80 Mon Sep 17 00:00:00 2001 From: qwinsi <70425035+qwinsi@users.noreply.github.com> Date: Sun, 8 Dec 2024 10:45:47 +0800 Subject: [PATCH] add support for Typst round function --- package.json | 2 +- src/writer.ts | 20 +++++++++++++++++--- test/symbol.yml | 8 ++++---- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 3e2d543..d40536d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tex2typst", - "version": "0.2.9", + "version": "0.2.10", "description": "JavaScript library for converting TeX code to Typst", "type": "module", "main": "dist/index.js", diff --git a/src/writer.ts b/src/writer.ts index 67f32f8..a43a99a 100644 --- a/src/writer.ts +++ b/src/writer.ts @@ -280,8 +280,17 @@ export class TypstWriter { res = res.replace(/ceil\(\)/g, 'ceil("")'); return res; } - this.buffer = smartFloorPass(this.buffer); - this.buffer = smartCeilPass(this.buffer); + const smartRoundPass = function (input: string): string { + // Use regex to replace all "⌊ xxx ⌉" with "round(xxx)" + let res = input.replace(/⌊\s*(.*?)\s*⌉/g, "round($1)"); + // Typst disallow "round()" with empty argument, so add an empty string inside if it's empty. + res = res.replace(/round\(\)/g, 'round("")'); + return res; + } + const all_passes = [smartFloorPass, smartCeilPass, smartRoundPass]; + for (const pass of all_passes) { + this.buffer = pass(this.buffer); + } return this.buffer; } } @@ -352,7 +361,12 @@ export function convertTree(node: TexNode): TypstNode { content: '', args: node.args!.map(convertTree), }; - if (["[]", "()", "\\{\\}", "\\lfloor\\rfloor", "\\lceil\\rceil"].includes(left.content + right.content)) { + if ([ + "[]", "()", "\\{\\}", + "\\lfloor\\rfloor", + "\\lceil\\rceil", + "\\lfloor\\rceil", + ].includes(left.content + right.content)) { return group; } return { diff --git a/test/symbol.yml b/test/symbol.yml index 5a618ab..8b2f8c5 100644 --- a/test/symbol.yml +++ b/test/symbol.yml @@ -74,15 +74,15 @@ cases: - title: combinatorial number tex: \binom{n}{k} typst: binom(n, k) - - title: unpaired left and right floor, ceil 1 - tex: \lfloor \rceil \left \lfloor \frac{1}{2} \right \rceil - typst: ⌊ ⌉ lr(⌊ frac(1, 2) ⌉) - - title: unpaired left and right floor,ceil 2 + - title: unpaired left and right floor,ceil tex: \rfloor \lceil \left\lceil \frac{1}{2} \right \rfloor typst: ⌋ ⌈ lr(⌈ frac(1, 2) ⌋) - title: paired left and right floor,ceil tex: \lfloor x \rfloor \lceil x \rceil \left\lceil \frac{1}{2} \right \rceil typst: floor(x) ceil(x) ceil(frac(1, 2)) + - title: paired lfloor and rceil + tex: \lfloor \rceil \lfloor x \rceil \left \lfloor \frac{1}{2} \right \rceil + typst: round("") round(x) round(frac(1, 2)) - title: trigonometric functions tex: \sin \cos \tan \cot \sec \csc typst: sin cos tan cot sec csc