Recent Changes - Search:

Cookbook

PmWiki

pmwiki.org

TrueLatex

Summary: Enables interpretation and rendering of real LaTeX markups in PmWiki. Support for XeLaTex included in v1.8.
Version: 2.0
Prerequisites: pmwiki-2.0.0 + A LaTeX compiler ('pdflatex' OR 'latex'+'dvipdf' OR 'xelatex' OR an external compiler) + 'convert' (ImageMagick) utility installed on server/host machine
Status: Working perfectly. Very simple to use, customizable and comes with lots of options.

Live Demonstration: http://fling.seas.upenn.edu/~subhrabh/cgi-bin/wiki/index.php?n=Projects.ITPmWiki-LaTeXinPmWiki

Maintainer: Subhrajit
Discussion: TrueLatex-Talk

Questions answered by this recipe

Q: Can I use LaTeX markups/commands in PmWiki pages?

A: Yes! You can, using this 'TrueLatex' recipe. It is as simple as writing your latex code inside the (:latex:) ... (:latexend:) markups. The recipe generates the latex formula as an image and displays it in place of the (:latex:) ... (:latexend:) wiki-text. One can use a shorthand notation as well: ($ ... $).

Description

With TrueLatex recipe, one can make PmWiki interpret, render and display latex formulae by placing the original LaTeX code inside the (:latex:) ... (:latexend:) wiki markup. The recipe generates the latex formula as an image and displays it in place of the (:latex:) ... (:latexend:) wiki-text. One can use a shorthand markup as well: ($ ... $).

TrueLatex relies on a LaTeX compiler (either 'pdflatex', OR 'latex' along with 'dvipdf', OR 'xelatex') utility installed on the server/host machine. Hence it generates "true" LaTeX-compiled formulae as one would expect upon rendering a proper TEX document using 'pdflatex' or 'latex'+'dvipdf' or 'xelatex' utility. This recipe makes use of LaTeX and ImageMagick utilities installed on the server to enable interpretation and rendering of LaTeX commands in PmWiki and display them as images.

Notes

For a live demonstration visit http://fling.seas.upenn.edu/~subhrabh/cgi-bin/wiki/index.php?n=Projects.ITPmWiki-LaTeXinPmWiki .

Syntax (things within square brackets are optional):

     (:latex [DisplayCode[+] = true|false]
              [Verbose = true|false]
               [ForceRender = true|false]
                [ClearCache = true|false] 
                 [... template parameters ...] :)
        <Your LaTeX Code (with proper '$' or 'equation' environments) goes here>
     (:latexend:)

Shorthand: In v1.8 a shorthand notation is introduved to invoke truelatex without any options. The shorthand is:

      ($ <Your latex code without the dollars> $)

For example one can write ($\sum_{k=0}^N 2^k = 2^{N+1} - 1$).

[Note: Verbose option has been superseded by $TrueLatex->AutoVerbose variable since v1.7]

The recipe makes use of a cache, thus avoiding the expensive task of re-rendering every time a LaTeX snippet is requested. Every time TrueLatex attempts to render a LaTeX formula it first creates a md5 hash of the LaTeX code concatenated with template parameters, and searches the cache for any image with name same as the md5 string. If it finds such an image, the image in the cache is used (unless ForceRender is turned on), otherwise it renders the image using pdflatex and convert utilities and then stores the produced image in the cache with the md5 string as its filename for future use.

Debugging the LaTeX code is made easy using the 'Verbose' option, which displays the output returned by the 'pdflatex' (or 'latex' + 'dvipdf') command right on the wiki page. The latex code can also be printed along with the image of the formula and the outputs.

One can edit the TEX template used for rendering the equations, add packages, change style & class files, add parameters/placeholders, etc. This gives complete customizability of the recipe. Also, the images of the latex equations are identified by a unique CSS class so that the images can be stylized at will using CSS style sheet.

Clearing the cache is as simple as setting the 'ClearCache' option to true for any (:latex:) markup, followed by loading the page once.

