Package: typst-sympy-calculator
Typst Sympy CalculatorAboutTypst Sympy CalculatorparsesTypst Math Expressionsand converts it into the equivalentSymPy form. Then,calculate itand convert to typst math text.It is designed for providingpeople writing in typsta ability to calculate something when writing math expression. It is based onSympymodule inPython.Thetypst-sympy-calculatorpython package is a backend for a VS Code extensionTypst Sympy Calculator, and you also can use it just for parse typst math expression to sympy form in order to do things for yourself.FeaturesDefault Math:Arithmetic:Add (+), Sub (-), Dot Mul (dot), Cross Mul (times), Frac (/), Power (^), Abs (|x|), Sqrt (sqrt), etc...Alphabet:a - z,A - Z,alpha - omega, Subscript (x_1), Accent Bar(hat(x)), etc...Common Functions:gcd,lcm,floor,ceil,max,min,log,ln,exp,sin,cos,tan,csc,sec,cot,arcsin,sinh,arsinh, etc...Funcion Symbol:f(x),f(x-1,),g(x,y), etc...Calculous:Limitlim_(x -> oo) 1/x, Integrationintegral_1^2 x dif x, etc...Calculous:Derivation (dif/(dif x) (x^2 + 1)is not supported, but you can usederivative(expr, var)instead), etc...Reduce:Sumsum_(k=1)^oo (1/2)^k, Productproduct_(k=1)^oo (1/2)^k, etc...Eval At:Evalatx^2 bar_(x = 2),x^2 "|"_(x = 2), etc...Linear Algebra:Matrix to raw echelon formrref, Determinantdet, Transpose^T, Inverse^(-1), etc...Relations:==,>,>=,<,<=, etc...Solve Equation:Single Equationx + 1 = 2, Multiple Equationscases(x + y = 1, x - y = 2), etc...Logical:and,or,not, etc...Set Theory:in,sect,union,subset, etc...Other:Binomialbinom(n, k)...Custom Math (in typst file):Define Accents:#let acc(x) = math.accent(x, math.grave)Define Operators:#let add = math.op("add")Define Symbols:#let xy = math.italic("xy")or#let mail = symbol("🖂", ("stamped", "🖃"),)Define Functions:# typst-calculator@func()defconvert_add(a,b):returna+bTypst Math Printer:CompleteTypstMathPrinterinTypstConverter.pyCustom Printer forTypstCalculator.pyandTypstCalculatorServer.pyVS Code Extension:Develop a VS Code Extension forTypst CalculatorInstallpipinstalltypst-sympy-calculatorUsageDifference Betweenparse,converter,calculator,serverTypstParser.py: parse typst math expression to ANTLR abstract syntax tree withTypstGrammar.g4;TypstConverter.py:convert typst math expression to sympy expression viaTypstMathConverter;convert sympy expression to typst math expression viaTypstMathPrinter;hasdecoratorsfor defining custom functions, operators;hasdefine_accent,define_symbol_baseanddefine_functionfor defining custom accents, symbols and functions;TypstCalculator.py:calculate sympy expression and convert to typst math expression;hassubs,simplify,evalfmethods;hasset_varianceandunset_variancefor calculating with variance;DefaultTypstCalculator: define many useful functions, operators, accents, symbols;Accents, Alphabet, Greeks, Arithmetic, Common Functions, Calculous, Linear Algebra, etc...TypstCalculatorServer:hasinitmethod for initializingTypstCalculatorwith a typst file;can define your custom functions on your typst file;hassimplify,subs,evalfmethods for calculating with typst file;It is a top-down design, so you can useTypstCalculatorServerdirectly, or useTypstCalculatorwithTypstConverter.RECOMMEND: see the usage of decorators like@func()inDefaultTypstCalculator.py.For the usage, you can see the unit test partif __name__ == '__main__':in each files.Sympy Expressions and Typst Math TextfromTypstCalculatorServerimportTypstCalculatorServerserver=TypstCalculatorServer()typst_math=r'1 + 1'expr=server.sympy(typst_math)print(server.typst(expr))fromTypstCalculatorimportTypstCalculatorcalculator=TypstCalculator()typst_math=r'1 + 1'expr=calculator.sympy(typst_math)print(calculator.typst(expr))fromTypstConverterimportTypstMathConverterconverter=TypstMathConverter()typst_math=r'1 + 1'expr=converter.sympy(typst_math)print(converter.typst(expr))Typst Calculator ServerThe simplest way to use it is just likeTypstCalculatorServer.py:fromTypstCalculatorServerimportTypstCalculatorServerserver=TypstCalculatorServer()typst_file=os.path.abspath(r'./tests/test.typ')server.init(typst_file)server.return_text=True# otherwise just return sympy formexpr=server.simplify('1 + 1',typst_file)print(expr)# 2server.enable_subs=Falseexpr=server.simplify('a + 1',typst_file)print(expr)# a + 1server.enable_subs=Trueexpr=server.simplify('a + 1',typst_file)print(expr)# 2expr=server.simplify('b + 1',typst_file)print(expr)# a + 2expr=server.simplify('cmat(1, 2)',typst_file)print(expr)# mat(1; 2)expr=server.simplify('f(1) + f(1)',typst_file)print(expr)# 2 f(1)expr=server.simplify('xy + mail + mail.stamped',typst_file)print(expr)# mail + mail.stamped + xyexpr=server.solve('x + y + z = 1')print(expr)# y = -x - z + 1, z = -x - y + 1, x = -y - z + 1expr=server.solve('cases(x + y + z = 1, x = 2)')print(expr)# cases(x = 2, z = -y - 1), cases(y = -z - 1, x = 2), y = -x - z + 1, z = -x - y + 1expr=server.solve('cases(x^2 + y = 4, y = 2)')print(expr)# x = sqrt(4 - y), cases(y = 2, x = sqrt(2)), cases(y = 2, x = -sqrt(2)), x = -sqrt(4 - y)expr=server.solve('cases(x < 2, x > 1)')print(expr)# 1 < x and x < 2and the typst filestests/test.typ#import "cal.typ": *



