Customizing LyX: An Introduction to Modules

In the past few months, I’ve written several articles about the ways LyX can be customized.  These included a brief introduction to layout files and how they relate to document classes in addition to a tour of character styles and how you can add them to the LyX local layout.  What I have not written about, though, is one of the most important ways of extending LyX, the module.

Ever since version 1.6 of LyX, the core LyX developers have worked very hard to make LyX a modular system.  Instead of hard coding values and options – as they had done previously – they’ve instead placed all of the needed information in configuration files that can be edited and modified by users.  This is a Very Good Thng.  It means that (given enough motivation), you can customize LyX to behave exactly was you wish.  You can change the default document classes, styles, fonts and anything else that your little heart desires.  It also means that any extensions you create will exist as first-class citizens.  They have access to all of the internal wizardry as the default document classes and features.

The last big piece of this transition was the creation of “modules”.  In a lot of ways, you might think of modules as document plugins.  Modules are optional add-ons that you can enable from the “Document Settings” pane.

They let you do things like run Sweave code, add additional theorem environments, or apply a different style to your text.  But unlike a layout file, they are not tied to any particular document class or type; which makes them very powerful.  In fact, nearly all of them they can be used with any document type that LyX supports.

There are two main types of modules:

  1. Modules that contain all of the code needed to implement a particular feature (or modify an existing one) and do not reference external packages.
  2. Modules that load existing LaTeX styles/packages and translate their features into insets, commands and headings.

In both cases, modules serve as a container for the code.  You can use a module to package code that would normally live in a document layout file, or you can use code that might have been placed in the local layout.  The code may be a document header, a new LaTeX command, a character style, a custom inset, or any other type of user customization that LyX supports.

The biggest difference between using a module instead of a layout, of course, is that when the code is placed in a module, you can then add it to any document on your system.  This makes modules a tremendously flexible way to reuse customizations that you’ve created.  In fact, in nearly all cases, they are the best way to package your customizations for use on your own system or for sharing with others.

In this article, I’d like to introduce the module.  I will explain its position in the larger LyX/LaTeX “big picture”, its internal anatomy and provide a few examples of how it can be used to add new features.

The Big Picture: A Refresher Course

Before jumping right into code and detailed specifics, it might be valuable to provide a brief refresher on how LyX and LaTeX work.  Specific examples are always better once you understand the theory.

LaTeX uses several important files.  These are document classes (ending with the extension, .cls) and styles/packages (which end with the extension, .sty).  Classes and styles are what tell LaTeX whether a block of text is a chapter, figure legend, table or footnote.

Likewise, LyX also uses  two main types of configuration files.  These are layout files (which correspond to LaTeX document classes) and modules, which correspond to modules.

A particular document may only use one document class/layout file, but many packages/styles/modules.  As a result, packages/styles/modules become an important way to modify the appearance of a document class or to add additional features such as new float/inset types or headings styles.

Note: Additional Information about how LaTeX and LyX work together can be found in the article, Customizing LyX: Create an NIH Grant Proposal Template.  See the section entitled, “Understanding the Big Picture.”

Anatomy of a Module

There are two items that many LyX modules have in common.  These are:

  • the module declaration and description (mandatory), which give the module a unique name and provide a summary of what the module does, and
  • the “Requires” statement (optional), that specifies which LaTeX packages are needed by the module and prompts for LyX to look for them.

After the “Requires” statement, you include any valid LyX configuration code such as header definitions, character styles, or custom insets.

Module Declaration

The module declaration appears at the very beginning of the module and includes the \DeclardLyXModule command and the module name.  The description then follows, offset by the #DescriptionBegin and #DescriptionEnd tags.  A simple example might have the form:

#\DeclareLyXModule(Module Name)
#DescriptionBegin
#This module provides several unique commands to aid with the typesetting of complex documents.
#DescriptionEnd

