Archive for June, 2007

An example book style

Wednesday, June 20th, 2007 | LaTeX | 2 Comments

Now that we have made our way through how to style a document, it is time to look at how we can actually use some of this knowledge in practice, by typesetting an actual book. Since all that Lorem Ipsum can get a tad boring in the long run, we will create a book with some works that have passed into the public domain, namely some by H. P. Lovecraft, a significant American horror author of the early 20th century. None other than the man behind Cthulhu.

Much like with the last four blog posts, we will take a look at styling the book in the same order, namely: chapter, table of contents, sections, and footers/headers. Remembering the plain chapter style, we have something like this, for our book:

Plain chapter style

As I’ve written before: while this is certainly acceptable, it’s not really too unique of fascinating, so let us think up a way to get it to feel more 1920’s and horror-ish. The last part is of course hard to quantify unless you pick some cheesy font that’s impossible to read, so let’s just stick to making it look a bit like a book on good literature. We will try to accomplish this by just writing the chapter number as a word (one, two, three, etc.), and omit the ‘Chapter’ prefix, centered, and put the chapter title in italics, also centered. We can do that with the following code:

\makechapterstyle{bookstyle}{ % Yes it's a very imaginative name
  \setlength{\beforechapskip}{0em}
  \setlength{\midchapskip}{1em}
  \renewcommand{\chapnumfont}{\normalfont\large\bfseries\fscshape}
  \renewcommand{\chaptitlefont}{\normalfont\huge\bfseries\itshape}
  \renewcommand{\printchaptername}{}
  \renewcommand{\printchapternum}{%

    \centering\chapnumfont\numtoname{\thechapter}
  }
  \renewcommand{\printchaptertitle}[1]{\centering\chaptitlefont ##1}
}
\chapterstyle{bookstyle}

This verily will take a bit further description. The \fscshape command introduces fake small-caps, and its existence depends on what font package you may or may not be using. If you have a commercial grade font, or one of the built-in fonts, then you will want to use \scshape instead. The \fscshape I am using here is provided by the mathdesign package together with the URW Garamond typeface. The only other surprise here should be the \numtoname command that is provided by memoir, and this command converts a number into a corresponding name, for instance \numtoname{13} will be turned into ‘thirteen’.

With this modest change in place, our chapter page suddenly looks like this:

Modified chapter style

This seems a tad more classic literature-ish to me, at least. So we will chalk one up for success on the chapter style. We could, of course, add something to the fancy and automatically insert an image for each chapter to complement the story, but since my freehand drawing skills aren’t what I’d like them to be, we shall skip this step for now.

With this out of the world, let us take a look at the existing table of contents:

Plain table of contents

Plain table of contents, cont.

Plain table of contents, cont.

From this we see that our book is divided in two parts: one for some of Lovecraft’s essays, and another for a very few of his poems. Since most of his essays aren’t subdivided, we probably have no need to indicate any of these, so let us turn them off and simplify the table of contents a bit. This may be done using:

\settocdepth{chapter}

Now, as long as you only want to tweak the distance between table of content entries, perhaps remove the dots on the line to the page numbers and move the page numbers a bit back and forth on the page, then everything is easy to do with memoir, but as soon as you move beyond that, things start to get really complicated, unfortunately. Not one to shy away from hard things, let us look at what it takes to center the part and draw lines around it and to typeset all the chapters in italics.

The first part is, unfortunately, rather hard. It requires us to override two different commands: \l@part and \partnumberline. The reason for this is two-fold. When we issue a \part command, the following is written to the .aux-file: \@writefile{toc}{\contentsline{part}{\partnumberline {I}Essays}{1}}, for instance, for part 1 called Essays. When this is going to be typeset then \l@part is called with the last two {}’s above as arguments.

Using the tikz package that we have covered earlier to draw the lines about the part title, we will give the entire definition of the two commands here and then proceed with an explanation of the key points. The overall structure has been ‘borrowed’ from memoir.cls:

\newlength\sb@partheight

\renewcommand*{\l@part}[2]{%

        \ifnum \c@tocdepth > -2\relax
        \addpenalty{-\@highpenalty}%
        \addvspace{\cftbeforepartskip}%

        \begingroup{
        \centering
        \settoheight{\sb@partheight}{\Large\bfseries\MakeUppercase{#1}}
        \setlength{\sb@partheight}{.5\sb@partheight}
        \addtolength{\sb@partheight}{5pt}
        \begin{tikzpicture}
                \draw (0,0) node { \Large\bfseries\MakeUppercase{#1} };
                \draw (-.25\textwidth,\sb@partheight) -- (.25\textwidth,\sb@partheight);
                \draw (-.25\textwidth,-\sb@partheight) -- (.25\textwidth,-\sb@partheight);
        \end{tikzpicture}
        \par

        }\endgroup
        \fi
}

\renewcommand{\partnumberline}[1]{}

So, I guess this requires some explanation. The test on \c@tocdepth tests for whether the part should actually be displayed in the table of contents, and -2 is the code for the part in this instance. The \addpenalty command here makes TeX prefer to create a page break \emph{before} the part rather than after, so we don’t have a part title dangling alone at the bottom of a page, since that doesn’t look particularly nice. Then we use \begingroup to localise our changes so they don’t seep into the remaining document, and inside this group, we do a bit of slight trickery to compute how heigh the part title is, using the \settoheight. Then we calculate the half height and add some space, and this we use as a measurement in the following tikzpicture. The tikzpicture code should be familiar, as we have already seen it here. The redefinition of \partnumberline merely discards the part number as we aren’t really interested in that.

Our changes to the actual chapters are a lot easier to accomplish. Indeed, it only requires the following two lines:

\setlength{\cftbeforechapterskip}{.2em}
\renewcommand{\cftchapterfont}{\normalfont\small\itshape}

Taking all this together and using it with our book, we get the following table of contents for it:

First page of the styled TOC
Second page of the styled TOC

This looks a good deal more like some of the older fictional works. So far so good. The next thing to turn pretty is the section titles. For the most part Lovecraft’s essays don’t have actual sections, but a few of them have sections named I, II, III, etc., and even fewer have actual section titles. One of the essays that do, is ‘Herbert West: Reanimator’.

Plain section title

First off, the numbering of the section doesn’t really make any sense in a fictional work as the title is usually sufficient in and of itself, so let’s do away with that. Apart from that, the standard section title layout looks quite decent. This is an extremely easy change then:

\maxsecnumdepth{chapter}
\setsecnumdepth{chapter}

And we get the following:

Modified section title

This leaves us with just the page headers and footers. As we can see below, and as I have written previously, the standard page headers are just ugly.

Default page header and footer

So, to rectify this, we will place the part title on the left page and the chapter title on the right page, both centered in the header, and we’ll place the page number on the page edge in the footer. And this is easily accomplished with the following code:

\makepagestyle{mybookstyle}
\makeoddhead{mybookstyle}{}{\itshape\rightmark}{}

\makeevenhead{mybookstyle}{}{\itshape\leftmark}{}
\makeoddfoot{mybookstyle}{}{}{\thepage}
\makeevenfoot{mybookstyle}{\thepage}{}{}
\makepsmarks{mybookstyle}{%

  \def\partmark##1{\markboth{##1}{}}
  \def\chaptermark##1{\markright{##1}}
  \def\sectionmark##1{}
}

\pagestyle{mybookstyle}

And presto, we get a much nicer output:

Styled page header and footer

Throughout all these examples, we have used the @-sign repeatedly in commands. This is ok if you’re implementing this in a package file, but if you’re pasting them into your document’s preamble, the @ will not be interpreted as a character and a lot of errors will follow. To rectify this, surround the code in the preamble with the commands \makeatletter and \makeatother. This will make everything right. In a future post, I will try to talk about implementing packages to better hide this functionality away in a reusable component.

This concludes the styling example for today. If you’re in a need for a lot of sensible material to try out different stylings on, then I suggest that you head over to WikiSource or Project Gutenberg and grab some works that have entered the public domain and try to make your own compilation of them. And for your viewing pleasure, here is the book typeset with the style above.

Tags: , , ,

Styling the page footer and header

Tuesday, June 12th, 2007 | LaTeX | 1 Comment

This leads us to the last post in my series of styling documents, namely the one on how to customise page headers and footers. This is one of the most visible style elements as it is (typically) present in some form or the other on almost all pages except chapter pages. As with the section titles it is also relevant for the page headers and footers to mimick the aesthetic feel of the chapter page, thus keeping a uniform expression that can be tied exclusively to your work (this is the really hard part, by the way). Before we delve into the intricacies, let us take a look at the standard page header:

Standard page header

For those of you with bad eye-sight, the chapter name and title is printed in all-caps. Absolutely ghastly. I mean, what is this, a tribute to AOL users?! We are definitely going to have to change something here indeed.

This is probably as good a time as any to bring this up. When we are typesetting a book it contains pages that will be to the left (verso pages) and on the right (recto pages). These two pages have different margins (try to open one of your books on your bookshelf and check for yourself), and furthermore books tend to have different things in the verso and recto headers and footers. Typically this means that the chapter number and title will be displayed on the verso page and the section number and title on the recto page (or part and chapter in other books, or something entirely different in yet other books).

These items (chapter number and title and section number and title) isn’t grabbed out of thin air in LaTeX, but is written into internal commands that can be read using the \leftmark and \rightmark commands (named for their use on left and right pages, obviously). Thus, the all-caps chapter title on the default page header has been written into the left mark here, so we will need to modify how the marks are stored.

The first step to creating a new page header and footer is to create a new page style using the \makepagestyle{name} command. So if we want to create a new page style where the header contains the page number and the chapter/section number (if any) and title, we would start out with the following:

\makepagestyle{mypagestyle}

To create a nice separation between the page number and the title—rather than typesetting them at opposite ends of the header—we will separate them with a vertical rule. Now the commands to modify the headers and footers of a page style are: \makeevenhead{style}{left}{center}{right}, \makeoddhead, \makeevenfoot, and \makeoddfoot. All with the same number of arguments. So, this means we can extend our page style as follows:

\makeevenhead{mypagestyle}{\thepage\hskip.5cm\vrule\hskip.5cm\leftmark}{}{}
\makeoddhead{mypagestyle}{}{}{\rightmark\hskip.5cm\vrule\hskip.5cm\thepage}

If we tack on a \pagestyle{mypagestyle} now, we will get some output like this:

Initial version of our own page style

Better than the standard, but it still feels partly like an AOL user tribute, what with all the caps and stuff. Before we fix this, it is time to discuss marks in a bit more detail.

Storing information to be read by \leftmark and \rightmark is accomplished using \markboth and \markright (no, there is no separate \markleft). And these two commands are meant to be invoked inside some specific commands that are in turn invoked from \chapter, \tableofcontents, etc. These commands include: \tocmark, \partmark, \chaptermark, and \sectionmark. There are, of course, more marks and you can generate more by creating new lists, so if you’re overriding marks you need to make sure to catch all of them appropriately.

Getting to the actual code now would be too easy. When we need to print the chapter number we have to remember that a book is divided into several ‘sections,’ namely the front matter (table of contents, lists, foreword, etc.), main matter (the actual book chapters), and back matter (bibliography, indices, etc.). Of these it is only customary to give the chapters in the main matter numbers in the heading.

Before we venture on, we also need to look at one of the ‘reserved’ symbols in LaTeX: @. This section is vague on purpose in order not to spend too much time on this detail. The @ is used for ‘reserved’ commands inside class-files and packages and its default ‘code’ to something that cannot be used. If, however, you’re in the need to using commands with @ in them you can use the command \makeatletter and then once you’re done return it to its original state with \makeatother. I will try to remember to visit this topic in more detail at some later time.

The use of @ becomes relevant when we need to test whether we’re in the main matter, because this is done (with memoir, remember @ means we’re overriding the internals of some package) using the \if@mainmatter where @mainmatter is a boolean value.

Now we’re finally ready to create our own marks! To recoup, we want to write the chapter mark on the verso page and the section mark on the recto page. This is done like this:

\makeatletter

\makepsmarks{mypagestyle}{
  \def\chaptermark##1{\markboth{%
    \ifnum \value{secnumdepth} < -1
      \if@mainmatter
        \chaptername\ \thechapter\ --- %
      \fi
    \fi
    ##1}{}}

  \def\sectionmark##1{\markright{%
    \ifnum \value{secnumdepth} < 0
      \thesection. \ %
    \fi
    ##1}}
}

\makeatother

The secnumdepth is a counter that contains information about what depth of sections should be numbered. Chapters is equal to secnumdepth 0 and sections to 1, hence the comparisons. Using this in our document we get the following output:

Page style with changed marks

And for those with bad eye-sight, a courtesy close-up of the verso page:

Close-up of changed marks

Rather much of an improvement to the earlier AOL user tribute. There are, of course, plenty of other things we could want to do: add a ruler below the header, place the page number in the margin to make it easier to find a page when flipping through a book, or whatever else we might imagine. Even though I’ve carried this post on for quite a while, let us take a brief look at accomplishing this. First we create a page style very much like above:

\makepagestyle{myruledpagestyle}
\makeevenhead{myruledpagestyle}{\thepage}{}{\leftmark}
\makeoddhead{myruledpagestyle}{\rightmark}{}{\thepage}
\makeatletter
\makepsmarks{myruledpagestyle}{
  \def\chaptermark##1{\markboth{%
        \ifnum \value{secnumdepth} > -1
          \if@mainmatter
            \chaptername\ \thechapter\ --- %
          \fi
        \fi
        ##1}{}}
  \def\sectionmark##1{\markright{%
        \ifnum \value{secnumdepth} > 0
          \thesection. \ %
        \fi
        ##1}}
}
\makeatother

This is almost exactly the same as mypagestyle above, with the only change that we now place the page number and the mark on opposite sides of the header. This leaves us with the task of moving the page number into the margin and adding a ruler below the header. This is fairly easily accomplished:

\makerunningwidth{myruledpagestyle}{1.1\textwidth}
\makeheadposition{myruledpagestyle}{flushright}{flushleft}{flushright}{flushleft}
\makeheadrule{myruledpagestyle}{1.1\textwidth}{\normalrulethickness}

Here \makerunningwidth changes the width of the headers and footers of the specified style. As standard it’s \textwidth long, here we make it 1.1 times longer. \makeheadposition changes the placement of the header and footer. It has the form \makeheadposition{even-head-position}{odd-head-position}{even-foot-position}{odd-foot-position} where the different positions can be chosen between flushleft, center or flushright. This command is only useful, if the width of the page header is different from \textwidth. Finally we apply the actual rule, stating that it should be the width of the header and to use the normal rule thickness. This is, unless you have changed something, typically 0.4pt in LaTeX.

With all this trickery, this is what we get as output:

Ruled page style

As an incidental note, the last style presented here is almost equivalent to the Ruled page style that comes with the memoir package (remember casing matters, there is both a ruled and Ruled page style). So if you want exactly this style, use that instead of defining all this yourself.

This fairly much concludes the styling the document series, but I am sure that I will, sooner or later, revisit how to style other parts of the document, or show even more involved styling solutions. But until then, let your imagination run free and bring some personal style to your documents.

Tags: , , ,

Styling the other document divisors

Saturday, June 2nd, 2007 | LaTeX | No Comments

While sectional titles aren’t as stylistically free as the chapter page, it is still important to carry over the style of the chapter page to sections, subsections and other such entries you have throughout your text. Thus, if the chapter style contained sans-serif text and a line below the text, it might be relevant to make the sections be sans-serif and possibly with both a line on top and below the section title.

While memoir is indeed very configurable, it doesn’t contain quite as an elaborate amount of commands to configure the sections, subsections and so forth. The primary command to customise with here is the \setXheadstyle where X can be sec, subsec, or subsubsec (and possibly more). So writing up the section style mentioned above would look like this:

\newcommand{\ruledsection}[1]{%
  \noindent%
  \parbox[t]{\textwidth}{%
    \hrule\vskip1em
    \sffamily\Large\bfseries #1\vskip1em%
    \hrule%
  }
}

\setsecheadstyle{\ruledsection}

Here we set the style to our custom command that will be called with the section number and title as an argument. This gives us the following output when compiled:

Boxed section style

Since styling in this way is fairly simple, I will not go into painstriking detail of how to create more section styles. It is, though, useful to note that there are three more useful commands to know of: \setbeforeXskip, \setafterXskip, and \setXindent. The two first commands take lengths such as ‘-3.5ex plus -1ex minus -.2ex’ as arguments, and the last command just takes a regular length as an argument.

To see how these lengths can be used in practice, please refer to the memoir manual.

Tags: , , ,