Dependencies: Before you can install and use TrueLatex with PmWiki, your server/host need to have the following command-line utilities:

  • pdflatex OR latex & dvipdf OR xelatex: This utility is used to interpret and parse the LaTeX commands and create a PDF from it. You either need 'pdflatex' or you need 'latex' along with 'dvipdf'. In version 1.8 support for 'xelatex' has also been included.
    To check if pdflatex is installed, just type 'pdflatex' in a terminal. Ubuntu Linux hosts can simply install the following packages to make this work: 'tetex-base', 'tetex-bin', 'tetex-extra', 'latex-ucs'
    To check if latex & dvipdf are installed, type 'latex' followed by 'dvipdf' in a terminal.
  • convert : This utility is a part of the ImageMagick package. It is used to extract and trim the content of the PDF generated by pdflatex into a PNG file (or any other image format) that can be embedded in PmWiki. To check if the utility is installed, just type 'convert' in a terminal. Ubuntu Linux hosts can simply install the 'imagemagick' package for installing the utility.


Installation

  1. Make sure a LaTeX compiler (either 'pdflatex' OR 'latex' along with 'dvipdf' OR 'xelatex') and the 'convert' command-line utility are installed on the server and can be run by the user running Apache/PHP (generally 'root'). [See Notes above.]
  2. Download TrueLatex-latest.zipΔ(check file consistency) and unzip it. The archive contains a single 'TrueLatex' folder.
  3. Copy this entire TrueLatex folder (inside the TrueLatex-latest.zipΔ archive) into the /cookbook folder (so that the contents of the 'TrueLatex' folder are inside folder /cookbook/TrueLatex/ ).
  4. In /local/config.php add the line include_once('cookbook/TrueLatex/truelatex.php');

Note: By default 'pdflatex' is the utility used by TrueLatex for compiling the LaTeX code to PDF. If you want to use 'latex'+'dvipdf' instead, you'll need to add the following line in config.php: $TrueLatex->RenderMethod = "latex-dvipdf:convert";. In version 1.8 support for XeLaTex has been included (see PHP variables below).


Use

Syntax:

     (:latex [DisplayCode[+] = true|false]
              [Verbose = true|false]
               [ForceRender = true|false]
                [ClearCache = true|false] 
                 [... template parameters ...] :)
        <Your LaTeX Code (with proper '$' or 'equation' environments) goes here>
     (:latexend)

[Note: The Verbose option has been superseded by $TrueLatex->AutoVerbose variable since v1.7]

Shorthand: In v1.8 a shorthand notation is introduved to invoke truelatex without any options. The shorthand is:

      ($ <Your latex code without the dollars> $)

For example one can write ($\sum_{k=0}^N 2^k = 2^{N+1} - 1$).

Basic Usage:

The TrueLatex utility can be invoked using the (:latex:) ... (:latexend:) markup

Examples:
      (:latex:)
      \begin{equation}
         \prod_{n=2}^N\frac{n}{n-1} = N
      \end{equation}
      (:latexend:)

      This is inline (:latex:)$ \epsilon < 10^{-10} $(:latexend:) latex equation

      This is also inline ($(a+b)^2 = a^2+2ab+b^2$), but in shorthand.

Understanding the cache:

Every time TrueLatex attempts to render a LaTeX formula it first creates a md5 hash of the LaTeX code concatenated with template parameters, and searches the cache for any image with name same as the md5 string. If it finds such an image, the image in the cache is used (unless ForceRender is turned on), otherwise it renders the image using Latex compiler and convert utilities and then stores the produced image in the cache with the md5 string as its filename.

Markup options

Option Description Default
DisplayCode Displays the LaTeX code instead of displaying the rendered image. Set the 'displaycode' option to 'true' in the (:latex:) markup. false
DisplayCode+ Displays the LaTeX code in addition to displaying the rendered image. Set the 'displaycode+' option to 'true' in the (:latex:) markup. false
Verbose Displays output returned by the pdflatex (or the 'latex'+'dvipdf' if you are using that instead) and convert utilities and makes special note for error, if any. Useful for debugging LaTeX code. Set the 'verbose' option to 'true' in the (:latex:) markup.

NOTE: Turn on the ForceRender option along with Verbose to invoke the pdflatex and convert utilities even if rendered image exists in cache.
Note: Verbose option has been superseded by $TrueLatex->AutoVerbose variable since v1.7. If $TrueLatex->AutoVerbose is set to true (which is so by default), then the Verbose markup option will have no effect. AutoVerbose turns on verbose mode automatically if the viewer has edit permission and a render was attempted for a formula.