All of the commands and commentary in the Module declaration should be preceded by the numeral sign (#).  Any line breaks in the description should also be preceded by the numeral sign.

The “Requires” Statement

The requires statement directly follows the module declaration and description.  In it, you would list any LaTeX pacakges required by that particular module.  The example (which is from the drop caps module discussed below), requires that both the lettrine and the stringstrings packages be installed:

Requires     lettrine,stringstrings

Examples

With the basic anatomy of a module out of the way, it may be helpful to look at two real-world examples.  The first example shows how to create a custom inset and LaTeX command.  It does not require any specialized packages other than those installed in a typical LaTeX distribution.  The second example, however, is slightly more complex.  It shows how to reference external packages, have LyX check whether they are installed and creates a new LaTeX command for automatically generating drop-cap letters.

Longtable Floats

One of the most useful features of LaTeX is the ability to position text, figures and other document objects automatically through the use of floats.  When used correctly, floats can help you to avoid a large number of formatting complications while ensuring that figures are placed in a consistent manner depending on the options that you specify.

But even though they are tremendously useful, floats suffer from one major limitation.  They can’t contain any content that is over a page in length.  While this limitation is very easy to work around for figures, it presents serious complications for tables.  In many types of publications, it is common to include tables that are more than a single page in length.  To include this type of material in LaTeX document, therefore, means that you must position it manually (usually after the document has been completely written).

Excessive manual formatting (sometimes referred to as “finger painting”) is something that you want to avoid when working with LaTeX for both philosophical and practical reasons.  In the first place, it’s completely anathema to the idea of semantic markup.  In the second, trying to manually specify the location of document elements is a great deal of work.

Luckily, it is possible to create a custom LaTeX command that, when used in conjunction with long tables, can  cause them to behave in a manner similar to that of a float.  This command is \afterpage, from the “afterpage” package.  The \afterpage command causes any content in its argument to be expanded after the current page has finished its output.  As a result, \afterpage can be used to float the table to the top of the next page without disrupting the text flow.

Module Code

The longtable module defines a new command that then allows you to use \afterpage within a LyX document.  To make its behavior more consistent with the other floats in LyX (figure, table), it defines a custom inset.  This is what the code looks like:

InsetLayout Custom:Longtable

LyXType                                 custom
Labelstring                             longtable
Decoration                             classic

LabelFont
Color                                  collapsable
Size                                    Small
EndFont

MultiPar                                 true

LatexName                            longtablepage
LatexType                              command
Requires                                afterpage

Preamble
\usepackage{afterpage}
\newcommand{\longtablepage}[1]{%
\afterpage{\clearpage #1}}
EndPreamble

End

This particular inset code has several distinct sections.  First, is the InsetLayout declaration and the inset’s category and name (Custom:Longtable).  Then, is a configuration block that describes the type (custom) and what label should be used, in addition to its appearance.  In this case, the label will be “longtable” and it will appear as a “classic”, collapsible inset.  These options were chosen to match the style of the “figure” and “table” floats already in LyX.  The third block tells LyX that this particular inset should allow paragraphs worth of content (MultiPar = true).

The final block of information gives the name of a new LaTeX operation, states that it is a command, and lists any packages that are needed for the command to be executed.  The preamble section is the code that will be listed in the document preamble and gives the LaTeX definition of \longtablepage.

Drop Case Letters Using lettrine and stringstrings

Drop Cap Initials - QUntil the 18th century and for brief periods in the 19th and early 20th century, books were often decorated with initials and ornaments.  The earliest books were decorated by hand and some of the most beautiful artwork of the middle ages can be found in these tomes, such as the Book of Kells.  Later on, the books were decorated through the use of woodcuts and copper engravings.

Many of the initials and ornaments are abstract, but many also include pictures that provide insights into how those of the past thought and felt.  In the case of the Book of Kells, it combines the religious iconography of the Romans with the motifs and designs of the British Isles in the early medieval ages and shows how Roman Christianity was adapted to mesh with Irish life.

lettrine

Because of their decorative value and historical interest, there has been a great deal of interest in adding initials and other textual decorations to LaTeX documents. And as a result, there are many packages which allow you to do so.  One of the most popular of these is called lettrine.

Lettrine specializes in a particular type of decorated initial known as a drop-cap.  With a drop cap, the initial sits within the margins and runs several lines deep into the paragraph, pushing some of the normal-sized text off of these lines.  This allows for the top and left margins to remain flush, thereby maintaining the layout grid of the page.

When working directly with LaTeX, lettrine makes it very easy to create drop cap letters.  For a basic drop-cap, you first add the package to your document and then make use of the \lettrine command:

\usepackage{lettrine}

\lettrine{L}{orem ipsum} dolor sit amet …

Drop Cap Initials - Llettrine takes two arguments.  The first is the letter that is to be dropped and the second includes additional text to be typeset in a bridge font that helps to transition from the dropped case to the normal paragraph typeface.  (The default setting for the bridge font is a small caps version of the document’s primary font.)  But while lettrine is easy to use from LaTeX, there is no good way to make use of it from LyX without specifying the the lettrine arguments with LaTeX code (in LyX parlance, referred to as evil red text).

stringstrings

The best way to use lettrine in LyX would be to create a custom character style.  However, because the character style inset can only accept a single argument, it is necessary to create an “interpretive” command that can detect the first letter of the text, and split it into two separate chunks of text that can then be fed to \lettrine.

This is where the stringstrings package comes in.  Stringstrings provides a large number of routines for the manipulation of strings.  These not only cover cosmetic application, such as the changing of letter cases or removal of character classes, but also provide functions for programming.  Unfortunately, stringstrings is not always included as part of a standard LaTeX installation and you may need to install it separately.

Note: For instructions for installing LaTeX packages, see this article.

Module Code

The dropcaps module, like in the case of the longtable module defines a custom character style and inset command.  Here is what the code looks like:

InsetLayout CharStyle:DropCap

LyxType                              charstyle
LabelString                         dropcap

LatexType                           command
LatexName                         dropcap
Font
Family                             Serif
Shape                              Smallcaps
EndFont

Preamble
\usepackage(lettrine)
\usepackage(stringstrings)
\newcommand{\dropcap}[1] {%
\substring[e]{#1}{1}{1}%
\edef\LeadingCap{\thestring}
\substring[q]{#1}{2}{$} %
\lettrine{\retokenize[v]{\LeadingCap}}{\thestring}}
EndPreamble

End

Again, there is several different blocks of code.  First, the type of inset is defined and given a name (dropcap).  Next, a LaTeX operation is defined, given a name (again, dropcap) and its appearance is specified (the character style will appear in small caps serif font).  Finally, the LaTeX commands are defined in the Preamble block.

7 Responses to “Customizing LyX: An Introduction to Modules”

  1. Hey,

    Thanks for the nice explanation! I’m just starting to get comfortable with LyX, and I like drop caps in my text. I managed to get lettrine working with “evil red text”. I installed the dropcap module, but how should I use it in my documents? I have added it to my “selected” modules in document->settings->modules.

    Keep on making such nice blog posts!

    • @Frank. Glad you were able to get it installed without trouble. The module uses a special LaTeX package called “stringstrings” to find the first letter in your document and make it into a drop cap. For things to work right, this package must be installed. (If you can add the package without trouble, I am willing to bet that it is.)

      After that, you simply apply a character style. Select the text that you would like to be included in the drop cap (both the initial and the small caps component), then go to the Edit > Style menu. One of the available options should be “DropCap”.

      If it works, the text in LyX will appear as small caps. When you compile the document, the first letter will be dropped. There are few limitations. If your paragraph begins with a quotation, don’t use it, as only the quote character will be dropped. Also, some LaTeX symbols don’t get included correctly. This has something to do with how LyX encodes the files and I have not yet been able to figure it out.

      Cheers,

      Rob

      • Dear Rob, thanks for your quick reply!

        I’m not sure what went wrong, I did not install stringstrings (at least not properly), but I also did not know to look under edit->style. With your help, I got it running great. I even managed to create a new dropcaps module that drops the cap 3 lines :) .

        Thanks!

Leave a Reply