## Troubleshooters.Com, T.C Linux Library and Litt's LyX Library Present

LyX, LaTeX and TeX

Contents

# Why You Need LaTeX

In many ways, LyX is an excellent tool for writing books and other long documents. LyX is a document typesetter producing beautifully laid out and typeset documents. From the user point of view, it's works like a wordprocessor. You type content, and when necessary apply styles (in LyX they're called "environments") to text by picking them out of a picklist. There are facilities to invisibly place codes in the text, but that's rarely necessary.

Sounds like the best of all possible worlds, doesn't it? There's just one small problem. If you need to modify an existing style (environment) or make a new one, you must modify or create the environment using a markup language called LaTeX. The learning curve for LaTeX is both deep and broad. In my opinion it's harder to learn than C, C++, Java, Perl and the like. But learn it you must, unless you're willing to accept every LyX default for the document class you've chosen.

Why must LyX environments be created or modified in LaTeX? It's because of the nature of LyX. LyX is a front end for the LyX native format, and it's also a converter from the LyX native format to a format called LaTeX. Then a separate program, called latex, or latex2e, or maybe something similar, converts the LaTeX to a "device independent" file with a .dvi extension. The cool thing about .dvi files is they print the same on all printers (always assuming the correct drivers. The display the same on all GUI terminals, always assuming the correct display programs. In Linux, the correct display program is dvisee.

Today, the .dvi format isn't used much. Instead, it's further converted to Postscript (.ps) or Acrobat (.pdf) for printing and viewing. Because .dvi, .ps and .pdf are all device independent, the conversion is pretty straightforward.

OK, so you need LaTeX, LaTeX can be harder to learn than C, C++, Java, Perl and the like, but to create and modify LyX environments you must learn LaTeX. How do you learn it? In my opinion you need to drop down one more abstraction, to a file format called TeX.

# TeX

TeX is a programming language, created by computer master Donald Knuth, to create books and other sizeable documents. TeX language source is converted to  a .dvi file by the tex program. The .dvi file is a fully laid out document whose appearance is identical on all printers and viewers. It's DeVice Independent (hence the .dvi).

Here's a Hello World program in TeX:

 hello world\bye

Now compile with tex and view it with dvisee as follows:
 [slitt@mydesk lyx]$tex hello_tex.texThis is TeX, Version 3.141592 (Web2C 7.5.5)(./hello_tex.tex [1] )Output written on hello_tex.dvi (1 page, 224 bytes).Transcript written on hello_tex.log.[slitt@mydesk lyx]$ dvisee hello_tex.dviThis is dvips(k) 5.95b Copyright 2005 Radical Eye Software (www.radicaleye.com)' TeX output 2007.01.13:1410' -> . [1]

Here's what you'll view in dvisee:
 The output is hello_tex.dvi. When viewed in dvisee, it has the phrase "hello world" on the top left, and the page number 1 in the center near the bottom. You can click on the image to see a larger and more readable image.

Few printers can directly handle .dvi files. You can convert the .dvi to a .ps postscript file like this:
dvips -o hello_tex.ps hello_tex.dvi
If you have a postscript printer, it will directly print the .ps file, but for other printers you need to further convert it to a .pdf file:
ps2pdf hello_tex.ps
Here's a diagram of this process:

A TeX source file is comprised of multiple commands. Remembering the Hello World program, in the string "hello world", each letter is a command that basically says "print me". \bye is a command basically saying "this source file has ended, so convert it to .dvi.

## TeX's Key Distinction

TeX's key distinction, the thing that sets it apart from other programming languages, is that its entire purpose is creating formatted documents, regardless of printer. So, for instance, it knows everything about fonts (at least those that have been associated with TeX), and prints letters with the right size and shape. Therefore, TeX is in a position to handle all line wrap and page wrap.

TeX has commands to change page layout and paragraph margins. Once they change, further text obeys those new commands.

In TeX, the paragraph is a special entity commensurate with its purpose in documents. The old paragraph is stopped and the new one begun using a blank line between text. You can use one blank line or a hundred, but in the output you'll just get the standard interparagraph spacing (or maybe no spacing if you're indenting paragraphs instead). Likewise, you can use one or twenty spaces between words, but in the finished document all words are separated by the standard inter-word distance.
 \font\normfont = cmbx12\font\bigfont = cmbx18\font\titleifont = cmmib24 % not used\font\titlefont = cmbx24\advance\vsize by 3in\headline{\normfont Page \folio\hfil{\titlefont Steve Was Here}\hfil By Steve Litt}\normfont\leftskip 1.5in\rightskip 1.5in Steve was here,and now is gone,but left his name,to carry on. This was a little bit of circa 1968 Southside poetry.\vskip 0.1in\bigfont\leftskip 0in\rightskip 0in For every neighborhood, in every age, thereis poetry. If you know the poetry, you understand. Poetry is {\italways} good, but sometimes even better.Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. \vskip 3inSteve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. \vskip 3inSteve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. Steve was here and now is gone, but left his name to carry on. \bye To the left is an example TeX file using fonts, indentation, a header, and vertical skipping. First we define several fonts (normfont, bigfont and titlefont). Then we create a one line header with \headline. The header has a page number on the left, a large title in the center, and the author on the right. See the two \hfil commands? They act like compressed air, pushing elements away from each other. That's how you can left, center and right align the three components. The text of the file starts with the first paragraph, which uses normfont, a 12 point font. The first paragraph's margins are shrunken 1.5 inches on each side (\leftskip 1.5in\rightskip 1.5in). The second paragraph uses bigfont, a monstrous 18 pointer. This paragraph has the normal margins (\leftskip 0in\rightskip 0in). The word "always" in the second paragraph is italic, because of the \it inside of a block delimitated by curly braces. Intuitively one would assume the current font would be italicized, but in fact it replaces the current font with the document's default font, italicized, hence the smallness. The paragraphs that follow are just filler so you can see that the header shows up on page 2 also, and the page number changes. Note that subsequent paragraphs are separated not by blank lines, but by \vskip commands. The switch from horizontal commands (the letters) to a vertical command (\vskip) ends the paragraph.

 The preceding code produces the output at the left. You can see the header with its page numbering on the left, its title large in the center, and its author on the right. Once again, this spacing was accomplished by the \hfil command. The first paragraph is 12 point and the second is 18. You can see the word "always" is italic, but it's small. The first paragraph's margins are both pulled in 1.5 inches. The second paragraph has normal margins, and is written in 18 point type. Subsequent paragraphs are just filler. The large space between the second and third paragraphs is accomplished by the \vskip 3in command. You can click the graphic to see a larger version.

 To the left is page 2 of the document. You'll notice that the header appears on page 2, and the page number caused by the \folio command has been updated. TeX provides other, more useful ways to make headers. You'll notice that the header hugs right up against the text, which is confusing to the reader. As far as I can tell, there's no way to space it differently with the \headline command.

