# Document mathematical Go code beautifully

### Related tags

Mathematics mathfmt

# mathfmt

Document mathematical Go code beautifully.

• Write mathematical formulae in a LaTeX-ish syntax
• Super/subscripts formatted with Unicode characters: 2^32 becomes 2³² and x_{i+1} becomes xᵢ₊₁
• Comprehensive symbol library: \zeta(s) = \sum 1/n^{s} becomes ζ(s) = ∑ 1/nˢ

Inspired by Filippo Valsorda's literate Go implementation of Poly1305, which can be reproduced using mathfmt.

## Usage

Install mathfmt with:

go get -u github.com/mmcloughlin/mathfmt


Apply to files just like you would with gofmt.

mathfmt -w file.go


## Example

Here's our variance function in Go, documented with LaTeX-ish equations in comments.

// Variance computes the population variance of the population x_{i} of size N.
// Specifically, it computes \sigma^2 where
//
//		\sigma^2 = \sum (x_{i} - \mu)^2 / N
//
func Variance(X []float64) float64 {
// Compute the average \mu.
mu := Mean(X)

// Compute the sum \sum (x_{i} - \mu)^2.
ss := 0.0
for _, x := range X {
ss += (x - mu) * (x - mu) // (x_{i} - \mu)^2
}

// Final divide by N to produce \sigma^2.
return ss / float64(len(X))
}

Run it through mathfmt and voila!

// Variance computes the population variance of the population xᵢ of size N.
// Specifically, it computes σ² where
//
//		σ² = ∑ (xᵢ - μ)² / N
//
func Variance(X []float64) float64 {
// Compute the average μ.
mu := Mean(X)

// Compute the sum ∑ (xᵢ - μ)².
ss := 0.0
for _, x := range X {
ss += (x - mu) * (x - mu) // (xᵢ - μ)²
}

// Final divide by N to produce σ².
return ss / float64(len(X))
}

## Syntax

First a warning: mathfmt does not have a rigorous grammar, it's a combination of string replacement and regular expressions that appears to work most of time. However you may run into some thorny edge cases.

### Source

mathfmt only works on Go source code. Every comment in the file is processed, both single- and multi-line.

### Symbols

mathfmt recognizes a huge symbol table that is almost entirely borrowed from LaTeX packages. Every symbol macro in comment text will be replaced with its corresponding Unicode character. In addition to LaTeX symbol macros, mathfmt supports a limited set of "aliases" for character combinations commonly used to represent mathematical symbols.

### Super/subscripts

Like LaTeX, superscripts use the ^ character and subscripts use _. If the super/subscript consists entirely of digits, then no braces are required: for example 2^128 or x_13. Otherwise braces must be used to surround the super/subscript, for example 2^{i} or x_{i+j}.

Note that Unicode support for super/subscripts is limited, and in particular does not support the full alphabet. Therefore, if there is not a corresponding super/subscript character available for any character in braces {...}, mathfmt will not perform any substition at all. For example there is no superscript q, so mathfmt will not be able to process 2^{q}, and likewise with x_{K}.

## Credits

Thank you to Günter Milde for the exhaustive unimathsymbols database of Unicode symbols and corresponding LaTeX math mode commands.

mathfmt is available under the BSD 3-Clause License.

##### A PDF document generator with high level support for text, drawing and images

GoFPDF document generator Package gofpdf implements a PDF document generator with high level support for text, drawing and images. Features UTF-8 supp

##### XPath package for Golang, supports HTML, XML, JSON document query.

XPath XPath is Go package provides selecting nodes from XML, HTML or other documents using XPath expression. Implementation htmlquery - an XPath query

##### Convert Microsoft Word Document to Markdown

docx2md Convert Microsoft Word Document to Markdown Usage $docx2md NewDocument.docx Installation$ go get github.com/mattn/docx2md Supported Styles

##### Markdown based document-driven RESTful API testing.

silk Markdown based document-driven web API testing. Write nice looking Markdown documentation (like this), and then run it using the silk command Sim

##### tbls is a CI-Friendly tool for document a database, written in Go.

tbls is a CI-Friendly tool for document a database, written in Go. Key features of tbls are: Document a database automatically in GFM format. Output d

##### squirrelbyte is a "proof of concept" document / search server backed by sqlite.

