Coder Social home page Coder Social logo

mathfmt's Introduction

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.

mathfmt's People

Contributors

mmcloughlin avatar

Stargazers

 avatar Ludi Rehak avatar Ray Lee avatar Andrew Woods avatar  avatar Sandalots avatar Julien Bisconti avatar Kenta Takahashi avatar Nikita Zhenev avatar  avatar e.j. sahala (they/them) avatar Francisco Diaz  avatar  avatar Lucas Bremgartner avatar Frederik Kvartborg Albertsen avatar Pinglei Guo avatar Lever avatar Matt Layher avatar Timur Mazitov avatar Pedro Amaral avatar Asaduzzaman Pavel avatar ringsaturn avatar Scott Blackwood avatar Mihai Todor avatar Jae-woo Kim avatar Eric Lagergren avatar arnaucube avatar Gautam Botrel avatar  avatar Rodrigo Schio avatar wwhai avatar Edgar Gavrik avatar  avatar Ivan Stasiuk avatar Einthusan Vigneswaran avatar Kent Gruber avatar Scott Cotton avatar Simon Boje Outzen avatar George Erickson avatar Can Evgin avatar Fabian avatar Prof Syd Xu avatar Simone Ragusa avatar Spiro avatar  avatar Tom Thorogood avatar Waleed AlMalki avatar  avatar Cat Ball avatar Matt Mueller avatar Aditya avatar Max Riveiro avatar Steven Ferrer avatar Armel Soro avatar Shakeel Mahate avatar Andres Mariscal avatar William Storey avatar Gustavo Freitas (Gus) avatar Eddie Scholtz avatar Lubomir Anastasov avatar micnncim avatar Pascal Dierich avatar Yining avatar rok avatar Ian avatar Tsuyoshi CHO avatar Zhao Xiaohong avatar Dmitri Shuralyov avatar Yijun Zhao avatar Dimitri Sokolyuk avatar Daniel Kertesz avatar Saad Azghour avatar Arda Aytekin avatar Ismail Chaida avatar Eliah Rusin avatar Triplex avatar n0nz avatar Ivan Ignatenko avatar Roman Hossain Shaon avatar John Duncan avatar Divyanshu Singh avatar genix avatar Yihau Chen avatar zbv avatar Fer⊼o Gonzalez-Morales avatar Eduardo Rabelo avatar Andy Walker avatar  avatar Jordi Montes avatar Dwi Siswanto avatar Alexey Terentev avatar Raúl Pleitez avatar  avatar Ashish avatar Philipp Sauter avatar  avatar Tomas Babej avatar Maddison Hellstrom avatar Nikita avatar Herby Gillot avatar

Watchers

Captain avatar Vladimír Chalupecký avatar  avatar  avatar

mathfmt's Issues

ci: windows

Fix tests on Windows.

There are some annoyances possibly related to line-endings, for example:

--- FAIL: TestFormatGolden (0.02s)
    --- FAIL: TestFormatGolden/poly1305 (0.00s)
Error:         golden_test.go:[7](https://github.com/mmcloughlin/mathfmt/actions/runs/5986804869/job/16240334229?pr=24#step:5:8)2: line number mismatch: got 30[8](https://github.com/mmcloughlin/mathfmt/actions/runs/5986804869/job/16240334229?pr=24#step:5:9) expect 307
    --- FAIL: TestFormatGolden/stats (0.00s)
Error:         golden_test.go:72: line 5:
            	got    = "//\t\t∑ xᵢ / N"
            	expect = "//\t∑ xᵢ / N"
Error:         golden_test.go:72: line 1[9](https://github.com/mmcloughlin/mathfmt/actions/runs/5986804869/job/16240334229?pr=24#step:5:10):
            	got    = "//\t\tσ² = ∑ (xᵢ - μ)² / N"
            	expect = "//\tσ² = ∑ (xᵢ - μ)² / N"
FAIL
exit status 1
FAIL	github.com/mmcloughlin/mathfmt	0.061s
Error: Process completed with exit code 1.

https://github.com/mmcloughlin/mathfmt/actions/runs/5986804869/job/16240334229?pr=24#step:5:7

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

`\eta_2`

I would expect it to be formatted as η₂.

(Let me just reiterate that I absolutely love this tool.)

testing: stdlib examples

The standard library has a lot of examples of this kind of thing. Perhaps use them for test cases?

Related #2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.