Posts Tagged ‘latex’

Real-time LaTeX in browser

Tuesday, August 23rd, 2016

A long time ago, I made a little web app that allowed you to submit Latex code to a server, the server would run pdflatex and then send back the pdf to be rendered on the page.

Nowadays MathJax can render LaTeX equations in the browser. I found http://www.texrendr.com that let’s you interactively write formulae, but it’s restricted to a single equation. There’s also the LaTeXit standalone app, but you have to keep hitting “typeset”. This isn’t so useful if you’re trying to quickly type math during a Skype call.

So I wrote a little program to run in the browser:

http://www.cs.toronto.edu/~jacobson/latex.html

You can also fork the git gist

Create a low resolution pdf of a LaTeX paper

Thursday, April 21st, 2016

Here’re the steps I use to create a low resolution version of a pdf created by LaTeX.

The simple thing to do is to follow the steps to create a camera ready (high res) pdf but replace the JPG settings to downsample the images and perhaps reduce the quality.

If you have a lot of raster images, this will work OK.

However, if you have a lot of vector graphics images or just a lot of images, this will not truly bring down the size of the final pdf.

For this I make sure that all of my \includegraphics commands in LaTeX are of the form:

\includegraphics[width=\linewidth]{\figs/figure-file-name}

Notice three things:

  1. the width is explicitly specified,
  2. the figure directory is a command/macro \figs, and
  3. the filename does not have an extension (figure-file-name instead of figure-file-name.pdf)

Then at the beginning of my file I have defined \figs. For the normal high resolution pdf I use:

\newcommand{\figs}{}
\def\figs/{figs/}

When I switch to low resolution I use

\newcommand{\figs}{}
%\def\figs/{figs/}
\def\figs/{figs/low-res/}

And before compiling I run the commands:

