cogLaTeX 1.0 Syntax Renderer
TypeJAR
CategorySyntax
Developed by

Vincent Massol, Thomas Mortagne

Active Installs4
Rating
Rate!
0 Votes
LicenseGNU Lesser General Public License 2.1
Compatibility

Since v1.5 requires XWiki 10.2RC1

Installable with the Extension Manager

Description

Generates LaTeX syntax, based on a system of templates which can be overridden.

In general you'd call the LaTeX syntax Renderer through the LaTeX Exporter.
Note that the renderer can only be used as org.xwiki.rendering.renderer.BlockRenderer right now.

Template Mechanism

When an XDOM is rendered, for each Block inside the XDOM, a template is looked up and that template contains the LaTeX commands to generate. The default templates are located as ClassLoader resources under latex/default/<simple name of Block>. For example the template for a WordBlock is located under latex/default/WordBlock. The template for the XDOM itself (which corresponds to the document) is located under latex/default/XDOM.

The templates are searched for using the following algorithm:

  • If the current skin is defined in a wiki page (in a XWiki.XWikiSkins xobject) then in an xproperty named latex/<simple name of Block>. See the Skin application for more details on how to add a template to the current skin.
  • If the current skin is defined on the filesystem, in a file in <skin name>/latex/<simple name of Block>.
  • If not found in the skin, then in the ClassLoader under latex/<simple name of Block>. This means you can drop overriding templates in WEB-INF/classes for example.
  • If not found, then in the ClassLoader under latex/default/<simple name of Block>.

Template Overrides

All the standard bindings that you can use in a script inside wiki pages are available to your templates when you write them as xproperties of XWiki.XWikiSkins xobjects.

In addition the following bindings are also available:

  • latex: Provides special APIs related to the LaTeX rendering:
    • latex.tool: Utilities
      • Escape special characters in LaTeX: $latex.tool.escape("content to escape")
      • Get the current language as a displayable string: $latex.tool.language. For example for en_US you get "English".
    • latex.block: The current block being rendered
    • latex.processor: Tool to tell to process the children block and to retrieve content of a specific Template or to render it.
    • latex.properties: Configuration properties for the export:
      • latex.properties.documentClass: the documentClass to use
      • latex.properties.coverPage: if true then a cover page should be generated
      • latex.properties.pageNumbering: if true then page numbers should be displayed
      • latex.properties.toc: if true then a TOC should be inserted
      • latex.properties.listOfFigures: if true then a list of figures should be inserted
      • latex.properties.listOfTables: if true then a list of tables should be inserted
      • latex.properties.title: the title of the export (used on the cover page if not empty)
      • latex.properties.subtitle: an optional subtitle for the export (used on the cover page if not empty)
      • latex.properties.author: the author of the export (used on the cover page if not empty)
      • latex.properties.date: the date of the export (used on the cover page if not empty)
  • SP: A special binding that represents a space character. Useful when you want to insert a leading space as leading spaces are trimmed by default in templates.

Best Practices

If you override a template you need to think about future upgradability. A best practice is to only replace the part of the template that you need and keep the rest coming from the default template that you're overriding. This can be achieved by using the $stringtool Velocity binding.

The general strategy is:

## Step 1: Get the default template that you're overriding
#set ($template = $latex.processor.getTemplate('default/<template name here>'))
## Step 2: Compute the new content
#set ($newContent = $stringtool.<replace/replaceAll/replacePattern/...(...)>)
## Step 3: Set the new content
#set ($discard = $template.content.setContent($newContent))
## Step 4: Render the modified template
$latex.processor.render($template)##

See below for some examples.

Examples

Table cells in italic

Put the following in a latex/TableCellBlock template:

## If we're not on the last cell of the row then end with a "&"
#set ($currentCellBlock = $latex.block)
\textit{${latex.processor.process($latex.block.getChildren())}}##
#if ("$!currentCellBlock.getNextSibling().class.getSimpleName()" == 'TableCellBlock' || "$!currentCellBlock.getNextSibling().class.getSimpleName()" == 'TableHeadCellBlock')
 & ##
#end

Wrapping table cells