// set variances

#let a = 1

#let b = $a + 1$andtests/cal.typjust like:// define accents

#let acc(x) = math.accent(x, math.grave)



// define operators

#let add = math.op("add")

#let f = math.op("f")



// define symbols

#let xy = math.italic("xy")

#let mail = symbol("🖂", ("stamped", "🖃"),)Default Typst CalculatorIf you have not a typst file, you can useDefaultTypstCalculator.py, it define many useful functions and symbols just like:# Symbolsabc='abcdefghijklmnopqrstuvwxyz'forcinabc:calculator.define_symbol_base(c)calculator.define_symbol_base(c.upper())# Functions@func()defconvert_sin(expr):returnsympy.sin(expr)So you can use it by:fromDefaultTypstCalculatorimportget_default_calculatorcalculator=get_default_calculator(complex_number=True)calculator.return_text=Trueoperator,relation_op,additive_op,mp_op,postfix_op,\reduce_op,func,func_mat,constant=calculator.get_decorators()expr=calculator.simplify('1 + 1')assertexpr=='2'expr=calculator.evalf('1/2',n=3)assertexpr=='0.500'calculator.set_variance('a','1/2')expr=calculator.simplify('a + 1')assertexpr=='3/2'calculator.unset_variance('a')expr=calculator.simplify('a + 1')assertexpr=='a + 1'orexpr=='1 + a'expr=calculator.evalf('pi',n=3)assertexpr=='3.14'expr=calculator.simplify('max(1, 2)')assertexpr=='2'calculator.define_function('f')expr=calculator.simplify('f(1) + f(1) - f(1)')assertexpr=='f(1)'expr=calculator.simplify('lim_(x -> oo) 1/x')assertexpr=='0'VariancesYou canASSIGNvariance a value using same assignment form in typst:#let x = 1



// Before

$ x $



// Shift + Ctrl + E

// After

$ x = 1 $PS: You can use grammar likey == x + 1to describe the relation of equality.If you want to see the bonding of variances, you can pressShift + Ctrl + P, and inputtypst-sympy-calculator: Show Current variances, then you will get data like:y = x + 1

z = 2 xFunctionsYou canDEFINEa function using same form in typst:#let f = math.op("f")



// Before

$ f(1) + f(1) $



// Shift + Ctrl + E

// After

$ f(1) + f(1) = 2 f(1) $SymbolsYou canDEFINEa symbol using same form in typst:#let xy = math.italic("xy")

#let email = symbol("🖂", ("stamped", "🖃"),)



$ xy + email + email.stamped $AccentsYou canDEFINEa accent using same form in typst:#let acc(x) = math.accent(x, math.grave)



$ acc(x) $Decorators for OperatorsYou canDEFINEa operator using same form in typst:#let add = math.op("+")



'''typst-calculator

@additive_op()

def convert_add(a, b):

    return a + b

'''



// Before

$ 1 add 1 $



// Shift + Ctrl + E

// After

$ 1 add 1 = 2 $Or just use'''typst-sympy-calculatoror'''python \n # typst-calculatorto define a operator.there are some decorators you can use:@operator(type='ADDITIVE_OP', convert_ast=convert_ast, name=name, ast=False): Define a common operator;@func(): Define a function, receive args list;@func_mat(): Define a matrix function, receive single argmatrix;@constant(): Define a constant, receive no args but only return a constant value;@relation_op(): Define a relation operator, receive argsaandb;@additive_op(): Define a additive operator, receive argsaandb;@mp_op(): Define a multiplicative operator, receive argsaandb;@postfix_op(): Define a postfix operator, receive argsa;@reduce_op(): Define a reduce operator, receive argsexprandargs = (symbol, sub, sup);It is important that the function name MUST bedef convert_{operator_name}, or you can use decorator arg@func(name='operator_name'), and the substring_dot_will be replaced by..There are some examples (fromDefaultTypstCalculator.py):# Functions@func()defconvert_binom(n,k):returnsympy.binomial(n,k)# Matrix@func_mat()defconvert_mat(mat):returnsympy.Matrix(mat)# Constants@constant()defconvert_oo():returnsympy.oo# Relation Operators@relation_op()defconvert_eq(a,b):returnsympy.Eq(a,b)# Additive Operators@additive_op()defconvert_plus(a,b):returna+b# Mp Operators@mp_op()defconvert_times(a,b):returna*b# Postfix Operators@postfix_op()defconvert_degree(expr):returnexpr/180*sympy.pi# Reduces@reduce_op()defconvert_sum(expr,args):# symbol, sub, sup = argsreturnsympy.Sum(expr,args)ContributingClone it bygit clone https://github.com/OrangeX4/typst-calculator.gitInstall dependencies bypip install -r requirements.txtCompile ANTLR grammar bypython ./scripts/compile.pyDebug or add your code withTypstCalculatorServer.pyorTypstCalculator.py, etc...It is welcome to create an issue or pull request.Thanksaugustt198 / latex2sympypurdue-tlt / latex2sympyANTLRSympyLicenseThis project is licensed under the MIT License.