## So What?

What you've seen so far is unimpressive. You've seen a computer language in which the "programmer" can specify each and every look and feel on each and every page. Busywork! It's kind of like MS Notepad with formatting. Who cares?

TeX would be a non-starter if it weren't for one feature not yet discussed -- macros. A macro is a programmer defined command -- a subroutine if you will. You see, TeX is a Turing complete language capable of calculations, iteration, and everything else a full featured language can do. Using Macros, you can make TeX into a really handy book writing application.

# TeX Macros

This section creates a section macro and a subsection macro, complete with correct numbering, and changing of the header with section names. The code is crude, with the sole purpose of demonstration of TeX's macro ability. However, after you read this section, I think you'll understand why, with the proper macros, TeX can be used to write a book.

 \font\normfont = cmbx14\font\sectfont = cmbx24\font\subsectfont = cmbx18\font\hdrfont = cmbx24\newcount\sectno\sectno = 0\newcount\subsectno\subsectno = 0\def\secttext {undefined}\headline{\hdrfont\secttext\dotfill Page \folio}\def\section#1{ \def\secttext {#1} \subsectno = 0 % reset subsection counter \advance\sectno by 1 {\sectfont~\par\vskip 0.7in Section \number\sectno: #1 \par\vskip 0.1in}}\def\subsection#1{ \advance\subsectno by 1 {\subsectfont ~\par\vskip 0.3in Subsection \number\sectno.\number\subsectno: #1 \par\vskip 0.1in}}\normfont\section{Musicians}Several musicians have made their mark over the pastdecades. This section has a few examples.\subsection{Jimi Hendrix}Jimi Hendrix is known as "the best guitar player ever". Helearned to play guitar on a broom, and then restrung a righthanded guitar to play it left handed. He was able to playrhythm and lead guitar at the same time.What often escapes notice is Jimi's lyrical skill. Everysong had a poetry of its own. His music went far beyond the"acid rock" genre for which he was often credited.\subsection{Justin Timberlake}Justin Timberlake is bringing Sexy back. J. Timberlakehow heavy is that!\subsection{Steve Litt}Steve Litt is known as "the worst guitar player ever". Afixture on the wall outside Columbus Ohio's "Ohio StaterInn" in the summer and fall of 1977, he hit the nadir of hisprofessional career earning 37 cents and a half loaf ofcheese in one night.\section{Athletes}\subsection{Carl Lewis}Carl Lewis broke Bob Beamon's "unbreakable" long jumprecord. He won gold medals in the 1984, 1988, 1992 and 1996olympics.\subsection{Mark McGwire}Give the guy a break. At the time he took them, thesupplements he took were legal. He broke Roger Maris'srecord by 9. There's absolutely no doubt that he shatteredit. He won a Golden Glove award for fielding in 1990. Puthim in the Hall of Fame.\subsection{Barry Bonds}OK, let's say it: Steroids. Barry Bonds never testedpositive for steroids. Even if he had, they were not againstthe Major League Baseball standards before 2003, and Barry'shome run record of 73 occurred in 2001. He's a good fielder,and a consumate base stealer. He won the Most ValuablePlayer (MVP) in 1990, 1992, 1993, 2001, 2002, 2003 and 2004.Did he take steroids? I don't know. Did McGwire? Other thana legal over the counter supplement, I don't know. Did allthe others? I don't know. But don't blame Barry Bonds forthe fact that baseball had no steroids policy til 2003. Votehim into the hall of fame.\subsection{George Foreman}One of the hardest punchers of all time, George Foreman wonthe Heavyweight Gold in the 1968 Olympics. Turning pro, onJanuary 22, 1973, he became heavyweight champion by knockingout Joe Frazier in the second round. In 1974 he knocked outKen Norton, hitting Norton so hard that Norton rolled like aball across the ring. Foreman was invincible.On October 30, 1974, Foreman fought former champion MuhammadAli, who, at 34, was approaching the twilight of his career.Ali outsmarted Foreman by covering his face and body to theextent possible, and letting the young but less experiencedForeman use him as a punching bag. Foreman tired, and in the8th round Ali knocked out Foreman. Following a 1977 loss toJimmy Young, a disallusioned George Foreman retired fromboxing and became a Minister.Ten years later, at the age of 38, George Foreman began along comeback. In 1991 he went a full 12 rounds withchampion Evander Holyfield but failed to win. Continuing tobox, on November 5, 1994, at the age of 45, George Foremanknocked out Michael Moorer for the IBF and WBA titles.Foreman might have been old and slow, but his nuclearpowered punches overwhelmed Michael Moorer.George Foreman retired for good in 1997, at the age of 48.\subsection{Tanya Harding}I liked Tanya Harding. She could jump like a grasshopper.She twirled like a radar star. She was pretty, and comparedto Nancy Kerrigan's gawkiness, she was an eagle in flight.Yeah, she had to be disqualified, but a lot of the "trailertrash" talk that followed was just plain mean spirited. Doesone need a pedegree to medal in ice skating? If so, maybe itshould be a marginal sport like curling and lacrosse.\subsection{Steve Litt}Steve Litt was a speed skater for the Venice Speed Demonsoutdoor speed team in the early 1980's. Learning to skate in1978, he placed third in a Chicago skate race in the fall of1979.Moving to California, he placed third in the 30-40 agecategory at the Riverside 10K in 1980, and the Long BeachMarathon in 1981. Although considered washed up, he skatedfirst pack in a 1983 Southern California "bootleg" race.Litt became a computer programmer in late 1983, gainedweight, and became less effective on wheels. In his lastcompetitive race in 1984, the Venice race, he could placeonly 4th in the 30-40 age category, even though the raceattracted only local talent. He continued practice skatingwith the Venice Speed Demons until his retirement in 1986.\section{Intellectuals}The last few centuries offered no shortage of intellectuals.Here's a very partial list.\subsection{Albert Einstein}Albert Einstein developed the theory of relativity,including $e = mc^2$.\subsection{John Stuart Mill}John Stuart Mill (1807-1873) was an economist andphilosopher. Mill's system of logic, consisting offive methods, formed the foundation of Steve Litt's latercontributions in the Universal Troubleshooting Process.\subsection{Justin Timberlake}Not!\subsection{Steve Litt}Steve Litt formulated the Universal Troubleshooting Processwhile working as an electronic technician, refining it overthe years to make it easier for the masses to learn.\bye To the left is code to write a short essay on musicians, athletes and intellectuals, complete with correctly numbered sections and subsections. The code starts out by defining four fonts that will be used throughout. It then declares and initializes three global variables, sectno, subsectno and secttext. sectno and subsectno are counts, while technically secttext is a macro because it's comprised of commands, even though those commands are just letters. The header, created with a \headline command, shows the header name (\secttext) and the page number. The heart of this document is the \section macro and the \subsection macro. Both print their argument (#1), but in addition they also increment and print their respective counters. The \section macro also zeros out the subsection counter, because generally speaking subsections are subservient to sections and therefore should restart upon section change. Subsection numbers are printed in the section.subsection format. Below the \subsection definition, the actual text of the document begins. You'll notice that thanks to the header and macros, writing of the document itself is rather straightforward. This example, while understandable, doesn't even begin to scratch the surface of TeX macro capabilities. You'll notice that \section and \subsection commands automatically terminate the macro that came before, so there's no necessity to insert a blank line, although blank line insertion would neither harm nor change anything, but simply make the source more readable. To see how this works, copy and paste the code to the left into a file, and compile the file with TeX. The first page looks like this: As you can see, sections print their section numbers and then the section name, which is an argument sent from the main document. Subsections print the section number in section.subsection format, and then the name. If you compile the source to the left and look at all pages, you'll see that the header of each page contains the section name of the section in force at the bottom of the page.