🐿️ squirrelbyte is a "proof of concept" document / search server backed by sqlite.

##### Programatic document generation as a HTTP service. Render PDFs using LaTeX templates and JSON.

LaTTe Generate PDFs using LaTeX templates and JSON. Try out the demo! Find LaTTe on Docker Hub Table of Contents About Obtaining LaTTe Running & Using

##### the document of monibuca

Monibuca 快速起步 项目地址 https://github.com/Monibuca 主页 https://monibuca.com 介绍 Monibuca 是一个开源的流媒体服务器开发框架，适用于快速定制化开发流媒体服务器，可以对接 CDN 厂商，作为回源服务器，也可以自己搭建集群部署环境

##### Document Indexing and Searching Library in Go

Fehrist Fehrist is a pure Go library for indexing different types of documents. Currently it supports only CSV and JSON but flexible architecture give

##### pdf document generation library

gopdf 项目介绍 gopdf 是一个生成 PDF 文档的 Golang 库. 主要有以下的特点: 支持 Unicode 字符 (包括中文, 日语, 朝鲜语, 等等.) 文档内容的自动定位与分页, 减少用户的工作量. 支持图片插入, 支持多种图片格式, PNG, BMP, JPEG, WEBP,

##### A document encryption solution for the reMarkable 2 ePaper tablet.

Remarkable 2 Encryption This repository contains multiple tools to encrypt the home folder of the reMarkable 2 epaper tablet using gocryptfs. Detailed

##### A PDF document generator with high level support for text, drawing and images

GoFPDF document generator Package go-pdf/fpdf implements a PDF document generator with high level support for text, drawing and images. Features UTF-8

##### Graphik is a Backend as a Service implemented as an identity-aware document & graph database with support for gRPC and graphQL

Graphik is a Backend as a Service implemented as an identity-aware, permissioned, persistant document/graph database & pubsub server written in Go.

##### CrankDB is an ultra fast and very lightweight Key Value based Document Store.

CrankDB is a ultra fast, extreme lightweight Key Value based Document Store.

##### estruct traverses javascript projects and maps all the dependencies and relationships to a JSON. the output can be used to build network visualizations of the project and document the architecture.

EStruct traverses javascript projects and maps all the dependencies and relationships to a JSON. The output can be used to build network visualizations of the project and document the architecture.

##### Everything a semantic desktop search engine combined with a single-user document management system

Everything will be a semantic desktop search engine combined with a single-user document management system. It will apply ideas of the semantic web and knowledge graphs to organize your data, allowing you to maintain private knowledge graphs as well as make use of public knowledge graphs, such as Wikidata.

##### sq is a command line tool that provides jq-style access to structured data sources such as SQL databases, or document formats like CSV or Excel.

sq: swiss-army knife for data sq is a command line tool that provides jq-style access to structured data sources such as SQL databases, or document fo

• #### testing: literate poly1305 test case

Since it sparked the idea in the first place, it would be good to have a test case based on @FiloSottile's literate poly1305 implementation.

https://blog.filippo.io/a-literate-go-implementation-of-poly1305/

opened by mmcloughlin 1
• #### latex symbols

Would be good to support a much more extensive set of symbols. Probably matching the LaTeX definitions would make sense. The following page provides a database we could use:

http://milde.users.sourceforge.net/LUCR/Math/

opened by mmcloughlin 0
• #### nasty edge cases

Collection of edge cases that are not handled well. See also #3.

Chained super/subscripts: For example in x/crypto/pkcs12:

	//       Z_2^u x Z_2^v -> Z_2^u


https://github.com/golang/crypto/blob/c9f3fb736b729628ec1e9c1a6b4313e883f452f9/pkcs12/pbkdf.go#L38

Punctuation prior: For example:

		//        A.  Set A2=H^r(D||I). (i.e., the r-th hash of D||1,


https://github.com/golang/crypto/blob/c9f3fb736b729628ec1e9c1a6b4313e883f452f9/pkcs12/pbkdf.go#L108

Tables: In the below, the -+ gets replaced with a "MINUS-PLUS" symbol.

//	                  |  USTAR |       PAX |       GNU
//	------------------+--------+-----------+----------
//	Name              |   256B | unlimited | unlimited
//	Linkname          |   100B | unlimited | unlimited