false
ForceRender TrueLatex may be made to render a formula forcefully even if it exists in the cache. Set the 'forcerender' option to 'true' in the (:latex:) markup.

NOTE: ForceRendering is not required to display updated LaTeX code. Changes in LaTeX code are detected automatically and will be rendered even without ForceRender turned on. One use of ForceRender is in conjuncture of 'Verbose' option

false
ClearCache To completely clear the cache simply set the 'ClearCache' option to true for any (:latex:) markup, and load the page once. The loading may take a while if the cache contains a large number of files. After the loading is done, the cache will contain only the re-rendered images corresponding to the markups following the last one on the page with ClearCache=true and itself. Set the 'clearcache' option to 'true' in the (:latex:) markup.

IMPORTANT: Remember to turn off ClearCache after its job is done. Having ClearCache turned on will result in clearing of the cache every time the page loads, and hence re-rendering of all the other deleted images. This significantly slows down the server.

false

Debugging suggestion: Set 'displaycode+=true' and 'verbose=true' while debugging your LaTeX code

template parameters (for template placeholders)
paperwidth, paperheight, eqncounter, fontsize
Values for placeholders in the TEX template can be directly passed on from the markup. For example, in the 'default.tmpl' template that comes with the package, there are placeholders <$-paperwidth-$>, <$-paperheight-$>, <$-eqncounter-$> and <$-fontsize-$>. The default values of these placeholders are defined to be "10", "5", "0" and "Large" respectively in 'truelatex.php' (can be defined in 'config.php' as well - discussed later). But in a particular instance of the markup inside wiki-text the default value can be over-written as follows:
      (:latex paperwidth=8 paperheight=12 fontsize=Huge ::eqncounter++:)
      \begin{equation}
         \prod_{n=2}^N\frac{n}{n-1} = N
      \end{equation}
      (:latexend:)

In the above example, for the particular Latex equation, the rendering will be performed in a different page size (see Comment by Trevor) and the font size will be Latex Huge instead of the default Large. Moreover the eqncounter (for equation numbering) gets incremented by 1 in the global scope of the parameter (denoted by the prefix '::').

Assignment syntax: Parameter values can be set using the "=" operator. Numeric (integer) parameters can be incremented or decremented using "++" and "--" respectively. One can also use the "+=" and "-=" operators to add to or subtract from numeric parameters.

Scope: There are two possible scopes for the template parameter values:

  1. Local to the formula - By default a parameter value is set in the local scope (i.e. setting fontsize=Huge will effect the font size of the particular equation only and not the subsequent ones).
  2. Global to the wiki-page - A parameter value can be changed/set in the global scope of the wiki-page by using a "::" prefix before the parameter name (i.e. setting ::eqncounter++ will increase the eqncounter in the page. Thus the subsequent equations will have their numbers increased by 1).

Notes: i. It is possible to create custom placeholders in the template file (described in Customization section). ii. Upon changing the value of a template parameter for a formula, it will be automatically re-rendered.

The out-of-the-box template parameters and their default values:

 paperwidth = 10
 paperheight = 5
 fontsize = Large
 eqncounter = 0

New template parameters and the default values for them can be defined in config.php (see Customization section).

If you intend to make basic use of the recipe, you can skip the advanced features below and jump to the Troubleshoot section.

Customization:

Template:

The template used for generating the TEX files is by default set as 'default.tmpl' in the TrueLatex folder. One can edit the template file to suit ones needs. The <$-Body-$> placeholder is where all the LaTeX codes get in. It is presently the only mandatory placeholder.

Adding placeholders in template file: It is possible to add new placeholders in the template file. For example, in the very first line of the template file, \documentclass[12pt]{report}, one can choose to replace the value "12" by a placeholder "<$-fontpoint-$>". For adding new placeholders you'll need to:

  1. Edit the template file (default.tmpl) to include the placeholder in the desired place. Placeholders are of the format <$-PlaceholderName-$>.
  2. In config.php define the default string value of the placeholder:
    $TrueLatex->TemplateParams['PlaceholderName'] = "Placeholder default value string";
    Make sure you declare all the used placeholders except Body and Header.
  3. In a (:latex:) markup you can now define values for the placeholders using the format (:latex PlaceholderName=PlaceholderValue:). Numerical (integer) values can be incremented/decremented using "++", "--", "+=" and "-=" operators (e.g. PlaceholderName++, PlaceholderName+=5). The values can be made to change in the global context of the wiki-page by preceding the parameter name by a "::" (e.g. ::PlaceholderName=PlaceholderValue)