So that's it. On the surface, TeX is a low level publishing language requiring micromanaging. However, TeX's extensive Macro capabilities mean that with some up front work, macros can substitute for voluminous repetitive code.

How far can one take TeX macros? Keep asking yourself that question...

# Styles, Macros, Groups and Environments

Styles are blocks of text with certain properties. Paragraph styles apply those properties to the whole paragraph, including margins, spacing, and font. Character styles apply the properties just to a word or phrase, meaning it influences only font. Styles can be accomplished in different ways.

In the example of TeX macros (the one with musicians, athletes and intellectuals), sections and subsections are paragraph styles. Each is implemented with a single macro implementing the properties, where the argument to the command is the text to which the properties are applied. This is an excellent way to implement a style over just a few words.

Another way to implement a style in TeX is to place a command defining the desired properties right after an opening curly brace ({), in which case those properties persist until encountering a matching closing curly brace (}). The area between braces is called a group. Groups can be nested, meaning it's somewhat practical to apply this type of style over several paragraphs. I say "somewhat" because the brace matching can become a debugging nightmare.

One way to eliminate the horrors of bracket matching across several paragraphs of text is with the abstraction of paired macros. For instance, you might create two macros called \beginstory and \endstory, whose job is to implement a style with narrower margins and italic type. The entire story, not each paragraph of the story, but the story itself, should be bordered top and bottom with a row of dots, and beyond the dots be bordered top and bottom with 1/2 inch of blank space. So what you do is code \beginstory so that it first skips 1/2 inch down, then begins a group, then shrinks the margins and declares an italic font, then draws a row of dots. You code the \endstory command to first draw a line of dots, then end the group, then skip 1/2 inch down.