https://github.com/golang/go/blob/f770366f6d910e4bf92a6f885908afe134d65b23/src/archive/tar/format.go#L19-L22

Channel syntax: Source code in a comment replaced with a unicode arrow.

//	x, ok := <-c


https://github.com/golang/go/blob/f770366f6d910e4bf92a6f885908afe134d65b23/src/builtin/buil tin.go#L218

Quoted strings:

	// R1 op R2 or r1 op constant.
// op is:
//	"<<" == 0
//	">>" == 1
//	"->" == 2
//	"@>" == 3


https://github.com/golang/go/blob/f770366f6d910e4bf92a6f885908afe134d65b23/src/cmd/asm/internal/asm/parse.go#L610-L615

Comment dividers:

// The original C code, the long comment, and the constants
// below are from FreeBSD's /usr/src/lib/msun/src/s_log1p.c
// and came with this notice. The go code is a simplified
// version of the original C.
//
// ====================================================
//
// Developed at SunPro, a Sun Microsystems, Inc. business.
// Permission to use, copy, modify, and distribute this
// software is freely granted, provided that this notice
// is preserved.
// ====================================================


https://github.com/golang/go/blob/f770366f6d910e4bf92a6f885908afe134d65b23/src/math/log1p.go#L7-L19

Windows filepaths: Can be interpreted as LaTeX symbols:

//   * UNC paths                              (e.g \\server\share\foo\bar)
//   * absolute paths                         (e.g C:\foo\bar)
//   * relative paths begin with drive letter (e.g C:foo\bar, C:..\foo\bar, C:.., C:.)
//   * relative paths begin with '\'          (e.g \foo\bar)
//   * relative paths begin without '\'       (e.g foo\bar, ..\foo\bar, .., .)


opened by mmcloughlin 1
###### a cheat-sheet for mathematical notation in code form

math-as-code Chinese translation (中文版) Python version (English) This is a reference to ease developers into mathematical notation by showing compariso

14.4k Dec 6, 2022
###### Mathematical expression parsing and calculation engine library. 数学表达式解析计算引擎库

Math-Engine 使用 Go 实现的数学表达式解析计算引擎库，它小巧，无任何依赖，具有扩展性(比如可以注册自己的函数到引擎中)，比较完整的完成了数学表达式解析执行，包括词法分析、语法分析、构建AST、运行。 go get -u github.com/dengsgo/math-engine 能够

253 Dec 2, 2022
###### Suan - Mathematical expression calculation tool

suan Suan( 算 ) is a CLI tool to calculate given mathematical expression. Current

1 Feb 14, 2022
###### Go-Notebook is inspired by Jupyter Project (link) in order to document Golang code.

Go-Notebook Go-Notebook is an app that was developed using go-echo-live-view framework, developed also by us. GitHub repository is here. For this proj

30 Nov 17, 2022
###### Test your code without writing mocks with ephemeral Docker containers 📦 Setup popular services with just a couple lines of code ⏱️ No bash, no yaml, only code 💻

Gnomock – tests without mocks ??️ Spin up entire dependency stack ?? Setup initial dependency state – easily! ?? Test against actual, close to product

997 Nov 30, 2022
###### :triangular_ruler:gofmtmd formats go source code block in Markdown. detects fenced code & formats code using gofmt.

gofmtmd gofmtmd formats go source code block in Markdown. detects fenced code & formats code using gofmt. Installation \$ go get github.com/po3rin/gofm

91 Oct 31, 2022
###### octocov is a tool for collecting code metrics (code coverage, code to test ratio and test execution time).

octocov is a tool for collecting code metrics (code coverage, code to test ratio and test execution time).

151 Dec 5, 2022
###### sail is an operation framework based on Ansible/Helm. sail follows the principles of Infrastructure as Code (IaC), Operation as Code (OaC), and Everything as Code. So it is a tool for DevOps.

sail 中文文档 sail is an operation framework based on Ansible/Helm. sail follows the principles of Infrastructure as Code (IaC), Operation as Code (OaC)，a

10 Dec 16, 2021
###### A rudimentary implementation of a basic document (NoSQL) database in Go

tiedot Documentation Keywords: Golang, go, document database, NoSQL, JSON tiedot - Your NoSQL database powered by Golang tiedot is a document database

2.7k Nov 14, 2022
83 Nov 3, 2022