Style/package/class files: Upon editing 'default.tmpl', if you use a new/custom style/package/class file, you'll need to ensure:

  1. All the required dependency files are present in the $TrueLatex->TemplateStyleFolder (by default /cookbook/TrueLatex/) folder
  2. The file names are declared in the array $TrueLatex->StyleFile

New template file: If you use a different template file, you'll need to:

  1. Place the template file under $TrueLatex->TemplateStyleFolder (by default /cookbook/TrueLatex/) folder
  2. Set the value of $TrueLatex->TemplateFile to indicate the new file

PHP variables

The following variables can be set in config.php

VariableDescriptionDefault
$TrueLatex->AutoVerboseTurns on verbose mode for a formula automatically if the viewer has edit permission and a render was attempted for the formula. Note: This variable has superseded the inline markup option 'Verbose' since v1.7. If $TrueLatex->AutoVerbose is set to true, the 'Verbose' markup option will have no effect.true
$TrueLatex->CodeFolderFolder containing the truelatex.php file$FarmD.'/cookbook/TrueLatex/'
$TrueLatex->CacheFolderThe cache folder$FarmD.'/pub/latexcache/'
$TrueLatex->CacheURLThe URL using which the cache folder contents can be accessed by the world$PubDirUrl.'/latexcache/'
$TrueLatex->TemplateStyleFolderThe folder containing the template and style files$FarmD.'/cookbook/TrueLatex/'
$TrueLatex->TemplateFileThe name of the template file"default.tmpl"
$TrueLatex->StyleFileAn array containing names of the style/class/package files used in the template filearray("geometry.sty")
$TrueLatex->TemplateParamsDeclaration of the placeholders used in the template along with their default valuesarray( 'paperwidth'=>"10", 'paperheight'=>"5", 'fontsize'=>"Large", 'eqncounter'=>"0" )
$TrueLatex->RenderMethodThe method to use for rendering Latex formula. Available values:
a. "pdflatex:convert" - use 'pdflatex' and 'convert' utilities
b. "latex-dvipdf:convert" - use 'latex', 'dvipdf' and 'convert' utilities
c. "xelatex:convert" - use 'xelatex' and 'convert' utilities
d. "xelatex-xdvipdfmx:convert" - use 'xelatex', 'xdvipdfmx' and 'convert' utilities
e. "phpfun-foo:convert" - A custom PHP function, 'foo', is used for parsing the LaTeX code. 'convert' used for image extraction. See the 'Custom PHP function for Latex render' section for more details.
"pdflatex:convert"
$TrueLatex->OutImageExtExtension/format of the output image filepng
$TrueLatex->EnableShorthandA boolean variable indicating whether or not to enable the shorthand markup.true
$TrueLatex->UsePDFColorsIf set to true, 'BackgroundColor' and 'FontColor' (see next) won't have any effect. The original colors rendered by Latex parser will be used.false
$TrueLatex->BackgroundColorThe background color for the rendered images. Can be "transparent" or a hexadecimal RGB value string (e.g. "ff8a6b")"transparent"
$TrueLatex->FontColorThe color for the font used in the formulae. Can be null or a hexadecimal RGB value string (e.g. "ca3bff")null

Custom PHP function for Latex render

Sometimes one may need to use unconventional methods for rendering the LaTeX formula instead of using the server-side LaTeX parser via PHP's shell_exec function. One, for example, may need to use an external server/website to parse the LaTeX code when there is no parser installed on the native server. This can be achieved by setting   $TrueLatex->RenderMethod = "phpfun-myCustomFunction:convert";   in config.php, where myCustomFunction is a custom PHP function (defined in config.php or any of the scripts that it includes) that is called by TrueLatex with appropriate parameters. The function needs to be of the format

    myCustomFunction($dirname, $filename)

which takes in two parameters:

  1. $dirname is the complete path to the temporary folder where the .tex file with the LaTeX code can be found, and,
  2. $filename is the name of the temporary .tex file (without the .tex extension).

The function should create a PDF file in the same path as $dirname, and with same name as $filename (but with .pdf extension), that contains the rendered formula. It can return a string that will be printed in verbose mode.