Imagine that you have the following table in xwiki/2.1 syntax, with a cell containing a lot of text:

| cell 1 | cell 2 | Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard de l'imprimerie depuis les années 1500, quand un peintre anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique, sans que son contenu n'en soit modifié. Il a été popularisé dans les années 1960 grâce à la vente de feuilles Letraset contenant des passages du Lorem Ipsum, et, plus récemment, par son inclusion dans des applications de mise en page de texte, comme Aldus PageMaker.
| cell 3 | cell 4 | cell 5

If you render this in LaTeX with the default templates and then convert to PDF you'll get:

table-wrap-bad.png

This isn't nice. LaTeX doesn't support automatic layout of tables. This we need to tell LaTeX how we want to layout our 3rd column. One solution is to introduce a custom template for this table. Let's name it CustomTableBlock. Then make sure you use it for this table:

(% latex-template="CustomTableBlock" %)
| cell 1 | cell 2 | Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard de l'imprimerie depuis les années 1500, quand un peintre anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique, sans que son contenu n'en soit modifié. Il a été popularisé dans les années 1960 grâce à la vente de feuilles Letraset contenant des passages du Lorem Ipsum, et, plus récemment, par son inclusion dans des applications de mise en page de texte, comme Aldus PageMaker.
| cell 3 | cell 4 | cell 5

Then edit your current skin and add a latex/CustomTableBlock template with the following content:



#set ($tableSpec = "|l|l|p{0.6\linewidth}")
\begin{center}
\begin{tabular}{${tableSpec}}
\hline
$latex.processor.process($latex.block.getChildren())##
\end{tabular}
\end{center}##

Now, when you export in LaTeX and then convert to PDF you get this:

table-wrap-good.png

Much nicer! See this donc on LaTeX tables for more information.

Add a package

For example imagine you wish to add the tabu package for tables. You'll need to override the default latex/default/Preamble template by putting the following in a latex/Preamble template:

#set ($template = $latex.processor.getTemplate('default/Preamble'))
$latex.processor.render($template)
%% For nice tables!
\usepackage{tabu}##

Replace a package

For example the following replaces \usepackage{amsmath} with \usepackage{amsmath, amsthm, amssymb, amsfonts}. Put the following in a latex/Preamble template.

## This is testing an override showing how to replace some default content with some other content
## Step 1: Get the default template
#set ($template = $latex.processor.getTemplate('default/Preamble'))
## Step 2: Compute the new content
#set ($newContent = $stringtool.replace($template.content.content, '\usepackage{amsmath}', '\usepackage{amsmath, amsthm, amssymb, amsfonts}'))
## Step 3: Set the new content
#set ($discard = $template.content.setContent($newContent))
## Step 4: Render the modified template
$latex.processor.render($template)##

Note that the Preamble template is a special template called by the XDOM template which does the following:

\documentclass{article}

$latex.processor.render('Preamble')

\begin{document}$latex.processor.process($latex.block.getChildren())

\end{document}

Add support for a new Macro

By default several Macros are already handled but may want to add specific support for a given macro. You could simply overwrite latex/MacroMarkerBlock but you'd need to copy the default content and thus it would be less easy to merge default changes with your own changes when you upgrade the LaTeX Extension. A better solution is to call the default template as in:

#if ($latex.block.id == 'something')
...
#else
$latex.processor.render('default/MacroMarkerBlock')##
#end

Specific Custom Templates

It's possible to use a custom template for a specific Block. For this define a parameter named latex-template. For example imagine that we'd like a given cell in a table to be displayed using the latex/custom/custom1 template. We could write:

|=Head1|=Head2
|cell1|(% latex-template="custom/custom1" %)cell2

Captioned Tables & Images

Since v1.5 You can use the Figure Macro.

Example input in XWiki Syntax 2.1:

See figure {{reference figure="f1"/}}.

