## Troubleshooters.Com and T.C Linux Library Present

Writing Self-Published Books with Lyx

LyX gives an author the means to write a uniform and beautifully typeset, formatted book with a minimum of effort.

But...

Custom paragraph styles and custom character styles are indispensible for the book author, and unfortunately the Lyx methods to accomplish these two necessities are horrendously underdocumented. In fact, as of LyX 1.1.6fix3, LyX doesn't even support character styles. But don't worry, this document containss a very nice workaround you can use to achieve the benefits of character styles.

The toughest impediment to learning to customize LyX is confusing LyX code with LaTeX code. This will be clarified in this document.

# Introduction to Lyx

## What Is Lyx?

Lyx is a document processor. It handles all document formatting based on styles and a set of rules to translate those styles to formatting. Therefore your book is consistent throughout. And if you use the same set of rules on multiple books, they'll all be formatted consistently.

Lyx uses paragraph styles (which are called "environments" in Lyx parlance) to govern formatting of document pieces. There are styles for different level headers, for emphasis, for peoples' names, for code snippets. And you can make your own styles, although that isn't simple.

If you use LyX, your documents will output as beautifully typeset documents with consistently professional formatting. They'll look like a book you see in the bookstore. And because LyX handles the formatting, you can spend your time and energy on what you're writing, not how it will look.

As mentioned, the LyX default styles may not format exactly how you want. In such cases you can modify styles or even make your own. This web page contains tutorials that walk you through creating your own style.

## What Lyx Isn't