The following function is an example that creates the required PDF by using the online LaTeX parser provided at http://latex.informatik.uni-halle.de/(approve links) (WARNING: Your use of this function and the service provided by uni-halle.de is subject to your acceptance of their terms and conditions. This function is a demonstration, and is not meant for use in live web-sites.)

function myCustomFunction($dirname, $filename)
{
    $ret = "";
    $url = "http://latex.informatik.uni-halle.de/latex-online/";

    $webpageXML = file_get_contents($url."latex.php?spw=2");
    $foundid = preg_match("/<input.*?name=\"id\".*?value=\"(.*?)\".*?>/is", $webpageXML, $idmatch);
    if (!$foundid) {
        $ret .= "Could not find ID field in form at $url"."latex.php?spw=2\n";
        return $ret;
    }
    $id = $idmatch[1];
    $ret .= "ID assigned by $url: ".$id."\n\n";

    $postdata = http_build_query(array(
                    'spw' => "2",
                    'id' => $id,
                    'finit' => "nothing",
                    'quellcode' => file_get_contents($dirname.$filename.".tex"),
                    'aformat' => "PDF",
                    'compile' => "Compile"
                ) );
    $opts = array( 'http'=>array(
                                 'method' => "POST",
                                 'header' => "Content-type: application/x-www-form-urlencoded",
                                 'content' => $postdata  )  );
    $context = stream_context_create($opts);
    $ret_content = file_get_contents($url."latex.php", false, $context);

    $foundresponse = preg_match("@<textarea.*?readonly.*?>(.*?)</textarea>@is", $ret_content, $response);
    $ret .= $response[1]."\n";
    $foundpdfurl = preg_match("/href=\"(.*?".$id."\\.pdf)\"/is", $ret_content, $pdfurl);
    if (!$foundpdfurl) {
        $ret .= "The URL to the PDF file not found.\nDebug info: \n".htmlspecialchars($ret_content);
        return $ret;
    }
    $ret .= "PDF URL: ".$pdfurl[1]."\n";
    copy($pdfurl[1], $dirname.$filename.".pdf");

    return $ret;
}

 

CSS classes

The formula image, the displayed code and the output (in verbose mode) are generated as HTML elements with specific class names. You can use CSS style definition for those classes to customize the appearance of the image/codes/outputs. The class names are:

  • TrueLatexImage - Class for the <img> tag of the displayed Latex formula
  • TrueLatexCode - Class for the <div> tag of the displayed Latex code (in DisplayCode mode)
  • TrueLatexOutput - Class for the <div> tag of the displayed output (in Verbose mode)


Troubleshoot and FAQ

Q: pdflatex not found, not installed or cannot be run:
A: Try 'latex'+'dvipdf' instead. In config.php add the line $TrueLatex->RenderMethod = "latex-dvipdf:convert";. If even this is not found/not installed, you'll need to install at least one of the supported LaTeX compilers. More details in the Notes section.
Alternatively, you may try the custom PHP function for Latex render feature added in v2.0.