{{figure}}
[[image:http://www.clker.com/cliparts/3/m/v/Y/E/V/small-red-apple-md.png||width=100]]

{{figureCaption}}{{id name="f1"/}}An image{{/figureCaption}}
{{/figure}}

See table {{reference figure="t1"/}}.

{{figure}}
|a|b

{{figureCaption}}{{id name="t1"/}}A table{{/figureCaption}}
{{/figure}}

Leads to the following PDF result:

example-figures.png

Image Resizes

The width and height image parameters are supported as follows:

  • Any width specified as a percentage translates into %\linewidth (for example width=50% generates width=0.5\linewidth).
  • Any height specified as a percentage translates into %\textheight (for example height=50% generates height=0.5\textheight which means half the page size in height).
  • Any other unit is translated into pixels. For example width=100 translates into width=100px.

Example:

[[image:whatever||width="100"]]

Generates:

\includegraphics[width=100px]{whatever}

Macros

The following macros have special handling during the export.

TOC

{{toc}}: Generates TOC in LaTeX. 

For example:

= Heading1 =

{{toc scope=local/}}

== Heading2 ==

=== Heading3 ===

{{toc/}}

Generates:

toc.png

Code

{{code}}: Generates colorized code. 

For example:

{{code language="java"}}
public class HelloWorld
{
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
{{/code}}

Generates: 

code.png

Message

{{info}}, {{warning}}, {{error}}, {{success}}: Generate styled boxes. 

For example:

{{info}}info{{/info}}

{{warning}}info{{/warning}}

{{error}}info{{/error}}

{{success}}info{{/success}}

Generates:

messages.png

Formula

{{formula}}: Generate a formula using LaTeX native syntax. 

For example:

Hello {{formula}}\sum_{n=1}^\infty\frac{1}{n^2} = \frac{\pi^2}{6}{{/formula}}

{{formula}}
\sum_{n=1}^\infty\frac{1}{n^2} = \frac{\pi^2}{6}
{{/formula}}

Generates:

formula.png

Id

{{id}}: Generates a LaTeX label.

Footnote

{{foonote}}: Generates a LaTeX footnote.

Reference

{{reference}}: Generate a LaTeX reference (\ref{...}). See Numbered Reference Macro for how to use it.

Container

{{container}}: Generates a multiple columns layout. 

For example:

Hello world

{{container layoutStyle="columns"}}
(((
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vestibulum eros sed lorem laoreet efficitur. Nulla semper luctus sagittis. Cras pretium posuere lacinia. Curabitur finibus at risus eget gravida. Fusce suscipit interdum justo, sit amet volutpat tellus rutrum et. Mauris sed suscipit purus. Sed ultricies mi id dui ullamcorper auctor. Donec imperdiet arcu at tortor consectetur finibus. In viverra maximus massa, non ultrices enim pretium at. Phasellus eu mattis augue. Ut non venenatis metus. Morbi pharetra ipsum ac erat varius tempor.

Aenean facilisis vulputate tortor, non convallis justo efficitur nec. Morbi tristique sapien a turpis malesuada lobortis sit amet lobortis dolor. Quisque consequat ornare enim, ac iaculis elit varius ac. Mauris purus justo, molestie vulputate pharetra vitae, scelerisque quis leo. Nam sed risus a purus lacinia congue. Suspendisse nisl eros, bibendum at nunc eu, semper ullamcorper orci. Nam rhoncus ac sem et venenatis. Pellentesque tincidunt felis eget eros facilisis scelerisque. Nulla porta nisl et diam luctus luctus. Integer at dignissim arcu, ac egestas tellus. Integer hendrerit turpis ligula, vitae ornare enim aliquet sed.
)))
(((
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vestibulum eros sed lorem laoreet efficitur. Nulla semper luctus sagittis. Cras pretium posuere lacinia. Curabitur finibus at risus eget gravida. Fusce suscipit interdum justo, sit amet volutpat tellus rutrum et. Mauris sed suscipit purus. Sed ultricies mi id dui ullamcorper auctor. Donec imperdiet arcu at tortor consectetur finibus. In viverra maximus massa, non ultrices enim pretium at. Phasellus eu mattis augue. Ut non venenatis metus. Morbi pharetra ipsum ac erat varius tempor.

Aenean facilisis vulputate tortor, non convallis justo efficitur nec. Morbi tristique sapien a turpis malesuada lobortis sit amet lobortis dolor. Quisque consequat ornare enim, ac iaculis elit varius ac. Mauris purus justo, molestie vulputate pharetra vitae, scelerisque quis leo. Nam sed risus a purus lacinia congue. Suspendisse nisl eros, bibendum at nunc eu, semper ullamcorper orci. Nam rhoncus ac sem et venenatis. Pellentesque tincidunt felis eget eros facilisis scelerisque. Nulla porta nisl et diam luctus luctus. Integer at dignissim arcu, ac egestas tellus. Integer hendrerit turpis ligula, vitae ornare enim aliquet sed.
)))
{{/container}}

Generates:

container-example.png

Release Notes

All release notes

1.7

  • Closed LATEX-56 Message macros don't support inline usage
  • Closed LATEX-55 Inline code macros not working
  • Closed LATEX-54 New line should not start a new paragraph
  • Closed LATEX-53 xcontext.action doesn't return "latexexport"
  • Closed LATEX-52 Invalid new line "\\" character after id macro
  • Closed LATEX-51 Pages with reserved latex characters in their name generate invalid latex
  • Closed LATEX-50 LaTeX export button text is not consistent with other buttons

1.6

  • Closed LATEX-48 Image path references can cause LaTeX compilation errors
  • Closed LATEX-47 Images in table cells generate invalid LaTeX
  • Closed LATEX-46 Use a more standard way to output empty lines
  • Closed LATEX-45 Images located inside {{context}} macros are not exported
  • Closed LATEX-44 Also escape the ampersand character

1.5

  • Closed LATEX-43 Add support for exporting document using sheets
  • Closed LATEX-41 Exporting a nested page should produce a zip named after the space name
  • Closed LATEX-35 Refactoring the template bindings so that they're all under the same namespace
  • Closed LATEX-34 Remove support for captions and labels as parameters for Image and Table blocks
  • Closed LATEX-33 Ignore generated numbers when the Numbered Reference transformations are used
  • Closed LATEX-32 Add support for the {{figure}} and {{figureCaption}} macros
  • Closed LATEX-31 Generate chapters for top level headings when the document type is a book
  • Closed LATEX-30 Pass the document type to the Syntax Renderer
  • Closed LATEX-24 Add support for the Container macro
  • Closed LATEX-12 Provide Export options in the UI
  • Closed LATEX-11 Contribute a LaTeX export button in the page export dialog box
  • Closed LATEX-9 Allow users to customize the export's index template

1.4

  • Closed LATEX-29 Parameters in a paragraph having an extra new line
  • Closed LATEX-28 Add support for the Reference Macro
  • Closed LATEX-15 Fix attachment link embedding

1.3

  • Closed LATEX-26 The messages macro should support wiki syntax
  • Closed LATEX-25 Implement max image size
  • Closed LATEX-23 Add support for labels for captioned tables and images
  • Closed LATEX-22 Have images centered by default
  • Closed LATEX-21 Supports links to current page when there's no label
  • Closed LATEX-20 Convert any link to the current page to a local link
  • Closed LATEX-18 Ignore leading spaces in templates to make them more readable
  • Closed LATEX-13 Handle resized images
  • Closed LATEX-7 Handle Group Block

1.2

  • Closed LATEX-19 Add support for styles in footnote content

1.1

  • Closed LATEX-10 Add support for footnote macros

1.0

  • Closed LATEX-3 Export entry point for LaTex
  • Closed LATEX-2 Export Filter for LaTeX
  • Closed LATEX-1 LaTeX Syntax renderer based on templates

Prerequisites & Installation Instructions

We recommend using the Extension Manager to install this extension (Make sure that the text "Installable with the Extension Manager" is displayed at the top right location on this page to know if this extension can be installed with the Extension Manager). Note that installing Extensions when being offline is currently not supported and you'd need to use some complex manual method.

You can also use the manual method which involves dropping the JAR file and all its dependencies into the WEB-INF/lib folder and restarting XWiki.

Dependencies

Dependencies for this extension (org.xwiki.contrib.latex:latex-syntax 1.7):

Tags:
Created by Thomas Mortagne on 2018/02/23 16:31
    

Get Connected