• Stars
    star
    155
  • Rank 236,090 (Top 5 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 10 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Convert mathematical equations to SVGs, PNGs, or MathML. A general wrapper to Lasem and mtex2MML.

Mathematical

Quickly convert math equations into beautiful SVGs (or PNGs/MathML).

Build Status Gem Version

Mathematical

Installation

Add this line to your application's Gemfile:

gem 'mathematical'

And then execute:

$ bundle

Or install it yourself as:

$ gem install mathematical

Note: you'll probably need to run script/bootstrap to fetch all the necessary dependencies.

Usage

The simplest way to do this is

require 'mathematical'

Mathematical.new.render(string_with_math)

string_with_math should just be a string of TeX math. The default delimiters are $..$ for inline and $$..$$ for display. These can be changed by options--see below.

The output will be a hash, with keys that depend on the format you want:

  • If you asked for an SVG, you'll get:
    • :width: the width of the resulting image
    • :height: the height of the resulting image
    • :data: the actual string of SVG
  • If you asked for a PNG, you'll get:
    • :width: the width of the resulting image
    • :height: the height of the resulting image
    • :data: the PNG data
  • If you asked for MathML, you'll get:
    • :data: the MathML data
  • If you pass in invalid TeX, you'll get:
    • :data: the original invalid TeX
    • :exception: the error class (with message)

Note: If you pass in invalid TeX, an error is not raised, but a message is printed to STDERR. It is the caller's responsibility to check for :exception and act on it.

render just converts a single equation. There are several other methods you can use:

  • filter: Given a string with a mix of TeX math and non-math elements, this returns a single string containing just the converted math elements.
  • text_filter: Given a string with a mix of TeX math and non-math elements, this converts all the math and leaves the rest of the string unmodified.
  • strict_filter: Given a string with a mix of TeX math and non-math elements, this converts all the math and leaves the rest of the string unmodified. HTML tags are removed completely.

Array of equations

Rather than just a string, you can also provide an array of math inputs:

inputs = []
inputs << '$\pi$'
inputs << '$not__thisisnotreal$'
inputs << '$\alpha$'

Mathematical.new.render(inputs)

This returns an array of hashes, rendering the indices. For example, for the above, you will receive the following output:

[ {:data => "...", :width => ... }, { :data => '$not__thisisnotreal$', :exception => "...", {:data => "...", :width => ... }]

That is, while the first and last elements are valid TeX math, the middle one is not, so the same string is returned. As with single strings, the error message is printed to STDERR, but not raised.

Options

Mathematical.new takes an optional hash to define a few options:

Name Description Default
:ppi A double determining the pixels per inch of the resulting SVG 72.0
:zoom A double determining the zoom level of the resulting SVG 1.0
:base64 A boolean determining whether Mathematical's output should be a base64-encoded SVG string false
:maxsize A numeral indicating the MAXSIZE the output string can be. unsigned long
:format A symbol indicating whether you want an :svg, :png, or :mathml output. :svg
:delimiter A symbol indicating whether you want an :DOLLAR for inline ($..$), :DOUBLE for display ($$..$$), :PARENS for inline (\(..\)), :BRACKETS for display ([..\]), or :ENVIRONMENTS for parsing bare \\begin..\\end environments. You can also pass in an array of symbols to have multiple delimiters considered. [:DOLLAR, :DOUBLE]

Pass these in like this:

options = { :ppi => 200.0, :zoom => 5.0, :base64 => true }
renderer = Mathematical.new(options)
renderer.render('$a \ne b$')

Supported commands and symbols

Check out SUPPORTED.md on the mtex2MML website.

Note: This library makes a few assumptions about the strings that you pass in. It assumes that $..$ is inline math and $$..$$ is display math.

Building

Before building this gem, you must install the following libraries:

  • Ruby 2.1 or higher (you'll need Ruby header files, so a *-dev version is also required)
  • GNU make
  • glib-2.0
  • gdk-pixbuf-2.0
  • xml2
  • cairo
  • pango
  • Dependencies for mtex2MML

After cloning the repo, you can fetch dependencies and run the library by typing:

script/bootstrap
bundle exec rake compile

If there were no errors, you're done! Otherwise, make sure to follow the dependency instructions.

Fonts and special notices for Mac OS X

Install the fonts with:

cd ~/Library/Fonts
curl -LO http://mirrors.ctan.org/fonts/cm/ps-type1/bakoma/ttf/cmex10.ttf \
     -LO http://mirrors.ctan.org/fonts/cm/ps-type1/bakoma/ttf/cmmi10.ttf \
     -LO http://mirrors.ctan.org/fonts/cm/ps-type1/bakoma/ttf/cmr10.ttf \
     -LO http://mirrors.ctan.org/fonts/cm/ps-type1/bakoma/ttf/cmsy10.ttf \
     -LO http://mirrors.ctan.org/fonts/cm/ps-type1/bakoma/ttf/esint10.ttf \
     -LO http://mirrors.ctan.org/fonts/cm/ps-type1/bakoma/ttf/eufm10.ttf \
     -LO http://mirrors.ctan.org/fonts/cm/ps-type1/bakoma/ttf/msam10.ttf \
     -LO http://mirrors.ctan.org/fonts/cm/ps-type1/bakoma/ttf/msbm10.ttf

Troubleshooting

Issues building Lasem

If you're having issues building Lasem, or have Lasem already preinstalled, you should set the MATHEMATICAL_USE_SYSTEM_LASEM environment variable to skip the build:

  • If you use bundler:

      MATHEMATICAL_USE_SYSTEM_LASEM=1 bundle install
    
  • If you use gem install:

      MATHEMATICAL_USE_SYSTEM_LASEM=1 gem install mathematical
    

Issues building mtex2mml

If you're having issues building mtex2mml, or have mtex2mml already preinstalled, you should set the MATHEMATICAL_USE_SYSTEM_MTEX2MML environment variable to skip the build:

  • If you use bundler:

      MATHEMATICAL_USE_SYSTEM_MTEX2MML=1 bundle install
    
  • If you use gem install:

      MATHEMATICAL_USE_SYSTEM_MTEX2MML=1 gem install mathematical
    

Benchmark

Run benchmarks with bundle exec rake benchmark:

Benchmarking....
Count: 3868 equations
Iterations: 1
                                               user     system      total        real
Rendering...                               3.280000   0.070000   3.350000 (  4.324458)

History

There are a smattering of libraries written in various languages to convert math into a variety of formats. But there needs to be a sane way to show math equations in the browser. With browser support for MathML under attack, it's unfortunately not a sustainable solution. A PNG or SVG representation of the equation is the safest way to go.

Most advice suggests using MathJax. While extremely popular I dislike the "stuttering" effect caused by pages loading math. JavaScript shouldn't be used in situations where server-rendering is a possibility, in my opinion.

To that end, I obsessed over the problem of server-side math rendering for over a week. Here was my journey:

  • I started out with blahtexml, which takes TeX equations and converts them to PNG. This wasn't a bad idea, but it took too long; for twelve equations, it took eight seconds. It was slow because it shelled out to LaTeX, then dvipng.

    In fact, as I discovered, most projects on the 'Net shell out to LaTeX, then something else, which makes performance absolutely horrid. I had to find something better, with preferably no dependency on LaTeX.

  • mimetex was my next attempt. It looked great: a pure C implementation that turned TeX equations into a rasterized representation, and then into a PNG. The speed was there, but the output image was pretty jagged. I tweaked the program to output BMPs, and tried to sharpen those with potrace, but the results were less then pleasant. The "update" to mimetex is mathtex, but it, too, depends on LaTeX and dvipng binaries to produce images.

  • pmml2svg had potential. It's a set of XSLT stylesheets to convert MathML to SVG. Unfortunately, it relies on XSLT 2.0, of which there are no Ruby bindings (at the time of this writing, April '14). It had to rely on Saxon and Java.

  • tth converts TeX to HTML, but the output is aesthetically unpleasing, so I passed.

  • Wikipedia uses texvc, which is written in OCaml, a language I am utterly unfamiliar with. In any event, I could not get the code to compile on my machine.

  • It took me forever to finally compile gtkmathview, and when it did, I got a bunch of SVG images with screwed up fonts.

  • dvisvgm worked well, but still depended on two external binaries (LaTeX to convert the text to dvi, and dvisvgm to turn it into SVG)

  • At one point, I began to try and convert the MathJax code to Ruby to figure out how it accomplished its toSVG methods. The MathJax codebase, while written by geniuses, is incomprehensible, due in part to JavaScript's inability to possess a coherent structure.

  • Near the end of my wits, I mimicked the behavior of mathrender2, which uses PhantomJS to embed MathJax onto a fake HTML page. This produced exactly what I needed: a bunch of accurate SVG files with no intermediate binaries. It was, unfortunately, a bit slow: for an arbitrary composition of 880 equations, it took about eight seconds to complete. Could I do better?

  • I came across Lasem, which met every need. It has no external binary dependencies (only library packages), can convert directly to SVG, and it's fast. The same arbitrary 880 equations were rendered in moments.

And thus a wrapper was born.

More math stuff

Check out math-to-itex, which quickly parses out TeX notation from strings.

With it, you could do something fun like:

MathToItex(string).convert do |eq, type|
  svg_content = Mathematical.new(:base64 => true).render(eq)

  # create image tags of math with base64-encoded SVGs
  %|<img class="#{type.to_s}-math" data-math-type="#{type.to_s}-math" src="#{svg_content}"/>|
end

More Repositories

1

html-pipeline

HTML processing filters and utilities
Ruby
2,250
star
2

html-proofer

Test your rendered HTML files to make sure they're accurate.
Ruby
1,550
star
3

markdowntutorial.com

Lessons to help guide new writers into Markdown!
HTML
515
star
4

commonmarker

Ruby wrapper for the comrak (CommonMark parser) Rust crate
Ruby
404
star
5

Earthbound-Battle-Backgrounds-JS

A JavaScript project that generates all the Earthbound/Mother 2 backgrounds.
JavaScript
338
star
6

jekyll-last-modified-at

A Jekyll plugin to show the last_modified_at time of a post.
Ruby
219
star
7

isBinaryFile

Detects if a file is binary in Node.js. Similar to Perl's -B
TypeScript
161
star
8

Shelves

An Android application that manages your collection of apparel, board games, books, comics, gadgets, movies, music, software, tools, toys, and video games.
Java
110
star
9

biscotto

UNMAINTAINED. CoffeeScript API documentation tool that uses TomDoc notation.
CoffeeScript
105
star
10

addalicense.com

DEPRECATED: Add a license to your public GitHub repositories
JavaScript
85
star
11

jekyll-time-to-read

A liquid tag for Jekyll to indicate the time it takes to read an article.
Ruby
72
star
12

nak

ack and ag inspired tool written in Node. Designed to be fast.
JavaScript
69
star
13

tailwind_merge

Utility function to efficiently merge Tailwind CSS classes without style conflicts.
Ruby
69
star
14

extended-markdown-filter

Some additional Markdown formatting, for use in HTML::Pipeline
Ruby
54
star
15

jekyll-html-pipeline

Use GitHub's HTML::Pipeline, in Jekyll!
Ruby
51
star
16

selma

Selma selects and matches HTML nodes using CSS rules. Backed by Rust's lol_html parser.
Rust
46
star
17

repository-sync

Simple Sinatra server to keep two repositories in sync (not like the band)
Ruby
45
star
18

ooo-maker

Modify your GitHub avatar to let people know you're away!
JavaScript
41
star
19

Earthbound-Battle-Backgrounds

This is a live wallpaper for Android 2.1+ that shows the battle background animations from Earthbound (Mother 2).
Java
38
star
20

roaster

Turns a raw and crunchy Markdown file into nice and smooth output
CoffeeScript
30
star
21

panda-docs

Pretty Awesome (and Necessary) Documentation Assembly--A total documentation build system for technical writers, and those who want to be like them.
JavaScript
29
star
22

no-more-masters

Rename your default Git branch from master to production
JavaScript
26
star
23

mtex2MML

A Bison grammar to convert TeX math into MathML.
C
24
star
24

graphql-idl-parser

A parser for the GraphQL IDL format.
Rust
24
star
25

panino-docs

API documentation generation tool with an emphasis on JSDoc-style comment parsing
JavaScript
22
star
26

publisher

Publishes your non-Jekyll content in `master` directly to `gh-pages`.
Ruby
19
star
27

ColoredLogcatPlusPlus

An extension of Jeff Sharkey's excellent ColoredLogcat terminal hack for Android development. Supports colors and filtering!
Python
17
star
28

jekyll-config-variables

A Jekyll monkey-patch to allow you to use variables within your _config.yml file.
Ruby
15
star
29

jekyll-conrefifier

Allows you to use Liquid variables in various places in Jekyll
Ruby
14
star
30

what_you_say

Natural language detection library. Written in Rust, wrapped in Ruby.
Ruby
13
star
31

namp

A fork of chjj's marked that adds some additional features
JavaScript
12
star
32

heroku_chat_sample

Go
11
star
33

NotoColorEmoji-png

A conversion of Android KitKat's NotoColorEmoji.ttf into PNG images
11
star
34

nothingherebut.me

A vanishing story.
JavaScript
10
star
35

color-proximity

Match the threshold of a color against a collection of colors.
Ruby
9
star
36

mathematical-node

A Node.js port of Mathematical
HTML
8
star
37

pointillist

A Ruby library to convert Atom's stylesheets into Pygments-compatible HTML
C
8
star
38

robotstxt-parser

Another fork of the robotstxt gem
Ruby
8
star
39

functional-docs

A documentation test suite for HTML files.
JavaScript
7
star
40

jekyll-geo-pattern

A liquid tag for Jekyll to generate an SVG/Base64 geo pattern
Ruby
6
star
41

function-extractor

Extracts all the functions from a Javascript file into an array of objects.
JavaScript
6
star
42

graphql-idl-parser-ruby

A parser for the GraphQL IDL format.
Ruby
6
star
43

branta

Search, for GitHub Pages.
Ruby
6
star
44

markdown_conrefs_js

Support for content references (conrefs) in Markdown (for Javascript).
JavaScript
6
star
45

notext.news

The news without the words
JavaScript
5
star
46

wireless-snes

Arduino sketches to intercept controller data from one SNES console and send it to another.
C++
5
star
47

destroy-all-monuments

This is data taken from the SPLC report titled "Whose Heritage? Public Symbols of the Confederacy" from April 21, 2016
Ruby
5
star
48

jekyll-jsminify

A very simple way to minify your JavaScript and CoffeeScript content in Jekyll.
Ruby
4
star
49

task-lists-js

An implementation of the basic task list logic (in CoffeeScript)
HTML
3
star
50

jekyll-toc-helpers

Some helper tags for generating TOCs.
Ruby
3
star
51

nanoc-redirector

A redirection extension for Nanoc
Ruby
3
star
52

past.codes

Remember the repositories you starred on GitHub.
Ruby
3
star
53

nanoc-conref-fs

A Nanoc filesystem to permit using conrefs/reusables in your content.
Ruby
3
star
54

dotfiles-old

My dotfiles.
Shell
3
star
55

heroicons_helper

Heroicons port for Ruby
Ruby
3
star
56

sffsoccer2ical

Converts the SFF soccer schedule to an ics file
Ruby
3
star
57

documentation-renderer

Documentation tools for Atom and Chrome
CoffeeScript
2
star
58

Shmup-for-Android

An Android port of an iOS Shmup.
D
2
star
59

ecma-re-validator

Validate a regular expression against what ECMA-262 (JavaScript) can actually do.
Ruby
2
star
60

mathematical-rs

Convert MathML into SVG.
Rust
2
star
61

page-toc-filter

A filter for the HTML::Pipeline to generate a page's table of contents.
Ruby
2
star
62

april-24-2015

Ruby
2
star
63

helpmewith.money

HTML
2
star
64

shale

JavaScript
2
star
65

math-to-itex

Parse a string and convert math equations to the itex notation.
Ruby
2
star
66

slack-pokemon-emoji

This is a tool to help you generate Pokรฉmon for your Slack team.
Ruby
2
star
67

changecase_rb

Demo showcasing wrapping Rust in Ruby (RubyConf 2023)
Ruby
2
star
68

kraken

Earthbound's battle backgrounds (as a screensaver)
C#
2
star
69

ADC-Zipcode-Sorter

Takes a CSV file, then sorts the zip codes in that file according to the USPS ADC rules
PHP
2
star
70

sfdc_grpc_api

JavaScript
1
star
71

who-owes-what

TypeScript
1
star
72

colorpicker

A native colorpicker, for Atom.
CSS
1
star
73

jekyll-collection-multiplier

Ruby
1
star
74

fake-pages-site

1
star
75

crud-test

A repository for people to ogle over.
1
star
76

rss-to-tweet

Ruby
1
star
77

tabulalingua

A table. For languages.
JavaScript
1
star
78

atweetforeveryoccasion.com

Tweets are considered official presidential statements; let's contrast 45's communication against his hypocritical actions.
CSS
1
star
79

ace

Ace (Ajax.org Cloud9 Editor)
JavaScript
1
star
80

escapist

Extremely minimal HTML/`href` escaping/unescaping. Emphasis on minimal.
Rust
1
star
81

tweetstorm

CLI tool to make a tweetstorm, with replies to yourself.
Ruby
1
star
82

graffito

JavaScript
1
star
83

YALC

Yet another link checker. This one only checks local files.
Perl
1
star
84

render-html-from-ast

Internal API renderer used by panino and cannolo
JavaScript
1
star
85

jekyll-github-markup

Ruby
1
star
86

jekyll-mathematical

A Jekyll plugin that wraps around Mathematical
Ruby
1
star
87

bartleby

JavaScript
1
star
88

focus_concentrate

Get close. Stay centered. Don't move.
HTML
1
star
89

heroku-buildpack-pango

Heroku buildpack with Pango
Shell
1
star
90

metrocarddump

This program will dump all of your EasyPay MTA rides into a JSON file.
Go
1
star
91

rubocop-standard

Grouped Rubocop rules
Ruby
1
star
92

token_checksum

Generate a 30 character long random token, with a prefix and a 32-bit checksum in the last 6 digits.
Ruby
1
star