Q: My server/host is running on Fedora / Red Hat Enterprise Linux. TrueLatex does not work on this server!
Q: SELinux prevents execution of system commands due to security reasons.
A: You might have SELinux turned on, and "httpd_ssi_exec" turned off. This prevents PHP from executing the pdflatex (or latex+dvipdf) and convert utilities. For checking if this really is the case, just type "/usr/sbin/getsebool -a | grep httpd" at the commandline in a terminal and check the value of "httpd_ssi_exec" that it prints. Unless you think turning it on will cause a security threat to your system, you can permanently turn it on by executing "setsebool -P httpd_ssi_exec 1;" at the terminal. (More details at http://php.net/manual/en/ref.exec.php).

Q: PHP cannot run/call shell_exec function.
Q: No specific error message printed by TrueLatex in verbose mode (other than "ERROR in parsing LaTeX!"), but rendering not happening!
A: Check the following possibilities:

  1. PHP might be running in SafeMode. Open the php.ini file and check if there is a line "safe_mode = On" in it. If that's the case, change it to "safe_mode = Off".
  2. The 'shell_exec' function of PHP might be disabled. To check this, open the php.ini file and check if there is a line "disable_functions=...", and if 'shell_exec' is in that list. If yes, just remove 'shell_exec' from that list.

Q: The formula image gets truncated at the bottom or on the right:
A: The page size of the template file is small for the formula you are trying to render. Try setting higher values for paperwidth and paperheight parameters: (:latex ... paperwidth=15 paperheight=8:) ... (:latexend:). (The default values of these two parameters are 10 and 5 respectively - units in inches)

Q: I expected the formula image to change/be re-rendered since I changed something. But it does not get updated!
A: Try setting ForceRender = true once for the formula. That should re-render it. Then remember to turn off ForceRender.

Q: The background color of my wiki pages are not white. How can I set the background color of the formula images to match my site's background.
Q: I need to specify the color for the fonts in the formulae to match my wiki's color template.
A: Since version 1.9 the default background is set to transparent, while the font colors are black. You can change these by setting the PHP variables $TrueLatex->BackgroundColor and $TrueLatex->FontColor in config.php.

Q: The text/formulae in the images created by TrueLatex seem to have texts with jagged edges rather than being smooth and nice.
A: This is most likely an issue with the version of imagemagik that your server is using, that handles transparency in a different way than what TrueLatex assumes it does. The easiest workaround to this is to disable transparency: Add the following in your config.php: $TrueLatex->UsePDFColors = true;. Remember to refresh/clear the cache after you make the change.
If you see an error/warning printed by TrueLatex when you use the verbose=true forcerender=true options with a formula, please post that in the TrueLatex-Talk page.



Release notes

2010-01-27: Version 1.1 released. Minor edits. Placement of PNG images in text for inline formula fixed.

2010-02-15: Version 1.5 released. Version summary:

  1. Besides 'pdflatex', now support of 'latex' & 'dvipdf' are included. Thus, a server having 'latex' & 'dvipdf' installed, but not 'pdflatex', can also use this recipe.
  2. Error messages displayed in Verbose mode are more extensive and diagnostic. The messages include system error messages as well.
  3. Support for customizable parameters in the TEX template included. Default parameter values can be set in config.php and for individual renders the value can be passed on from the markup's options (see Customization for details).
  4. Installation is made simpler by automating the process of creating the '/pub/latexcache' folder and setting permission for it.

2010-02-17: Version 1.6 released. Minor fixes made. Global & local scope of template parameters defined.

2010-03-31: Version 1.7 released. AutoVerbose introduced.

2010-07-21: Version 1.8 released. Shorthand markup introduced. Support for XeLaTex included.

2011-09-06: Version 1.9 released. PHP variables $TrueLatex->BackgroundColor and $TrueLatex->FontColor introduced. Transparent background introduced.

2012-05-10: v1.92 released. Additional diagnostic outputs if file/folder couldn't be created. PHP variable $TrueLatex->UsePDFColors introduced.

2012-07-05: v2.0 released. "phpfun-foo:convert" RenderMethod introduced. Some standard packages included in default.tmpl.

See also

Cookbook /
AMmathjax  Add markup to embed math using ASCII MATH by MathJax. (Stable)
ASCIIMath  Display MathML rendered ascii formula into PmWiki 2.x pages (Stable)
Formula  Lightweight rendering of mathematical formulas in wiki pages (Beta)
JsMath  Add markup to display and embed mathematical formulas in wiki pages using TeX. (Obsolete - use MathJax)
LaTeXMathML  Translating LaTeX math notation dynamically to Presentation MathML (Stable)
LinuxTex  Enable TeX markup
LuaExecute  Lets Lua scripts dynamically generate parts of your wiki page (Beta)
MathJax  Add markup to embed math using TeX syntax. (Stable)
Mathtex  Add markup to display and embed several lines of mathematical formulas in wiki pages (testing)
MimeTeX  Add markup to display and embed mathematical formulas in wiki pages (Stable)
SageCell  This allows you to embed an interactive SageCell into your webpage. Sage is an open source alternative to MathLab, Mathematica, and Maple. (Stable)
SimpleJsMath  

Contributors

Comments and Discussions

Please use the TrueLatex-Talk page for comments and discussions.


User notes? : If you use, used or reviewed this recipe, you can add your name. These statistics appear in the Cookbook listings and will help newcomers browsing through the wiki.

Edit - History - Print - Recent Changes - Search
Page last modified on October 09, 2012, at 04:34 PM