Lyx isn't a word processing program. You can't (and shouldn't) format individual words or paragraphs. Instead you assign styles to the words or paragraphs. Those styles correspond to the words and paragraphs' function, not to the way you want them to look. You'd never use Lyx to design a high impact flyer, or a poster, or a love letter. Lyx configuration is difficult enough that you don't start seeing a return on your configuration investment unless you write books or *lots* of reports.

## WYGIWYM

We've all heard of WYSIWYG. Lyx is WYGIWYM. WYGIWYM stands for "What You Get Is What You Mean". This means if you mean for text to represent source code you assign it a source code environment (Lyxese for style), and it formats the way you meant it to. You needn't worry about formatting during the writing of your document. If you don't like the way it looks upon finishing and printing it out, you can change the way styles map to formatting, and those styles will consistently change throughout the document.

WYGIWYM has spacing ramifications. Spaces are considered nothing but word separators, and as such multiple spaces are output as a single space. Likewise, carriage returns (newlines and the like) are simply paragraph separators, and as such you cannot make a blank line by inserting an additional return. Blank lines should never be necessary. Instead, each paragraph specifies interparagraph spacing, spacing before the first of such paragraphs, and spacing after the last of such paragraphs.

This is a matter of philosophy. Do we view a book as 300 pages, each of which is a sketch or painting? Or do we view it as parts containing chapters containing various levels of headings containing paragraphs of varying types, such as normal body text, code examples, notes, tips, warnings and the like. LyX takes the latter view, and thus simply declares the formatting of various paragraph styles. Such formatting can be complex, including lines, graphics, justification, spacing, and almost anything else you can think of. The beauty of this philosophy is once you've decided the properties of each paragraph style, those decisions are applied uniformly throughout your book. If you decide to change one of those styles, every paragraph of that style is instantly updated throughout your book.

A cynic might label this as WYGIWWA - "What You Get Is What We Allow". Lyx makes the rules and unless you're knowledgeable enough to change those rules you just accept what Lyx says you get. This is one of the reasons for the paragraph and character style examples on this page -- to let you use Lyx without settling for an unsatisfactory format.

## Data Safety

In this era of software rental licenses and companies going out of business, it's nice to know that your documents are in easy to parse ascii text. It's quite easy to write a simple computer program to convert Lyx documents to other formats. The native Lyx format is even human readable, so there's every reason to believe that 20 years from now you'll be able to get your hands on your data.

Data safety was the #1 reason I chose LyX. The books I write are vital to my business.
===============================

# Built in Paragraph Styles

This section details the available paragraph styles contained in the "book" document class. There are other document classes such as "article", "letter", "seminar", "slides", "broadway" (scripts for plays), "hollywood" (movie scripts), and many more, including some specialized styles for different types of books. However, this web page discusses the "book" document class, because it provides the nicest looking general purpose styles for books. This document then goes on to instruct you how to change existing styles and make new styles to get exactly the book you want.

This is a list of the heading styles, in order of inclusiveness (i.e. a Part contains chapters, not vice versa).

 Heading  Paragraph  Style Key Binding Part Chapter M-p 1 Section M-p 2 Subsection M-p 3 Subsubsection M-p 4 Paragraph M-p 5 Subparagraph M-p 6

 NOTE The preceding styles called "Paragraph" and "Subparagraph" are headings, not body text type paragraph styles. Body text is most accurately mapped to the LyX environment called "Standard"

## Itemization Type Paragraph Styles

 List Paragraph Style Key Bind Style Description Itemize M-p b Bulleted list Enumerate M-p e Numbered list Description M-p d 2 column list of short terms on the left, and a long definition on the right. The term on the left is bold List M-p l (lower case L) Similar to List, but left hand term is not bold.

## Styles for Special Paragraphs

 Special Paragraph Style Key Bind Style Description LyX-Code M-p c Use this for a source code listing. Fixed width font. Unlike other LyX styles, this one allows multiple spaces in order to accurately reflect a source file. Quotation M-p Q Used for a long quote (i.e. quoting a paragraph of the State of the Union Address). Quote M-p q Used for a short quote (i.e. "A penny saved is a penny earned".) Verse M-p v Used for poetry and prose. All lines after the first line of the paragraph are indented. Caption M-p M-c This is a mechanism to title figures and tables, and must be used in conjunction with figure floats and table floats.

## Book Structure Paragraph Styles

 Special Paragraph Style Key Bind Style Description Title M-p t Title of the book Author M-p A Author of the book Date M-p D Date of the book Bibliography M-p B Bibliography

# Built in Character Styles

There are no built in character styles as a book author would think of them. This is a serious deficiency which the LyX people plan to correct in the future. So this deficiency won't hurt your long term use of LyX.

Frustratingly, fonts like font-code are sometimes referred to as styles in the LyX world. In fact, using font-code introduces a \family typewriter into the LyX file, so it's no different from using <tt> in your HTML to represent code. There's not a one to one correspondence.

Nevertheless, it's easiest to use font-code to represent a small slice of code within a larger paragraph. Here are some of the other fonts I use to represent things:

 font-emph C-e Emphasized text (italicized) font-code Create in ~/.lyx/ui/default.ui. Filenames, tiny commands and other code like things within a larger paragraph (fixed spaced text) font-noun M-c c Terminology -- words to be defined, etc. (small caps)

Styles are supposed to map to usages, and it's obvious that the preceding fonts do not. So they're a compromise. But it works as long as you don't use italics, smallcaps or monofonts for other things. If you do not, then when LyX gains character style capabilities it will be trivial to search/replace these fonts with real styles.

But of course you will use italicized, fixed space and small cap text for other things. That's OK as long as those other usages are done with color pseudostyles.

# Simulating Character Styles With Color Pseudostyles

This section will show you how to set up a one to one correspondence between character color and a LaTeX character style. This allows you to easily convert to real character styles when LyX gains that feature. Place the following code near the top of your .layout file.

 Preamble % %%% Pseudo character styles indexed by color %%% \usepackage{ifthen} \renewcommand{\textcolor}[2]{% \ifthenelse{\equal{#1}{blue}}{{\textsl{\textsf{#2}}}}{}%       Steps \ifthenelse{\equal{#1}{magenta}}{{\textsl{\textsf{#2}}}}{}%    Chapters \ifthenelse{\equal{#1}{magenta}\or\equal{#1}{blue}}{}{#2}%     fallthrough } EndPreamble

The Preamble and EndPreamble keywords are LyX code. Everything between them is LaTeX code. In fact, it's safe to assume that any code between  Preamble and EndPreamble is LaTeX code.

The ifthen package bestows the ability to assign according to choices -- in this case colors. the \usepackage keyword incorporates that package much the same as a Perl use or a  C include.

# Paragraph Styles (LyX Environments)

Books need styles like Tip, Note, Warning and the like. The following code implements a Note style, narrower than normal text, contained between lines, and titled with the word NOTE.

 Style Note   LatexType             Environment   LatexName             note_l      LabelType             Centered_Top_Environment   LabelString           "NOTE"   AlignPossible         Left   LeftMargin            "MMMMM"   RightMargin           "MMMMM"   ParSkip               0.7   ParSep                0.7   TopSep                0.7   BottomSep             0.7   Font   EndFont   Preamble         \setlength{\scratchLength}{\leftmargin}         \addtolength{\scratchLength}{1cm}         \newenvironment{note_l}                 {                 \begin{list}{}                         {                         \setlength{\leftmargin}{\scratchLength}                         \setlength{\rightmargin}{\leftmargin}                         \setlength{\parsep}{1cm}                         }                 \item[]                 \hrulefill                 \\[0.1cm]                 {\centering\large NOTE \\[0.2cm]}                 }                 {                 \\[0.2cm] .\hrulefill \\                 \par                 \end{list}                 }   EndPreamble End

In the preceding, the style is described first in LyX code (everything except that between Preamble and EndPreamble), and a parallel description in LaTeX (everything between Preamble and EndPreamble). You'll note that I didn't bother to put the lines in the LyX version.

Note also there are plenty other ways to do this. The best way is probably to enclose the note in a minipage, but I don't know how to do that yet.

# Will Lyx Suit My Needs?

Why use LyX?

Because once you learn it, you can easily and quickly produce books, reports and other large documents that are professionally formatted and typeset. These documents can be put into Postscript or PDF format so they print correctly everywhere.

I chose LyX after getting tired of inconsistent typefaces. After getting tired of having to remember whether I made a style for things. After getting tired of trying to remember what font I made a given entity the last time.

I got tired of manually tweaking books to get the paging right. I got tired of inaccurate tables of contents. I got tired of printing inconsistencies.

I got tired of my word processor slowing me down. That same word processor that seemed so easy to learn ages ago, but now confounded me with an array of formatting choices seemingly every paragraph.

Now I can reasonably expect to write a professional looking book, and send a postscript file to the print shop of my choice.

But LyX requires a serious committment. A person who could learn MS Word or Star Office in a day could take a week or more to learn Lyx unless they approach that learning process the right way. The creation and modification of environments (styles) in LyX are inobvious to say the least. You will not successfully write books with Lyx unless you make a serious committment to learn the program and style modification. This page contains an article called The Fast Way to Learn Lyx, designed to make your committment much more achievable.

LyX suits your needs if you need its benefits and can handle its costs. The benefit is uniformly consistent formatting of your books, reports and other large documents, without your needing to oversee that consistency. The cost is learning LyX (easy) and learning to create and modify its styles (difficult, but made much easier by the tutorials on this page).

# Evaluating Lyx for Your Needs

First, know that you can use LyX to produce almost any type of printed document you can imagine. It's that flexible. It's VERY doubtful that LyX would not be able to produce what you need, unless what you need is formatted on the fly stuff like flyers, posters, invitations and the like. But for serious documents like books, reports, and even business letters, you can be 99% certain that LyX can be made to produce the format you need. LyX is ALMOST NEVER a dead end. As a matter of fact, it's much less likely to be a dead end than more mainstream word processors.

But that doesn't mean it will be easy. Changing default environment to format mappings is much more difficult with LyX than with standard word processors. See the article titled The Fast Way to Learn Lyx to minimize the LyX training period.

Here are some of the questions you'll need to answer in order to decide for or against Lyx:

• How important is consistency in my documents (Lyx is very consistent)
• Can I live with Lyx's default document classes and formatting? (If so, go with LyX -- it's a no brainer)
• Do I or somebody in my organization have the ability to learn to I create and modify Lyx styles to produce output suiting my needs? (Before answering, read the rest of this web page. After reading the web page, if the answer is No, LyX doesn't suit your needs).
• Is the Lyx program's performance sufficient for books the size I want to write, and if my books are big enough to slow it down, am I willing to write the books in parts and put everything together in the end (makes crossreferencing harder)
• Note: My dual 450mhz Celeron with 512Meg and a 7200rpm hard drive can load, reformat, or output to Postscript in less than 20 seconds for a 100,000 word (about 250-300page) document. On the same document I can save in less than 5 seconds. However, on a 550,000 word doc (about 1200-1400 pages) it takes about 3 minutes to load or reformat.
• How important is a good index to me? (LyX is great at indexing)
• How important is a good, accurate table of contents to me? (LyX produces good looking and accurate tables of contents)
• How important is guaranteed future access to my book's data (proprietary wordprocessors are often hard to export from).
• Are you proficient with a capable text editor with macros and search/replace? (Proper use of a text editor on your LyX files can greatly enhance your LyX capabilities, although this isn't absolutely necessary for profitable use of LyX).
I'd recommend starting by using Lyx for reports (they have a Report document class). If that works out use their Letter document class to produce letters whose format isn't important (personal letters and the like).

Take the tutorial later in this web page. If you're successful with it you'll probably be able to commit to Lyx. If you cannot do the tutorial after many repeated attempts, Lyx is probably not for you. That is, unless you have a consultant who can modify document classes and environments. Many businesses have computer experts create macros and templates so that less technical people can produce corporate standard documents.

Run performance tests to see how Lyx works on your computer with books resembling the size and structure of yours. This page contains a C program you can use to create just such a test book. If you can't compile the program, have a programmer friend do it. If the performance is insufficient, you'll need to

# The Fast Way to Learn Lyx

LyX can take a day or two to learn, or it could take weeks, depending on how you approach learning it. This article describes how to learn LyX in a day or two.

LyX has two distinct aspects:

1. Creating content
2. Controlling the format of that content in the output
#1 is no harder than any other word processor, and it's probably actually easier than most word processors. The best way to learn #1 is to run the LyX tutorial (Help->Tutorial from the menu). Once finished with the LyX tutorial, you'll have an excellent grasp of how to write content in LyX. That leaves #2:

#2 is much harder than with other word processors. First, most word processors allow you to format content on the fly. LyX doesn't allow that because on-the-fly formatting leads to inconsistant and amatuerish documents. If you want professional looking documents, LyX is your product.

But changing the mapping of styles to formatting is much harder than in programs like WordPerfect, MS Word or StarOffice. It requres knowledge of LyX coding and the LaTeX markup language. Both are extensively documented, but unfortunately the documentation is a reference, not a tutorial.

So I created some tutorials to walk you through creating and formatting your first LyX style (LyX styles are actually called "environments"). Those tutorials appear on this page. These tutorials will take you one to four hours, after which you'll be ready to create custom environments to make your document look the way you want it to, consistently.

In summary, if you'd like to trim the LyX learning process down to a day or two, do the LyX tutorial, and then do the tutorial on this page.

To shorten the learning time, use tutorials. Start with the tutorial that comes with LyX (Help->Tutorial).

# Beginning Textclass Modification Tutorial

Lyx is a wonderful program with wonderful documentation. The docs tell you every aspect of Lyx user operation, as well as giving you all sorts of Lyx functions and Latex codes (the latter being in /usr/share/texmf...). But there's a gaping hole in the docs when it comes to exactly how you create new environments in a real life situation. All too often the documentation tells you what to insert but assumes you know where to insert it. All too often you get your new environment into Lyx, only to find that it doesn't render in Postscript or DVI.

This tutorial and the next one are designed to condense a week of manual reading, emailing and experimentation into two 1 hour tutorials. This is the first tutorial, designed to give you the fundimentals. Read on...

## Proof of Concept

This proof of concept does nothing but enable a new textclass to appear in your Layout->Document->Document->Class dropdown list. It has no practical use, and must be reversed out, meaning that you must make a backup of the file you modify.
2. Find your system's Lyx layout directory.  It's typically in /usr/share/lyx/layouts, but of course can vary. The following two commands may help you find it:

3. locate -r "article\.layout$" find / -type f | grep "article\.layout$"
Note however that your system contains other copies of article.layout. The one you want should have "lyx" in the directory path.
4. cd to the Lyx layout directory. From there, the pwd command should reveal "lyx" somewhere in the directory name, and there should exist several .layout files.
5. Back up the article.layout file with the following command:

6. cp -p article.layout article.layout.org
7. Edit article.layout. Change the second line, which looks like this:

8. #  \DeclareLaTeXClass{article}
to this:
#  \DeclareLaTeXClass{Hello World}
9. Reconfigure Lyx with Edit->Reconfigure
10. Close all copies of Lyx, open a Lyx session, open a file, and note that the Layout->Document->Document->Class dropdown list now contains a class called "Hello World".

### Discussion

You have just changed the name of the "Article" class to "Hello World". For reasons you'll see later, this is useless except as a confidence building exercise.

## Changing an Environment's Font in the Proof of Concept

In this exercise you will change the font and alignment of the Author environment (an environment is Lyx's word for a paragraph style), to see what it affects, and perhaps more importantly, what it does not effect.
1. Create a baseline article
1. Use Lyx to create a new two line document of type "Hello World". The first line should be "Title" and should be formatted to the Title environment (chosen from the Layout->Document->Document->Class dropdown list).  The second line should be "Author" and should be formatted to the Author environment picked from the same dropdown.
2. Save as z.lyx.
3. Notice that in Lyx both the words "Title" and "Author" are centered, and that the word "Title" is much bigger than the word "Author".
4. Use View->Postscript to view the document in a viewer. Notice that the words "Title" and "Author" are centered but skewed toward the right (they're right of center), and that the word "Title" is much bigger than the word "Author". Notice that there's a third line containing a date, but ignore that line, as it's not relevant to the point being made. The main point is that "Title" is bigger than "Author", and that they're both centered toward the right.
5. Exit the Lyx program.
2. Edit article.layout
1. Add the following lines to the bottom of article.layout:

2. Style Author
Align   Left
AlignPossible  Left

Font
Size  Giant
EndFont

3. Understand that what you just did is modify the existing Article environment, changing the alignment to left and the font size to Giant.
4. Save article.layout.
3. Tell Lyx about the layout change.
1. In Lyx, Edit->Reconfigure
2. Exit Lyx and run it again.
4. Notice the changes, and also notice what doesn't change
1. Pull up z.lyx in Lyx.
2. Notice that now the word "Author" is larger than the word "Title", and that the word "Author" is now left justified instead of centered.
3. Use View->Postscript to view the document in a viewer. Notice that the Postscript article is identical to the one formatted before the change. "Author" is NOT bigger than "Title", nor is it left justified.

### Discussion

File article.layout changes the layout of the article under Lyx, but not the finished product. You must modify other files to change the output.

## Exploring the Role of Layout Filenames

This exercise introduces the fact that filenames matter, and methods of specifying the mapping between files and layouts initially appears almost magical.
1. Verify once more that environment "Hello World" appears in the Layout->Document->Document->Class dropdown list.
2. Rename article.layout to aarticle.layout.
3. In Lyx, Edit->Reconfigure
4. Exit Lyx and run it again.
5. Pull up z.lyx in Lyx
6. Notice an error message saying "unknown textclass article".
7. Notice that environment "Hello World" is now missing in the Layout->Document->Document->Class dropdown list.
8. Verify the following:
• Changing \textclass article  to \textclass aarticle does not restore environment "Hello World".
• grep -r "article\.layout$" /usr/share/lyx reveals no config files mapping to filename article.layout. • Likewise, grep -r "article\.layout$" ~/.lyx reveals no config files mapping to filename article.layout.
• Removing the "\.layout" from the preceding commands also reveals no information on why filename article.layout is so special.

### Discussion

Obviously, something declares the filename article.layout to be special, but at this point it's difficult to find. How do you get Lyx to recognize a layout file of arbitrary filename? Read on...

## Recognizing a Layout with Arbitrary Filename

This exercise gets Lyx to recognize aarticle.layout, and postulates the reason such a procedure was necessary.
1. Edit aarticle.layout.
2. Replace the current #  \DeclareLaTeXClass line (should be the second line) with the following:

3. #  \DeclareLaTeXClass[article]{Hello World}
4. Save aarticle.layout.
5. In Lyx, Edit->Reconfigure
6. Exit Lyx and run it again.
7. Pull up z.lyx in Lyx
8. Notice that the error message has disappeared.
9. Notice that environment "Hello World" has returned to the Layout->Document->Document->Class dropdown list.

### Discussion

You just proved that Lyx DOES INDEED read every .layout file in the lyx/layout directory, and that there's nothing magical about the filename. This exercise makes that obvious because you renamed the file to an arbitrary filename (aarticle.layout is definitely arbitrary -- a filename that's mentioned nowhere except this tutorial.

The key distinction is that the .layout file must name an existing document class in order to be included in the Layout->Document->Document->Class dropdown list. So once we referenced existing document class article (inside the brackets), we get what we want. Almost.

There are still 2 problems:

• We must have root access and are making the new layout system wide instead of per user.
• We are still not modifying the finished product (Postscript or dvi or whatever) to our desire.
The next exercise fixes the first problem...

 Now copy article.layout.org back to article.layout with the following command: cp -p article.layout.org article.layout Also, delete aarticle.layout.

## Modifying a Layout File the Right Way

The preceding exercises were done because they are easy to describe and perform. However, they were useless because they cannibalized the Article layout instead of using it as the basis of a more specialized layout. Also, this method does not require being logged in as root.

A couple facts for those of you trying to transpose this to a Windows-based system:
~/.lyx means the .lyx directory (yes, it starts with a dot) off your home directory. The tilde is UNIX shorthand for "home".

1. Set the system back to original state
1. If you haven't yet, restore the original article.layout as described preceding this exercise.
2. rm aarticle.layout
3. In Lyx, Edit->Reconfigure
4. Exit Lyx and run it again.
5. Pull up z.lyx in Lyx
6. Notice that there are no error messages
7. Notice that the "Author" line is centered and smaller than the "Title" line.
8. Notice that environment "Hello World" is gone, but has been replaced by environment "Article" in the Layout->Document->Document->Class dropdown list.
9. Understand that you have restored the system back to its original state.
2. Make a user-specific layout file
1. Log out and log back in as your normal username. For safety and security, real work should not be done as a priveleged user.
2. cp /usr/share/lyx/layouts/article.layout ~/.lyx/layouts/aarticle.layout
3. Edit file ~/.lyx/layouts/aarticle.layout
4. Replace the current #  \DeclareLaTeXClass line (should be the second line) with the following:

5. #  \DeclareLaTeXClass[article]{Hello World}
6. Add the following lines to the bottom of aarticle.layout:

7. Style Author
Align   Left
AlignPossible  Left

Font
Size  Giant
EndFont

8. Understand that what you just did is modify the existing Article environment, changing the alignment to left and the font size to Giant.
9. Save the file.
10. In Lyx, Edit->Reconfigure
11. Exit Lyx and run it again.
12. Pull up z.lyx in Lyx
13. Notice that the Layout->Document->Document->Class dropdown list contains both document classes article and Hello World. Note that toggling between the two document classes toggles the size and alignment of the "Author line.

### Discussion

You have extended the concept of configuring an arbitrarily named file to link to an existing document class (Article in this case) to work with your own personal Lyx directory. Without disturbing the existing Article document class or layout, you've created your own document class, called Hello World, that implements a changed Author environment. Unfortunately, the modifications to the Author environment do not show up in the finished product (a Postscript, DVI or PDF file). Making the changes show up in the finished product requires some additional exercises.

## Directly Inserting Code into the Document's Preamble

This exercise gives you a trivially simple example of changing the finished document's appearance using the Document Preamble.
1. View the original
1. View->Postscript
2. Notice the layout
2. Change and view again
3. Layout->Latex Preamble...
1. In the input box that appears, type these two commands:

2. \setlength{\hoffset}{2 in}
\setlength{\voffset}{2 in}
3. Click the OK button.
4. Save the file (File->Save)
5. View->Postscript
6. Notice that the output is now approximately 2 inches down and to the right.

### Discussion

This exercise illustrates the simplist possible way to insert code in the document preamble in order to change the output. If you remember up until this time everything we did changed the layout in Lyx, but not the final Postscript output. In subsequent exercises you will expand on placing code in the preamble in order to get the final output you want.

# For Real Tutorial -- Adding an Environment

Rename aarticle.layout to aarticle.layout.newbie so the layout you declared there doesn't conflict with this exercise.

Create the following file, called barticle.layout, in your lyx/layouts directory:

 #% Do not delete the line below; configure depends on this #  \DeclareLaTeXClass[article]{article (Whopper Enabled)} # Article textclass definition file. Taken from initial LyX source code # Author : Matthias Ettrich # Transposed by Pascal André # Heavily modifed and enhanced by serveral developers. # Input general definitions Input stdclass.inc # There are no chapters in an article. NoStyle Chapter NoStyle Chapter* MaxCounter              Counter_Section SecNumDepth             3 TocDepth                3 Preamble \newenvironment{whopr}{\begin {Huge}}{\end{Huge}\linebreak} EndPreamble Style Whopper   LatexType             Environment   LatexName             whopr   Align                 Left   AlignPossible         Left   Font     Size                Giant   EndFont End

Next reconfigure Lyx with Edit->Reconfigure. This reads in your new barticle.layout., which implements a style called "article (Whopper Enabled)".

Create a new file called y.lyx, giving it a title, author and a couple sections.

Layout->Document->Document->Class dropdown list, and select article (Whopper Enabled).

Type a couple lines in the standard environment, then press Enter to start a new line, and select Whopper from the environment list, and type a couple lines. You'll notice that the font is very large.

Hit Enter, note that you're still in Whopper environment, and type some more.

Save the file, then View->Postscript, and note that the lines formatted as Whopper are large in the output also.

## Discussion

This is the Real McCoy. The extra large font is seen in both Lyx and in the output (Postscript). This is because the Lyx style, which starts with keyword Style, points to the LaTeX code in the Preamble/EndPreamble section, by virtue of the fact that the style's Latexname value is the same as the LaTeX code's name.

### Explanation of Strategic Lines

#### #  \DeclareLaTeXClass[article]{article (Whopper Enabled)}

This declaration on the second line declares a new class called "article (Whopper Enabled)" to be a class inheriting properties from already defined class "article". The parentheses in the name are just text -- they have no specific syntax function. This is the second line of the .layout file. You'll notice every .layout file has something similar as its second line.

#### Input stdclass.inc

This includes an include file called stdclass.inc, which contains definitions required by any document class. It must appear near the top.

#### Preamble

This line declares that everything between it and the EndPreamble line go in the document's preamble. The preamble is the text above the authored material.

#### \newenvironment{whopr}{\begin {Huge}}{\end{Huge}\linebreak}

This is a LaTeX statement, not a Lyx function or keyword. This statement is passed right through to Latex2e, the LaTeX interpreter.

This command creates a new LaTeX (not LyX) environment. It therefore is reflected in the appearance of the Postscript or DVI output, not in the Lyx program.

The general form for this type of command is:

\newenvironment{name}[num]{before}{after}
{name} is the name of the environment. [num] is optional (all LaTeX encased in square brackets is optional). {begin} contains all text and commands to be executed before printing the content typed into the environment. {after} contains all text and commands to be executed after the content typed into the environment. In this case before the content the font is changed to Huge. After the content the Huge font is removed, reverting text back to its original condition. And then a linebreak is inserted, because we want the Whopper environment to resemble a heading style.

#### Style Whopper

This declares a LyX style governing the appearance in LyX. All the text between this statement and its corresponding End statement (the last line of the file in this case) pertain to this style.

#### LatexType        Environment

The Environment value of LatexType tells Lyx that the style has blocks of commands and text at both the beginning and the end. Other valid values are Paragraph, Command, Environment, Item_Environment, and List_Environment. List and Item Environments are similar to Environment, except they're part of enumerations. Command issues commands only in the beginning, not begin and end like Environment. Paragraph issues no commands at all.

#### LatexName        whopr

This is it folks. This is the link between the LyX appearance and the LaTeX appearance, by linking the LyX style with the LaTeX commands in the Preamble.

#### Font

Between this line and its corresponding EndFont line go all the attributes of the font.

#### Size             Giant

This says the Size attribute of the font is Giant, which is the largest possible in the LyX font size naming system.

### Font Sizes

Speaking of fonts, Lyx and LaTeX have different names for various font sizes. Use the LaTex font sizes in LaTeX commands destined to change the font size in the finished product, and the LyX size designations in LyX style statements.

 LaTeX Font Sizes LyX Font Sizes \tiny Tiny \scriptsize Smallest \footnotesize Smaller \small Small \normalsize Normal \large Large \Large Larger \LARGE Largest \huge Huge \Huge Giant

### \newcommnd, \newenvironment, et al

You just used \newcommand to implement a font size in the finished product, but there are actually several similar LaTeX commands.

#### \newenvironment

The syntax here is:
\newenvironment{name}[num]{before}{after}
Where {name} is the name of the new environment, [num] is optional and beyond the scope of this discussion, {before} is text and commands run before the content, and {after} is the text and commands run after the content. Typically the {after} "undoes"  the effect of the {before}.

\newenvironment must be used ONLY when the environment didn't yet exist. To modify an existing environment use \renewenvironment.

#### \renewenvironment

Syntax and functionality is the same as \newenvironment, except it modifies an already existing environment.
\newenvironment{name}[num]{before}{after}

#### \newcommand

\newcommand{name}[num]{definition}

# Programs to help with Lyx

## makelyxbook.cpp

This software allows you to make dummy Lyx books for the purposes of format and performance testing. You can modify the nature of the book (how many Subsections per Section, and how much standard text gets printed in that subsection), by modifying the source code. At the top of the file (just after the top of file comments) are the following constants you can modify:
#define PARTSPERBOOK 2
#define CHAPTERSPERPART 4
#define SECTIONSPERCHAPTER 4
#define SUBSECTIONSPERSECTION 2
#define SUBSUBSECTIONSPERSUBSECTION 1
#define PARAGRAPHSPERSUBSUBSECTION 2
#define SUBPARAGRAPHSPERPARAGRAPH 2
Because of a bug in the program you can't set any of them to zero, but you can keep them from printing.

At the bottom of the program are the print() methods for each of the Environment objects (Subparagraph, Paragraph, Subsubsection, Subsection, Section, Chapter, Part, Book). To keep one from printing, simply give it an empty print method (or comment out the existing print method code. Code in the print method must print the appropriate header, print the text under the header, and update the Stats object with what has been printed. It's fairly obvious.

Here's how you use the program:

• Create a new Lyx document
• File/New
• Layout/Document/Document
• In the Class dropdown, select either Book, Book (AMS), or Book (Koma-Script)
• Type in the word "placeholder".
• File/Save as, and save as x.lyx.
• Modify makelyxbook.cpp:
• Modify the per-parent constants
• Modify the various class's print() methods
• Compile the program to a.out
• Create the document
• ./a.out > temp.tmp
• vim temp.tmp x.lyx
• Yank entirety of temp.tmp
• Switch to x.lyx
• Paste just before the line saying \the_end
• Save x.lyx and quit vim
• Pull up x.lyx in lyx
 // ####################################################################### // makelyxbook.cpp: Lyx test book creator, version 0.2.0 //   Copyright (C) 2001 by Steve Litt (Steve Litt's email address) // //   This program is free software; you can redistribute it and/or modify //   it under the terms of the GNU General Public License as published by //   the Free Software Foundation version 2 of the License. // //   This program is distributed in the hope that it will be useful, //   but WITHOUT ANY WARRANTY; without even the implied warranty of //   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the //   GNU General Public License for more details. // //   You should have received a copy of the GNU General Public License //   along with this program; if not, write to the Free Software //   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // Steve Litt, Steve Litt's email address, http://www.troubleshooters.com // ####################################################################### // ####################################################################### // ####################################################################### // ####################################################################### // HISTORY // V0.1.0 //    Creates test book in lyx format // //    BUGS: //      The contstants controlling child environment objects must be //      one or greater, even if you do not wish any child objects. //      Placing a value of 0 for any of these will cause in infinite //      loop. //       //      To implement zero child environments in the book, simply //      empty the corresponding class's print() method.  # // //      Version 0.1.0 was a lame OOP implementation. //Steve Litt, 8/16/2001 //End of version 0.1.0 // V0.2.0 //    Replaced OOP with simple loops. Fixed but where you couldn't //    have PER vars with a zero value. Shortened the code. // //    User modifications happen in the PER constants at the top, //    and the print routines at the bottom. // //    BUGS: //      The contstants controlling child environment objects must be //      one or greater, even if you do not wish any child objects. //      Placing a value of 0 for any of these will cause in infinite //      loop. //       //      To implement zero child environments in the book, simply //      empty the corresponding class's print() method.  # // //      Version 0.1.0 was a lame OOP implementation. //Steve Litt, 8/17/2001 //End of version 0.2.0 //END OF HISTORY // //SOURCE CODE CONFIGURATION: //    The test book output is controlled by source code changes to //    two sections of this program. First are the child per parent //    constants (PARTSPERBOOK, CHAPTERSPERPART, //              SECTIONSPERCHAPTER, SUBSECTIONSPERSECTION, //              SUBSUBSECTIONSPERSUBSECTION, //              PARAGRAPHSPERSUBSUBSECTION,and //              SUBPARAGRAPHSPERPARAGRAPH). These constants //    are located at the top of the source file. These constants //    control how many children each environment object has. For //    instance, a CHAPTERSPERPART of 3 would mean each part //    contains three chapters. These constants are at the top //    of the program, just below these comments. //     //    Secondly, each environment has a print routine that //    controls how it prints and how it reports that printing to //    the Stats object. Here is where you control how much //    standard text is printed for each environment object.  //    Those print routines are at the bottom of the program. //     // ####################################################################### #include //********************************************************** //********************************************************** // Modify the following constants to achieve the best structure // and size for your Lyx test document //********************************************************** //********************************************************** #define PARTSPERBOOK 2 #define CHAPTERSPERPART 4 #define SECTIONSPERCHAPTER 4 #define SUBSECTIONSPERSECTION 2 #define SUBSUBSECTIONSPERSUBSECTION 1 #define PARAGRAPHSPERSUBSUBSECTION 0 #define SUBPARAGRAPHSPERPARAGRAPH 0 //********************************************************** //********************************************************** // End of modifiable constants //********************************************************** //********************************************************** void printBook(int n); void printPart(int n); void printChapter(int n); void printSection(int n); void printSubsection(int n); void printSubsubsection(int n); void printParagraph(int n); void printSubparagraph(int n); //******************************************************* //             Stats class //******************************************************* class Stats         {         long Words;         long Lines;         long Subparagraphs;         long Paragraphs;         long Subsubsections;         long Subsections;         long Sections;         long Chapters;         long Parts;         public:         long getWords(){return Words;};         long getLines(){return Lines;};         long getSubparagraphs(){return  Subparagraphs;};         long getParagraphs(){return  Paragraphs;};         long getSubsubsections(){return  Subsubsections;};         long getSubsections(){return  Subsections;};         long getSections(){return  Sections;};         long getChapters(){return  Chapters;};         long getParts(){return  Parts;};         void incWords(long a){Words += a;};         void incLines(long a){Lines += a;};         void incSubparagraphs(long a){Subparagraphs += a;};         void incParagraphs(long a){ Paragraphs+=a;};         void incSubsubsections(long a){ Subsubsections+=a;};         void incSubsections(long a){ Subsections+=a;};         void incSections(long a){ Sections+=a;};         void incChapters(long a){ Chapters+=a;};         void incParts(long a){ Parts+=a;};         void setWords(long a){Words = a;};         void setLines(long a){Lines = a;};         long setSubparagraphs(long a){ Subparagraphs=a;};         long setParagraphs(long a){ Paragraphs=a;};         long setSubsubsections(long a){ Subsubsections=a;};         long setSubsections(long a){ Subsections=a;};         long setSections(long a){ Sections=a;};         long setChapters(long a){ Chapters=a;};         long setParts(long a){ Parts=a;};         void show();         }; void Stats::show()         {         cout << endl << endl;         cout << "Words = " << getWords() << "," << endl;         cout << "Lines = " << getLines() << "," << endl;         cout << "Subparagraphs = " << getSubparagraphs() << "," << endl;         cout << "Paragraphs = " << getParagraphs() << "," << endl;         cout << "Subsubsections = " << getSubsubsections() << "," << endl;         cout << "Subsections = " << getSubsections() << "," << endl;         cout << "Sections = " << getSections() << "," << endl;         cout << "Chapters = " << getChapters() << "," << endl;         cout << "Parts = " << getParts() << endl << "." << endl;         } Stats stats; long printLine(long a)         {         cout << "\\layout Standard" << endl << endl;         for(int n=0;n

## otl2lyx.vim

The following Vim script converts an outline with tab defined indentation into Lyx code suitable for the structure of a book:

 :%s/^/lyxxyl/ :%s/^lyxxyl^I^I^I^I^I^I/\\layout Subparagraph\r\r/ :%s/^lyxxyl^I^I^I^I^I/\\layout Paragraph\r\r/ :%s/^lyxxyl^I^I^I^I/\\layout Subsubsection\r\r/ :%s/^lyxxyl^I^I^I/\\layout Subsection\r\r/ :%s/^lyxxyl^I^I/\\layout Section\r\r/ :%s/^lyxxyl^I/\\layout Chapter\r\r/ :%s/^lyxxyl/\\layout Part\r\r/

### Note the following:

• Replace each ^I with a tab character.
• Because of the \r substitutions, this works only in UNIX like environments.
• Because of the use of \r\r the preceding works only on Linux/Unix/BSD boxes. It won't work in a Windows environment.
• The preceding is for Book or Koma-script Book or AMS Book document class.
• You must append it onto a empty lyx file created with the Book or Koma book document class. Use Vim or other quality text editor to do the appending.
• WARNING! Do not use otl2lyx.vim directly, as it could mess up your outline. Instead call it from a script that first copies your outline to a temporary file so the vim script can work on the temporary file.
• Note that lyxxyl is simply a place holder -- it could be any string unlikely to occur in the original outline.
• If you're looking for an outline processor to do tab indented outlines, and you know VI, you can use VimOutliner at http://www.troubleshooters.com/projects/vimoutliner/index.htm.

### Using otl2lyx.vim to Fill a Lyx Book With Your Outline Structure

• Create a new Lyx document
• File/New
• Layout/Document/Document
• In the Class dropdown, select either Book, Book (AMS), or Book (Koma-Script)
• Type in the word "placeholder".
• File/Save as, and save as x.lyx.
• Run otl2lyx.vim
• Make a temporary copy of the outline to be converted to Lyx. To preserve the integrity of your original outline, you'll process only the temporary copy.
• Edit the temporary copy in the Vim editor on a UNIX, BSD, Linux, or any other UNIX workalike. Because of the \r line insertions, this won't work on Windows.
• From within Vim, run otl2lyx.vim with the following command:

• : source otl2lyx.vim
• Note that your file now looks like Lyx code.
• Save with the :w command.
• Insert the Lyx-ized outline into your new Lyx document
• From the top of the file, type yG to yank (copy) the entire file into the main register
• Edit the Lyx doc you created earlier with the following command:

• : e x.lyx
• Place your cursor on the word "placeholder" you typed earlier. It will be near the bottom of x.lyx.
• Copy the lyx-ized version of your outline by pressing P (upper case P).
• Go to the bottom of the file again and find the line that says "placeholder".
• Delete the line that says "placeholder".
• File/save
• x.lyx now contains the exact structure of your original outline.

# Strongarming the date in a LyX document

Many LyX documents "help" you by automatically inserting a date in the document, and if you don't say otherwise, it will be the date it's printed or converted to postscript or PDF. Obviously this isn't what you want.

To fix the date at the date the doc was written, do one of these two things:

1. Hardcode the desired date in the Date environment.
2. Hardcode \date{1/30/2002} as ERT (TeX) at the top of the document
Note that because the Letter document class has no date environment, only #2 will work in letters.

# Incorporating Layout Files

LyX finds its layout files in two places:
1. In ~/.lyx/layouts/.
2. In the /usr/local/texmf/tex/latex/ tree
But maybe you really want your layout (mybook.layout) in the directory containing mybook.lyx (/data/books/mybook). That way the layout file is always backed up with the book, and isn't trashed when you reinstall the operating sytsem. To accomplish that, you simply create a symbolic link:

ln -s /d/at/books/utp/utpbook.layout /home/slitt/.lyx/layouts/utpbook.layout`
After doing this, you might need to run the texhash program, and you'll probably need to perform Edit->Reconfigure from the Lyx menu.

However, you might want your layout file to accompany your book document's file. Remember, your book document is worthless without the layout file that produced it, and even if you manage to recreate the layout file, any differences will cause big changes in the book.

You can
.