mkdir -p figs/low-res/
mogrify -colorspace RGB -resize 400x -background white -alpha remove -quality 100 -format jpg -path figs/low-res/ figs/*.{pdf,png}[0]

There are a couple import flags here to ensure that the background is white and only a single output is created for pdfs with accidentally multiple art-boards/pages.

Make the most recent tex document in the current directory and open it

Wednesday, January 13th, 2016

Here’s a little bash script to compile (pdflatex, bitex, 2*pdflatex,etc.) the most recent .tex file in your current directory that contains begin{document} (i.e. the main document):

#!/bin/bash
if [ -z "$LMAKEFILE" ]; then
  echo "Error: didn't find LMAKEFILE environment variable"
  exit 1
fi
TEX=$( \
  grep -Il1dskip "begin{document}" *.tex | \
  xargs stat -f "%m %N" | \
  sort -r | \
  head -n 1 | \
  sed -e "s/^[^ ]* //")
BASE="${TEX%.*}"
if [ -z "$TEX" ]; then
  echo "Error: Didn't find begin{document} in any .tex files"
  exit 1
fi
make -f $LMAKEFILE $BASE && open $BASE.pdf

Simply use it:

texmake

MathJax reloading when editing wordpress page using wp-markdown plugin

Wednesday, August 5th, 2015

Here’s what I added to the wp-admin/admin-header.php file of my wordpress site to re-typeset the preview of the latex-math as I type into the post editor:

<script>
document.addEventListener('DOMContentLoaded', 
  function()
  {
    // http://stackoverflow.com/a/4029518/148668
    var idleTime = 0;
    // Increment every 100 millisecond
    setInterval(timerIncrement, 100);
    function timerIncrement()
    {
      idleTime+=100;
      if(idleTime>1000)
      {
        idleTime=0;
        if(MathJax.Hub.queue.running == 0 && MathJax.Hub.queue.pending == 0)
        {
          MathJax.Hub.Typeset();
        }
      }
    }

    document.getElementById("content").onkeypress = 
      function(e)
      {
        idleTime = 0;
      };
  },false);
</script>

Battle with acmsiggraph.cls’s copyright space

Monday, April 13th, 2015

Switching to the final version of the acm siggraph latex template always messes up the first page, but lately I’ve had a lot of trouble with the copyright space. Somehow I end up with blank space all other the first two columns rather than just a small portion at the bottom of the first column. To fix this, in acmsiggraph.cls I replaced:

\footnotetext[0]{\rule[\ACMcopyrightspace]{2.71828in}{0in}}%

with

\footnotetext[0]{\vspace*{1in}}%

Alias for universal latex makefile

Wednesday, December 31st, 2014

A friend recently turned me on to latex-makefile. This little script generates a universal Makefile for building latex documents. I was pretty impressed. All you need to do is copy the generated Makefile into your working directory of tex files and issue:

make

or if you have many .tex files

make [main_document]

I caught myself copying this makefile into a few places which seemed a bit silly so instead I put it in a reasonable place and made an alias to find it there:

export LMAKEFILE="/usr/local/include/UniversalLatexMakefile"
alias lmake="make -f $LMAKEFILE"

Now I can type from anywhere:

lmake [main document]

without copying the Makefile

Drop-in replacement header for switching from MathJax to KaTeX in markdown

Friday, November 7th, 2014

I wanted to try out switching to KaTeX from MathJax for our libigl tutorial. KaTeX needs a little bit of javascript besides the including the script to know to iterate over all class=math tags and render the latex code.

Also, it seems that markdown translates \\(x+y\\) into <span class=math>\(x+y\)</span> and the \( parenthesis throw off the KaTeX. You get an error like:

ParseError: KaTeX parse error: Expected 'EOF', got '\(' at position 2: \(x+y

So my header to switch from mathjax simply iterates over all math tags on document load using jquery and strips these parenthesis (which I expect on all tags):

<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.1.1/katex.min.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.1.1/katex.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(function(){
  $(".math").each(function() {
    var texTxt = $(this).text();
    texTxt =  texTxt.slice(2,-2);
    el = $(this).get(0);
    if(el.tagName == "DIV"){
        addDisp = "\\displaystyle";
    } else {
        addDisp = "";
    }
    try {
        katex.render(addDisp+texTxt, el);
    }
    catch(err) {
        $(this).html("<span class='err'>"+err);
    }
  }); 
}); 
</script>

I didn’t invest much more into bulletproofing this because it seems like KaTeX is still in its infancy in terms of LaTeX support. It doesn’t support unicode characters (e.g. ∑, ∆, π) or common tags like \mathbf or \begin{cases}. Hopefully it will eventually, it is much faster than MathJax for the simple equations.

Emoji in LaTeX documents

Tuesday, August 5th, 2014

Update: Hilariously, it turns out that either wordpress or my wordpress markdown plugin is choking on the emoji inserted into this post. Thus, to see the actually emoji commands see this plaintext version


We were recently joking around about using emoji in math equations. The idea was to satire of the bad rap exterior calculus symbols like the the Hodge star operator (★) and the “musical isomorphisms” (♭,♯) get in the computer graphics community.

I found a solution for upTeX. This works by first extracting all of the emojis as pdfs and then including the pdfs via (includegraphics) whenever a \coloremoji{...} command is found. This unfortunately did not work with my TexLive pdflatex setup. With some help, I’ve redesigned a coloremoji.sty stylesheet that allows you to directly include emoji in your LaTeX documents.

A Hello, EmojiWorld LaTeX document would look like this:

WordPress dies on emoji, see plaintext version

This produces something that should look like:

hello world emoji

You can also use emoji in mathmode:

WordPress dies on emoji, see plaintext version

alligator power integral math emoji latex

Download the coloremoji package and simply add \usepackage{coloremoji} to the top of your document.

Actually, Nobuyuki Umetani gave a talk where he used graphic icons in math (I believe successfully!) to explain Sensitive Couture (change in clothing with respect to change in mouse interaction):

Nobuyuki's emoji math

Update: I’m now hosting this style package on github.

Continuously refresh markdown output

Tuesday, June 17th, 2014

I had a hard time finding a chrome plugin for a rendering markdown which supported LaTeX equations. Instead I’m using multimarkdown which supports equations with mathjax. However, to render the html output I need to open it in Chrome and refresh it when anything changes. So my pipeline looks like:

repeat
  edit .md files
  run multimarkdown command
  open/refresh .html file in chrome
end

I found this nice ruby/applescript script.
I’ve modified it to support markdown files and to run a command when a file changes:

#!/usr/bin/env ruby
# watch.rb by Brett Terpstra, 2011 <http://brettterpstra.com>
# with credit to Carlo Zottmann <https://github.com/carlo/haml-sass-file-watcher>

trap("SIGINT") { exit }

if ARGV.length < 2
  puts "Usage: #{$0} watch_folder keyword command"
  puts "Example: #{$0} . mywebproject"
  exit
end

dev_extension = 'dev'
filetypes = ['css','html','htm','php','rb','erb','less','js','md']
watch_folder = ARGV[0]
keyword = ARGV[1]
command = ARGV[2]
puts "Watching #{watch_folder} and subfolders for changes in project files..."

while true do
  first = true
  while true do
    files = []
    filetypes.each {|type|
      files += Dir.glob( File.join( watch_folder, "**", "*.#{type}" ) )
    }
    new_hash = files.collect {|f| [ f, File.stat(f).mtime.to_i ] }
    hash ||= new_hash
    diff_hash = new_hash - hash
    if not diff_hash.empty?
      if first and not command.empty?
        val=`#{command}`
        first = false
      else
        break
      end
    else
      sleep 1
    end
  end


  unless diff_hash.empty?
    hash = new_hash

    diff_hash.each do |df|
      puts "Detected change in #{df[0]}, refreshing"
      %x{osascript<<ENDGAME
            tell application "Google Chrome"
    set windowList to every window
    repeat with aWindow in windowList
        set tabList to every tab of aWindow
        repeat with atab in tabList
            if (URL of atab contains "#{keyword}") then
                tell atab to reload
            end if
        end repeat
    end repeat
        end tell
ENDGAME
}
    end
    sleep 1
  end

end

Save this in a file watch.rb and then call with something like:

watch.rb . readme "multimarkdown readme.md -o readme.html"

Tricking latexmk into using -draftmode

Thursday, June 12th, 2014

A friend recently showed me latexmk, an alternative to my current setup of using make to compile complicated tex documents (calling bibtex and pdflatex). Latexmk seems cool because it’s really tracking all the dependencies and not just recompiling everything. However, it seems to always run pdflatex in “final draft” mode, even for early passes which might as well use the -draftmode option. On my thesis (218 page document with figures on roughly every other page), this meant latexmk took 50s and my makefile routine took 23s (assuming a cold start).

I guess the sad answer is that it’s impossible to know if the current run of pdflatex should be the last (and hence should not be using -draftmode). So I guess latexmk plays it safe and runs everything without -draftmode.

My makefile assumes that I only ever need 3 passes, which I guess is pretty common but by no means universal.

I came up with gnarly alternative, which almost needs a makefile itsel:

latexmk -f -pdf -pdflatex="touch thesis.pdf && pdflatex -draftmode" thesis.tex && rm thesis.pdf && latexmk -pdf thesis.tex

First it runs latexmk forcing pdflatex to use -draftmode, but also always touching the pdf so latexmk is convinced that it succeeded in making its targets, then before running a final pass with latexmk I need to remove the pdf so that latexmk thinks there’s something to do. Draftmode passes cost very little so this also runs at about 24s on my thesis.

Wonder if there’s a cleaner way. Especially if thesis.pdf could be inferred nicely from thesis.tex (I guess using basename) and whether I can safely wrap this into an alias:

alias latexmk="..."

Update: Here’s a better version, my friend came up with. It still needs the tex filename twice, but at least it’s using substitution in the pdflatex “command” and the -g option forces latexmk to run at least once.

latexmk -f -pdf -pdflatex='pdflatex -draftmode %O %S && touch %D' thesis && latexmk -pdf -g thesis