LaTeX Syntax 1.0

Version 60.4 by Manuel Leduc on 2022/01/31 00:18
Warning: For security reasons, the document is displayed in restricted mode as it is not the current version. There may be differences and errors due to this.

cogLaTeX 1.0 Syntax Renderer
TypeJAR
CategorySyntax
Developed by

Vincent Massol, Thomas Mortagne

Active Installs109
Rating
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)
    • resourceConverter: Converts ResourceReference objects.
      • Copy a resource to the LaTeX zip: $latex.resourceConverter.convert(...).
      • Add a resource to the LaTeX zip: $latex.resourceConverter.store(...).
  • 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.

UI Extension Points

Latex 1.16+ 

UIXPs are now available for all template kinds, in a generic way. See Template Mechanism. The * in the document UIXPs must be replaced by the <simple name of Block> of the desired kind.

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. Thus 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 doc 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 you may want to add specific support for a given macro. You can do so by providing a new template with your macro name in latex/macros/<macro name> (e.g. latex/macros/video).

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}

Headings

Headings are numbered by default in the generated LaTeX export. 

XWiki 1.14+ 

It's possible to avoid numbering of a specific heading by setting the data-xwiki-rendering-protected parameter on the heading block (or on a wrapping group block). For example:

(% data-xwiki-rendering-protected='true' %)
= heading A =

or

(% data-xwiki-rendering-protected = 'true' %)(((
= heading A =
)))

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

Coding Examples

In order to generate a full LaTeX document, you can use the latex/1.0 BlockRenderer, as in (example in Java):

@Inject
@Named("xwiki/2.1")
private Parser xwiki21Parser;

@Inject
private SyntaxRegistry syntaxRegistry;

@Inject
@Named("latex/1.0")
private BlockRenderer latexBlockRenderer;

...

DefaultWikiPrinter printer = new DefaultWikiPrinter();
Syntax latexSyntax = new Syntax(new SyntaxType("latex", "LaTeX"), "1.0");
XDOM xdom = xwiki21Parser.parse(new StringReader(text));
latexBlockRenderer.render(xdom.getChildren(), printer);

You can also generate a LaTeX fragment instead of a full document, using the latex+fragment/1.0 syntax, as in (example in Velocity):

{{velocity}}
#set ($xdom = $services.rendering.parse('hello **world', 'xwiki/2.1'))
{{{$services.rendering.render($xdom, 'latex+fragment/1.0')}}}
{{/velocity}}

Failed to execute the [include] macro. Cause: [Cannot find section [HReleaseNotes] in document [extensions:Extension.LaTeX.WebHome]]. Click on this message for details.

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).

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.15):

Tags:
    

Get Connected