The preceding paragraph's references to beginning and ending a group refer to commands \begingroup and \endgroup. You use these instead of curly braces because the curly braces would conflict with the curly braces beginning and ending the definition of the commands. Here's a sample TeXdocument with such a \begingroup and \endgroup:
 \def\beginstory{ ~\vskip 0.5in % Skip down 1/2 before story \begingroup % Start of formatting properties \leftskip 1in\rightskip 1in % Wider margins for narrower text \it % Italic font \noindent{.\dotfill{}.\par} % Make dotted line % Text after close of \beginstory will be story formatted}\def\endstory{ \par\noindent{.\dotfill{}.\par} % Make dotted line \endgroup % End of formatting properties ~\vskip 0.5in % Skip final 1/2 inch}Here's a story about the formative era of personal computing. Ioriginally wrote it in 1999, but the point it makes is still valid.Hope you like it.\beginstory It was an age of heros, those days. Men of action, ofvision, of legend. Ed Roberts, Gary Kildall, Jobs and Woz, Paul andBill, Philippe Kahn. Richard Stallman and Linus Torvalds. Theyswashbuckled across the technological stage, making their mark. Theytook naked chips and gave them soul. It seems so long ago, lookingback from our perspective of comfort and complacency. We stand ontheir shoulders, and they deserve our credit and our thanks. Theyshaped our world.But that was a long time ago.Where have all the heros gone? Did innovation die in 1990? Maybe nowsoftware is just too big for one person to deliver full blown into theworld. Maybe we live in a world of big teams and little advances.These are not the days of heros. Or are they?Did you know that a heavy duty data enabled web developmentenvironment, called Zope, has surfaced as free software within thelast year? Did you know that a group is now writing a portable, freesoftware Clipper workalike? Did you know that both Perl and Pythonhave XML interfaces already? Do you think five years from now some ofthese people might be considered heros?So next time time you're at your Linux User Group meeting, look aroundthe room. That guy sitting next to you just might be the next hero. Ormaybe the next hero is even closer. Think about that the next time youlook in the mirror.\endstoryI wrote that story in 1999 as part of a Troubleshooting ProfessionalMagazine issue themed "Where Have All The Heroes Gone". The nextmonth's issue, themed "More Heroes, and a Trip to Linux Expo" featuredan article on a college kid named Mark Spencer, who had coded up agraphical network monitoring app, an AOL client for Linux, a PPP/VPNapp, and an app that makes your Linux box seem like a simple modemconnection to your Palm Pilot. The article ended like this: "Who arecomputing's future heroes? Only time will tell. I'm keeping a closeeye on Mark Spencer."Eight years later Mark Spencer's company, now called Digium, employs50 employees and and rakes in over \$10 million in revenue. They're ahardware company. Their niche -- selling preloads of Asterisk, thefree software PBX system created by Mark Spencer. The heroes just keepon coming.\bye As mentioned, this is a macro pair. begins the \beginstory part of the text that should be vertically surrounded by dotted lines and then spaces, horizontally surrounded by a wider margin, and text formatted in italics. \endstory ends the part. The code plus comments (everything to the right of a percent sign is a comment) make things clear enough. Here's what the output looks like (you can click it to see a bigger version): As you can see, the output is exactly as needed. This code is a proof of concept. Real pair macros have all sorts of error checks to throw an intelligent error if you insert one without the other, or if they include things that shouldn't be included. The preceding code abstracted format change over a long run of text to a macro pair. You can abstract even farther by creating environments. You notice I said creating environments. Environments are NOT native to TeX. You create them as macros. You create macros called \environment and \endenvironment that work on anonymous variables to do similar things as command pairs. Making environments in TeX is waaayyyy beyond the scope of this document, but that's OK, because fortunately, LaTeX is just an incredibly complete group of TeX macros, and LaTeX includes environments already fully coded for your use. # LaTeX The LaTeX set of TeX macros is so powerful that LaTeX code bears a familiarity, but not really a resemblance, to TeX. If one were to make a C language analogy, TeX would be like C with only stdio.h and stdlib.h, while LaTeX is more like C with all header files. But that's not a good analogy. The header files (and associated library code) might cut the application developer's job by a factor of 10, but the application developer's code is still just plain C. Perhaps a better analogy is that TeX is C++, and LaTeX is the Standard Template Library. Pure STL code bears little resemblance to its C++ underpinnings. It's a bunch of subroutine calls. How would you like to program in pure STL without C++ knowledge. It's doable until you need to code something not available in the STL. Then you're stuck. It's the same with LaTeX and TeX. LaTeX does more with less. If you mostly use defaults, it's easy. But when you need to go offroad, sometimes you need to drop back to TeX. That's why it's essential to know TeX, and fortunately, TeX is fairly straightforward. Here's a hello world LaTeX document:  \documentclass[12pt]{article}\begin{document}Hello World\end{document} The LaTeX \documentclass built-in macro probably does a hundred things. For one thing, it sets the document's default font to 12 point. It declares and initializes a vast number of variables, commands and counters. It also declares the document to be of document class article, which yields a certain look and feel, as well as determining what environments are and are not available.For instance, there's no chapter environment in this document class -- you'd need the book document class to get chapters. LaTeX implements macros \begin and \end. These are a generic pair whose argument determines the environment that's being begun or ended. LaTeX makes it much easier to code environments. Here's a generic environment definition:  \newenvironment{environment_name}{stuff to do before text}{stuff to do after text} That's it -- the \newenvironment macro takes three arguments: 1. The name of the environment being created 2. The stuff to do before the text being assigned that environment 3. The stuff to do after the text being assigned that environment The resemblance to TeX paired macros is obvious, but LaTeX environments make it generic across all environments, and place the beginning and ending code in one place. Not only that, but because the environment has one name instead of two different names, it's very easy for a front end like LyX to assign environments to highlighted stretches of text. The \newenvironment macro works only when environment_name is undefined. If there's already an environment with that name, use \renewenvironment instead. If you don't know, there are ways to test. The following is a LaTeX version of the \beginstory / \endstory example, with the two macros folded into the definition of one environment called story.  \documentclass[12]{article}\setlength\textwidth {6.5in} % Widen from article default\setlength\evensidemargin {0in} % Bring back left on even pages\setlength\oddsidemargin {0in} % Bring back left on odd pages\newenvironment{story}{ ~\vskip 0.5in % Skip down 1/2 before story \begingroup % Start of formatting properties \leftskip 1in\rightskip 1in % Wider margins for narrower text \it % Italic font \noindent{.\dotfill{}.\par} % Make dotted line % Text after close of \beginstory will be story formatted}{ %%%%%% "\endstory" follows \par\noindent{.\dotfill{}.\par} % Make dotted line \endgroup % End of formatting properties ~\vskip 0.5in % Skip final 1/2 inch}\begin{document}Here's a story about the formative era of personal computing. Ioriginally wrote it in 1999, but the point it makes is still valid.Hope you like it.\begin{story} It was an age of heros, those days. Men of action, ofvision, of legend. Ed Roberts, Gary Kildall, Jobs and Woz, Paul andBill, Philippe Kahn. Richard Stallman and Linus Torvalds. Theyswashbuckled across the technological stage, making their mark. Theytook naked chips and gave them soul. It seems so long ago, lookingback from our perspective of comfort and complacency. We stand ontheir shoulders, and they deserve our credit and our thanks. Theyshaped our world.But that was a long time ago.Where have all the heros gone? Did innovation die in 1990? Maybe nowsoftware is just too big for one person to deliver full blown into theworld. Maybe we live in a world of big teams and little advances.These are not the days of heros. Or are they?Did you know that a heavy duty data enabled web developmentenvironment, called Zope, has surfaced as free software within thelast year? Did you know that a group is now writing a portable, freesoftware Clipper workalike? Did you know that both Perl and Pythonhave XML interfaces already? Do you think five years from now some ofthese people might be considered heros?So next time time you're at your Linux User Group meeting, look aroundthe room. That guy sitting next to you just might be the next hero. Ormaybe the next hero is even closer. Think about that the next time youlook in the mirror.\end{story}I wrote that story in 1999 as part of a Troubleshooting ProfessionalMagazine issue themed "Where Have All The Heroes Gone". The nextmonth's issue, themed "More Heroes, and a Trip to Linux Expo" featuredan article on a college kid named Mark Spencer, who had coded up agraphical network monitoring app, an AOL client for Linux, a PPP/VPNapp, and an app that makes your Linux box seem like a simple modemconnection to your Palm Pilot. The article ended like this: "Who arecomputing's future heroes? Only time will tell. I'm keeping a closeeye on Mark Spencer."Eight years later Mark Spencer's company, now called Digium, employs50 employees and and rakes in over \$10 million in revenue. They're ahardware company. Their niche -- selling preloads of Asterisk, thefree software PBX system created by Mark Spencer. The heroes just keepon coming.\end{document} As mentioned, we tweak the margins to undo the article document class defaults, which would have made the story text so narrow it would have gone on to the next page. Then we basically just copy the code from the old \beginstory and \endstory into the second and third argument of \newenvironment. Instead of delineating the text to be formatted with \beginstory and \endstory, it's delineated with  \begin{story} and \end{story}, where \begin and \end are LaTeX provided macros and story is the environment name. If you're LaTeX literate you're grimacing now because this is LaTeX written with a TeX accent. It's an example to make LaTeX easier to understand. Speaking about TeX accents, LaTeX eliminates the need to include \begingroup and \endgroup -- LaTeX does the equivalent thing for you, so you can safely delete those two lines from the story environment.

