Skip to content

Instantly share code, notes, and snippets.

@matshch
Last active August 31, 2020 05:26
Show Gist options
  • Save matshch/bbf1e245dd49b88680e8 to your computer and use it in GitHub Desktop.
Save matshch/bbf1e245dd49b88680e8 to your computer and use it in GitHub Desktop.
Add-on for Anki which properly align LaTeX images
# -*- coding: utf-8 -*-
# Properly align LaTeX images to baseline
# Copyright (c) 2016, Artem Leshchev <[email protected]>
# Improved by Johannes Bechberger <[email protected]>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is furnished
# to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Based on:
# Edit LaTeX generation procedure
# Soren I. Bjornstad <[email protected]>
# add-on Version 2, for Anki 2.0.27+
# I do not think this add-on is really eligible for copyright protection, since
# it simply overwrites a variable in Anki's code, but in case it is, you are
# free to do anything you want with it without needing to ask for permission.
import os, re, shutil, sys
import anki.latex
import anki.media
from anki.hooks import wrap
from anki.utils import namedtmp, tmpdir
newLaTeX = \
[
["latex", "-interaction=nonstopmode", "tmp.tex"],
["dvipng", "-D", "200", "-T", "tight", "-z", "9", "--depth", "-q", "tmp.dvi", "-o", "tmp.png"]
]
def after_buildImg(col, latex, fname, model):
"Save depth info"
oldcwd = os.getcwd()
try:
os.chdir(tmpdir())
with open(namedtmp("latex_log.txt", rm=False)) as f:
for line in f:
match = re.search('depth=(.*)$', line)
if match:
depth = match.group(1)
dat = namedtmp("tmp.dat")
file = open(dat, "w")
file.write(depth)
file.close()
shutil.copyfile(dat, os.path.join(col.media.dir(), fname + ".dat"))
except:
pass
finally:
os.chdir(oldcwd)
imgRegexps = [
# src element quoted case
"(?i)(<img[^>]* src=(?P<str>[\"'])(?P<fname>[^>]+?)(?P=str)[^>]*>)",
# unquoted case
"(?i)(<img[^>]* src=(?!['\"])(?P<fname>[^ >]+)[^>]*?>)",
]
def change_imgLink(col, latex, model, _old):
"Use depth info"
link = _old(col, latex, model)
if link.startswith("<img"):
for reg in imgRegexps:
for match in re.finditer(reg, link):
fname = match.group("fname")
if (not os.path.exists(fname + ".dat")) and anki.latex.build:
txt = anki.latex._latexFromHtml(col, latex)
err = anki.latex._buildImg(col, txt, fname, model)
if err:
return err
try:
depth = open(os.path.join(col.media.dir(), fname + ".dat")).read()
style = ' style="vertical-align: -%spx" src=' % depth
link = link.replace(' src=', style)
except:
link += anki.latex._errMsg("latex", col.media.dir())
return link
def afterFilesInStr(self, mid, string, includeRemote=False, _old=None):
l = _old(self, mid, string, includeRemote)
try:
newl = []
for f in l:
if f.startswith("latex-"):
newl.append(f + ".dat")
return l + newl
except:
return l
# make the changes
anki.latex.latexCmds = newLaTeX
anki.latex._buildImg = wrap(anki.latex._buildImg, after_buildImg)
anki.latex._imgLink = wrap(anki.latex._imgLink, change_imgLink, "around")
anki.media.MediaManager.filesInStr = wrap(anki.media.MediaManager.filesInStr, afterFilesInStr, "around")
@parttimenerd
Copy link

I improved the LaTeX error handling in this gist.

@matshch
Copy link
Author

matshch commented Aug 31, 2020

I improved the LaTeX error handling in this gist.

@parttimenerd, thanks! I incorporated your changes in my gist.

Hello, can you consider incorporating the change made on this gist?

@diego898, I incorporated fixes of @parttimenerd, looks like your fixes had the same idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment