Document mathematical Go code beautifully

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
//
// See also: https://en.wikipedia.org/wiki/Variance.
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
//
// See also: https://en.wikipedia.org/wiki/Variance.
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.

License

mathfmt is available under the BSD 3-Clause License.

Owner
Similar Resources

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

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

Dec 28, 2022

Produces a set of tags from given source. Source can be either an HTML page, Markdown document or a plain text. Supports English, Russian, Chinese, Hindi, Spanish, Arabic, Japanese, German, Hebrew, French and Korean languages.

Produces a set of tags from given source. Source can be either an HTML page, Markdown document or a plain text. Supports English, Russian, Chinese, Hindi, Spanish, Arabic, Japanese, German, Hebrew, French and Korean languages.

Tagify Gets STDIN, file or HTTP address as an input and returns a list of most popular words ordered by popularity as an output. More info about what

Dec 19, 2022

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

Dec 28, 2022

Convert Microsoft Word Document to Markdown

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

Jan 4, 2023

Markdown based document-driven RESTful API testing.

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

Dec 18, 2022

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.

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

Jan 5, 2023

Document-oriented, embedded SQL database

Genji Document-oriented, embedded, SQL database Table of contents Table of contents Introduction Features Installation Usage Using Genji's API Using d

Jan 1, 2023

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

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

May 20, 2022

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

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

Dec 29, 2022

the document of monibuca

the document of monibuca

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

Nov 25, 2022

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

May 22, 2022

pdf document generation library

pdf document generation library

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

Dec 8, 2022

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

Nov 7, 2022

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

Jan 4, 2023

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 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.

Dec 30, 2022

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.

Apr 12, 2022

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.

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.

Jan 27, 2022

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.

May 21, 2022

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

Jan 1, 2023
Comments
  • testing: literate poly1305 test case

    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/

  • latex symbols

    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/

  • nasty edge cases

    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.
    //
    // ====================================================
    // Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
    //
    // 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, .., .)
    

    https://github.com/golang/go/blob/f770366f6d910e4bf92a6f885908afe134d65b23/src/path/filepath/symlink_windows.go#L52-L56

Related tags
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

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

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

Jan 3, 2023
Suan - Mathematical expression calculation tool

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

Feb 14, 2022
Go-Notebook is inspired by Jupyter Project (link) in order to document Golang code.
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

Jan 9, 2023
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

Dec 29, 2022
:triangular_ruler:gofmtmd formats go source code block in Markdown. detects fenced code & formats code using gofmt.
: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

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).

Jan 9, 2023
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

Dec 16, 2021
A rudimentary implementation of a basic document (NoSQL) database in Go
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

Dec 11, 2022
Powerful and versatile MIME sniffing package using pre-compiled glob patterns, magic number signatures, XML document namespaces, and tree magic for mounted volumes, generated from the XDG shared-mime-info database.

mimemagic Powerful and versatile MIME sniffing package using pre-compiled glob patterns, magic number signatures, xml document namespaces, and tree ma

Nov 3, 2022