And here's a doc that implements sections and subsections:
 \documentclass[12pt]{article}\usepackage{fancyhdr}\pagestyle{fancy}\begin{document}\section{Musicians}Several musicians have made their mark over the past decades. Thissection has a few examples. \subsection{Jimi Hendrix}Jimi Hendrix is known as \char\"{}the best guitar playerever\char\"{}. He learned to play guitar on a broom, and thenrestrung a right handed guitar to play it left handed. He was able toplay rhythm and lead guitar at the same time.What often escapes notice is Jimi's lyrical skill. Every song had apoetry of its own. His music went far beyond the \char\"{}acidrock\char\"{} genre for which he was often credited. \subsection{Justin Timberlake}Justin Timberlake is bringing Sexy back. J. Timberlake how heavy isthat! \subsection{Steve Litt}Steve Litt is known as \char\"{}the worst guitar playerever\char\"{}. A fixture on the wall outside Columbus Ohio's\char\"{}Ohio Stater Inn\char\"{} in the summer and fall of 1977, hehit the nadir of his professional career earning 37 cents and a halfloaf of cheese in one night. \section{Athletes}\subsection{Carl Lewis}Carl Lewis broke Bob Beamon's \char\"{}unbreakable\char\"{} longjump record. He won gold medals in the 1984, 1988, 1992 and 1996olympics.\subsection{Mark McGwire}Give the guy a break. At the time he took them, the supplements hetook were legal. He broke Roger Maris's record by 9. There'sabsolutely no doubt that he shattered it. He won a Golden Glove awardfor fielding in 1990. Put him in the Hall of Fame.\subsection{Barry Bonds}OK, let's say it: Steroids. Barry Bonds never tested positive forsteroids. Even if he had, they were not against the Major LeagueBaseball standards before 2003, and Barry's home run record of 73occurred in 2001. He's a good fielder, and a consumate base stealer.He won the Most Valuable Player (MVP) in 1990, 1992, 1993, 2001, 2002,2003 and 2004.Did he take steroids? I don't know. Did McGwire? Other than a legalover the counter supplement, I don't know. Did all the others? I don'tknow. But don't blame Barry Bonds for the fact that baseball had nosteroids policy til 2003. Vote him into the hall of fame.\subsection{George Foreman}One of the hardest punchers of all time, George Foreman won theHeavyweight Gold in the 1968 Olympics. Turning pro, on January 22,1973, he became heavyweight champion by knocking out Joe Frazier inthe second round. In 1974 he knocked out Ken Norton, hitting Nortonso hard that Norton rolled like a ball across the ring. Foreman wasinvincible.On October 30, 1974, Foreman fought former champion Muhammad Ali, who,at 34, was approaching the twilight of his career. Ali outsmartedForeman by covering his face and body to the extent possible, andletting the young but less experienced Foreman use him as a punchingbag. Foreman tired, and in the 8th round Ali knocked out Foreman.Following a 1977 loss to Jimmy Young, a disallusioned George Foremanretired from boxing and became a Minister.Ten years later, at the age of 38, George Foreman began a longcomeback. In 1991 he went a full 12 rounds with champion EvanderHolyfield but failed to win. Continuing to box, on November 5, 1994,at the age of 45, George Foreman knocked out Michael Moorer for theIBF and WBA titles. Foreman might have been old and slow, but hisnuclear powered punches overwhelmed Michael Moorer.George Foreman retired for good in 1997, at the age of 48. \subsection{Tanya Harding}I liked Tanya Harding. She could jump like a grasshopper. She twirledlike a radar star. She was pretty, and compared to Nancy Kerrigan'sgawkiness, she was an eagle in flight.Yeah, she had to be disqualified, but a lot of the \char\"{}trailertrash\char\"{} talk that followed was just plain mean spirited. Doesone need a pedegree to medal in ice skating? If so, maybe it should bea marginal sport like curling and lacrosse. \subsection{Steve Litt}Steve Litt was a speed skater for the Venice Speed Demons outdoorspeed team in the early 1980's. Learning to skate in 1978, he placedthird in a Chicago skate race in the fall of 1979.Moving to California, he placed third in the 30-40 age category at theRiverside 10K in 1980, and the Long Beach Marathon in 1981. Althoughconsidered washed up, he skated first pack in a 1983 SouthernCalifornia \char\"{}bootleg\char\"{} race.Litt became a computer programmer in late 1983, gained weight, andbecame less effective on wheels. In his last competitive race in 1984,the Venice race, he could place only 4th in the 30-40 age category,even though the race attracted only local talent. He continuedpractice skating with the Venice Speed Demons until his retirement in1986.\section{Intellectuals}The last few centuries offered no shortage of intellectuals. Here's avery partial list. \subsection{Albert Einstein}Albert Einstein developed the theory of relativity, including \$e =mc\textasciicircum{}2\$.\subsection{John Stuart Mill}John Stuart Mill (1807-1873) was an economist and philosopher. Mill'ssystem of logic, consisting of five methods, formed the foundation ofSteve Litt's later contributions in the Universal TroubleshootingProcess. \subsection{Justin Timberlake}Not! \subsection{Steve Litt}Steve Litt formulated the Universal Troubleshooting Process whileworking as an electronic technician, refining it over the years tomake it easier for the masses to learn.\end{document} Here we start the source with the typical \documentclass macro. The next two macros, \usepackage{fancyhdr} and \pagestyle{fancy} set the headers to reflect the last section on the page. In addition, they reflect the first subsection on the page, and also put a nice little line under the header. I tried for hours to achieve that line with TeX and was unable to do it. These two lines of LaTeX substitute for who knows how many lines of complex TeX. Behold the power of LaTeX. In the LaTeX source, sections and subsections are about the same as in TeX. They do the numbers right, even though I didn't have to write a single line of code to get that to happen. In the LaTeX version, the word "Section" doesn't appear before the section number because that's not the default behavior of the article document class (or most other document classes either), but it wouldn't have been hard to get it to happen. Below is page 1 of the output (you can click the image to see a larger view). The graphic that follows is page 2. Here you can clearly see that the header includes both the last section on the page and the first subsection on the page: LaTeX relieves the writer from having to get into the bowels of TeX, at least to the extent that the writer is willing to use the document class's defaults. The other thing about LaTeX is it requires broad knowledge of the various packages available (such as fancyhdr)., but relieves part of the need of deep TeX knowledge. Once again, the relationship between LaTeX and TeX is similar to that between the Standard Template Library and C++.

## Font Sizes and Attributes

LaTeX adds the following generic font sizes and attributes:

 LyX vs. LaTeX Font Traits Trait LaTeX (command mode) LaTeX (argument mode) Default? Comment Family \rmfamily \textrm{text} Default Roman \sffamily \textsf{text} Sans Serif \ttfamily \texttt{text} Teletype (monospaced) Series \mdseries \textmf{text} Default Normal weight \bfseries \textbf{text} Bold Shape \upshape \textup{text} Default Upright \itshape \textit{text} Italics \slshape \textsl{text} Slanted \scshape \textsc{text} Small caps Size \tiny \scriptsize \footnotesize \small \normalsize Default \large \Large \LARGE \huge \Huge
The exact size you get is dependent on the base font size (10, 11 or 12), and the available fonts. Likewise, italics, slant and small caps work only if such fonts are available.

# Changing Commands and Environments with TeX & LaTeX

In LaTeX, commands are entities that happen in one place. A new command is created like this:

 \newcommand{\tweak}[2]{ \center {\Huge #1\par} \vskip 0.3in #2\par \vskip 0.6in} The  new command on the left prints the command's first argument centered in huge print, then skips 0.3 inches and prints the second argument in normal print. Centering is removed at the end.

Within the document text, it's called like this:
\tweak{Why?}{or why not?}
In LaTeX, an environment is an entity that happens over a range of text. A new environment is created like this:

 \newenvironment{breakoutbox}[1]{ % The argument is the box title ~\vskip 0.2in % Skip down 1/2 before story \leftskip 1in\rightskip 1in % Wider margins for narrower text {\noindent.\dotfill{}.\par} % Make dotted line {\center\LARGE{}#1\par} % Print box title LARGE and centered \vskip 0.2in}{ %%%%%% "\endstory" follows \par\noindent{.\dotfill{}.\par} % Make dotted line ~\vskip 0.5in % Skip final 1/2 inch} The new environment on the left prints the title large and centered when a range of text is bracketed with the following: \begin{breakoutbox}{An Age of Heroes}This is the text I want to be in environmentbreakoutbox, blah blah blah\end{breakoutbox} The stuff before }{ happens before the range of text is printed, while the stuff after the }{ is done after the range of text is printed.

Now that you understand the functionality of both commands and environments, let's talk about modifying a command, using this one to start:

 \newcommand{\tweak}[2]{ \center {\Huge #1\par} \vskip 0.3in #2\par \vskip 0.6in} The  new command on the left prints the command's first argument centered in huge print, then skips 0.3 inches and prints the second argument in normal print. Centering is removed at the end.

If, after the command has been defined, you want to change it to print a dotted line on top, you'd do it like this:

To put a dotted line after instead of before, do this:
 \let\oldtweak = \tweak\renewcommand{\tweak}[2]{ \oldtweak{#1}{#2}\par {\noindent .\dotfill.\par}} Here we call \oldtweak before making the dotted line. Note that we need the \par after the call to \oldtweak in order to make it work right. In general, if something doesn't work right, try a \par after every line that should be a paragraph on its own. Experiment.

To put dotted lines top and bottom, do this:
 \let\oldtweak = \tweak\renewcommand{\tweak}[2]{ {\noindent .\dotfill.\par} \oldtweak{#1}{#2}\par {\noindent .\dotfill.\par}} Here we do the dotfill before and after the old command.

Perhaps you'd like to add a third argument, which will go flush right on the second line, with the original content of the second line (arg2) going flush left. No problem:
 \let\oldtweak = \tweak\renewcommand{\tweak}[3]{ \oldtweak{#1}{#3\hfil#2}} Here you increase the number of arguments for command \tweak (#3), and then call \oldtweak, which has only two argument, using a concatination with fill for the old command's arg2.

Now that we've discussed modifying commands, let's discuss modifying environments, which, as you remember, are entities that happen over a range of text. The \newenvironment LaTeX macro has three arguments:
1. The environment name
2. The code to execute before printing the range of text
3. The code to execute after printing the range of text
The following is a restating of an example, in this case a "box" bordered top and bottom by a row of dots, with a title just below the top row of dots.
 \newenvironment{breakoutbox}[1]{ % The argument is the box title ~\vskip 0.2in % Skip down 1/2 before story \leftskip 1in\rightskip 1in % Wider margins for narrower text {\noindent.\dotfill{}.\par} % Make dotted line {\center\LARGE{}#1\par} % Print box title LARGE and centered \vskip 0.2in}{ %%%%%% "\endstory" follows \par\noindent{.\dotfill{}.\par} % Make dotted line ~\vskip 0.5in % Skip final 1/2 inch} The new environment on the left prints the title large and centered when a range of text is bracketed with the following: \begin{breakoutbox}{An Age of Heroes}This is the text I want to be in environmentbreakoutbox, blah blah blah\end{breakoutbox} The stuff before }{ happens before the range of text is printed, while the stuff after the }{ is done after the range of text is printed.

Let's say you want to modify the preceding to make the title slanted text, and put an additional subtitle (an extra argument) in black right below that, and to print a double row of dots at the bottom of the "box". Here's what you do:
 \let\oldbreakoutbox = \breakoutbox % Save old environment\let\endoldbreakoutbox = \endbreakoutbox % Save old executable end\renewenvironment{breakoutbox}[2]{ % Declare another argument \slshape % Slanted text for title \begin{oldbreakoutbox}{#1} % Original opening formatting \upshape % Go back to upright text {\center\large #2 \par} % Center and print subtitle large \vskip 0.2in % Re-skip 0.2 inches}{ \par\noindent{.\dotfill{}.\par}% % Make additional dotted line \end{oldbreakoutbox}% % Original closing formatting} The first two statements save the old environment. Note that the second statement is a piece of fantastic magic that saves the executable part of the original end -- in this case the printing of dots. You must prepend the word "end" to each variable. Yes, I know \endoldbreakoutbox is never used again, but internally the macros call it. We begin by slanting the text, then running the old environment beginning, switching back to upright shape, then adding the subtitle (centered and large), and adding a skip below the subtitle, after which the range of text is printed. The ending features the printing of a line of dots, and then the original end of environment formatting.

 DANGER: POTENTIAL DEBUGGING NIGHTMARE See these two lines: \let\oldbreakoutbox = \breakoutbox\let\endoldbreakoutbox = \endbreakoutbox Both lines are vital, and their variables must be named **EXACTLY**!!!! Yes, I'm shouting. Even though you never see the \endoldbreakoutbox variable mentioned again, it must be assigned the value of \endbreakoutbox, because the \end{oldbreakoutbox} command secretly accesses \endoldbreakoutbox in the bowels of LaTeX. In general, if you're modifying an environment called \myenv, then those two lines should look like this: \let\oldmyenv = \myenv\let\endoldmyenv = \endmyenv\renewenvironment{myenv}[1]{ % Additional actions before printing text \begin{oldmyenv}{#1} % Additional actions before printing text }{ % Additional actions after printing \end{oldmyenv} % Additional actions after printing}

## The Theory Behind the Variable Naming

If you're a C programmer, it seems inconceivable that the name of a variable would matter. In C, variable names are a compile time issue, and therefore the variable name cannot be accessed at runtime. TeX is not like C -- it's more like Ruby. In Ruby (and Perl for that matter), there are ways to deduce or change variable names, not just values, at runtime.

Before modifying an environment, you must store the old one. You can store it to any name you want, as long as you use that name inside both the beginning and ending parts of the environment. Most people simply prepend "old" to the original name, but that's just custom -- you can call it anything.

Now we get to the magic part. The specific actions of the ending part of any environment are stored in a command with the word "end" prepended to the environment name. In other words, if you have an environment called \x, then its specific ending actions are stored in a command called \endx. LaTeX does this automatically, you don't have to do a thing.

Whenever you call \end{x}, LaTeX automatically assembles a variable name by prepending "end", and then runs a command called \endx. That's why, if you stored the original environment to \oldx, you must save \endx to \endoldx so that, in the ending part of the modification, when \end{oldx}
calls \endoldx, \endoldx  contains the specific ending actions of the original macro.

What do I mean by "specific ending actions"? The ending part of a macro does two things:
1. "Turns off" all the formatting that was turned on in the beginning part
2. Takes specific actions such as printing a line, skipping space and the like
#2 is what we're talking about.

## Other Methods of Modifying Commands and Environments

The methods discussed so far are based on TeX, and are not necessarily the best. Often, if you look hard enough, you can find LaTeX hosted variables that can be changed in order to accomplish what you want. Other times, you can find a LaTeX package to enable you do to what you want. Both of these are probably preferable to the TeX methods discussed so far.

Another possibility, though probably the worst, is to go through all the source that ships with LaTeX, find the original environment declaration, copy it to a layout file, and modify it. Doing this means that it could break on the next LaTeX version. However, sometimes the TeX method doesn't work, because you need to add something in the middle of the old begin or end code, not before or after it. In those cases, if variables and packages can't be used, then your only choice might be to copy and modify LaTeX distribution source.

# LyX

A good working simplification is that LyX has two functions:
1. Front end to modify LyX native code
2. Converter to convert LyX native code to LaTeX
The front end is a WYSIWYG interface (go ahead, call me wrong) to LyX native code. It's cool because you can simply type, assign environments with menus, and never (or seldom) need to insert codes. Once all your environments are made, LyX is a lightning fast authoring tool.

LyX native code determines two things:
1. How the document will look on paper
2. How the document will look on the input screen
How it will look on paper is determined by LaTeX code contained in the LyX document's document preamble. The document preamble can be accessed directly from LyX via Document->Settings->LaTeX Preamble. Another way to access it is from within a layout file. Check out this layout file, which is called tarticle.layout:

LyX and LaTeX code are similar enough that they can be quite confusing, but different enough that you better not confuse them. LyX uses a hash mark (#) for a comment, while LaTeX uses a percent sign (%). LaTeX is case sensitive and LyX isn't. LyX and LaTeX use different words for relative font sizes (mainly because LyX can't differentiate with upper case).

## Where to Put Your Layout File

To be recognized by LyX, your layout file or a symlink to it must be in the .lyx/layouts directory under your home directory. Personally, I keep the real file in a much more secure place than ~/.lyx/layouts, and then put a symlink to the real file in  ~/.lyx/layouts.

And remember, every time you change a layout file, in order for LyX to recognize the changes, you need to perform a reconfigure (Tools->Reconfigure on LyX 1.4.2), and then exit LyX and restart it. That's why you should get your LaTeX environments and commands working in LaTeX before adapting them to LyX.

# Get It Working in LaTeX First

A style in LyX is a LyX code wrapper around a working LaTeX environment or command. It's the LaTeX environment or command that determines the look of the output. Therefore, when making a new style or redefining an old one, get the LaTeX environment or command working in LaTeX first.

The LaTeX edit/compile/run cycle is much faster than its LyX counterpart. In LyX, you must run a reconfigure, then exit LyX, then rerun LyX every time you change a layout file. With LaTeX, you simply run the latex command.

Once the environment or command does what you want in LaTeX, put it in a preamble section of a LyX layout, and then in a non-preamble section, write a LyX style wrapper to call it. Hopefully debugging will be minimal.

# LyX is WYSIWYG!

Oh, I can hear the LyX adherants getting ready to shout. "NO, IT'S WYSIWYM." WYSIWYM stands for "What You See Is What You Mean". What does that even mean?

According to Wikipedia (WYSIWYM), it means software favors logical markup over graphical markup. That's a roundabout way of saying it works with styles. What's so special about that? I used WordPerfect 5.1 to write "Troubleshooting: Tools, Tips and Techniques" in 1990, and used styles to represent all that book's formatting.

LyX adherants bend over backward to tell you that LyX is different from WordProcessors because you just type in content, and LyX does the formatting. They claim that WordProcessors make you type in a jumble of formatting features along with the content. This is false. WordProcessors all have styles, and if you choose to use them and use them well, you'll type in content and choose styles, and that's it. Sure, you can use 50 different fonts with different slants and colors using a WordProcessor, but if you wanted to you could do the same thing with LyX. It's called ERT (Evil Red Text). As a matter of fact, up until maybe 2004, LyX didn't even have character styles, so you were forced to format sub paragraph text with things like italic or monofont instead of styles representing their true meaning. WordPerfect 5.0 had character styles back in 1988.

When I wrote Samba Unleashed, Macmillan told me to write it in MS Word, and gave me a template with all their styles, and the only styles they'd allow. Styles for code, styles for each heading level, styles for emphasis, styles for notes and warnings. At that point, I did nothing but write content and choose styles appropriate to that content. I never had to make my own style or declare anything italic or monofont. Logical markup over graphical markup! WYGIWYM!

In other words, LyX is no more content-favoring than WordPerfect, MS Word, or most other WordProcessors used with styles. Oh, that's not completely true -- LyX has automatic hyphenation, with excellent word wrapping, page wrapping, page layout. LyX is a wonderful product, by far my favorite for book writing. But it's about as content-favoring as WordPerfect and MS Word.

Now for my claim that LyX is WYSIWYG. If you want to see something that's not WYSIWYG, find a copy of WordPerfect 5.0 or 5.1. These products did fonts and graphics, but those fonts and graphics didn't show up on the input screen. The input screen showed nothing but monospaced system font. The input screen's lines did not wrap the same as the paper output. Graphics showed up as a little character sized block. If you wanted to see what the document would look like, you had to preview the document in graphical mode, and it looked completely different than it did in the input screen.

Contrast that with LyX. For all well made LyX styles, the input screen makes a reasonable representation of what it will look like on paper. If the font is really big on paper, it will be really big in the input screen. If it's italic on paper, it will be italic on the input screen. If you put in a graphic, it will show up on the input screen, though not necessarily near the same paragraph where it would show up on paper.

LyX isn't nearly as WYSIWYG as MS Word. MS Word's input screen looks almost identical to what you get on paper, whereas LyX's input screen is symbolic of what you'll see on paper. LyX's input screen gives you the feel and context of what you'll see on paper, and that's a good thing -- you can always see where you are at a glance.

In my opinion, instead of bragging that LyX is WYSIWYM and not WYSIWYG, LyX adherants should tout its true capabilities. LyX (via LaTeX) produces highly attractive, professionally typeset documents. LyX does hyphenation right. LyX has an easy to parse, non-patented, plain text native format. From version to version, LyX handles old documents consistently compared to, let's say, MS Word. LyX (via LaTeX) comes with tens of templates (document classes), and you can obtain many more on the Internet. Thousands of packages are available to enhance what LyX can do (via LaTeX), and most are available at ctan.org. LyX's underlying technologies, LaTeX and TeX, are mature, tested, and here to stay. If for some reason LyX ceased to exist, converting LyX documents to LaTeX would be doable, so your data is protected. Just try that with MS Word! LyX has a thriving mailing list with very knowledgeable people.

One more LyX benefit -- it's WYSIWYG, at least to the degree that you can instantly see where you are and not get lost on the input screen. IMHO that's a good thing.

# Summary

LyX is a wonderful book authoring tool, and it's trivially easy to use if you accept all of your document class's defaults. For those of us who want our books to look like books, and not an academic tome, that means we need to modify the default styles, which means we need to use and understand LaTeX.

LaTeX is basically a library of TeX styles. That's an oversimplification, but for understanding it's a good operational definition. To really understand LaTeX, you must understand the underlying technology, TeX. TeX is a programming language optimized to print books.

This document has an overview of TeX complete with examples, followed by a discussion of how LaTeX relates to TeX, once again with examples, and finally how LyX relates to LaTeX. This document isn't intended to be complete or rigorous. If it simply lowers your apprehension of making your own LyX styles, it's done its job.