TeX/LaTeX: an open-source typesetting system for text, mathematical formulas and much more.
In the beginning was Chaos, when several typesetting systems existed, none of them free. Then Donald Knuth renounced a sabbatical to develop a digital typesetting systems of his own. And he named it TeX, after the Greek word technology
or techne
.
TeX and its child LaTeX are user-friendly desktop publishing tools mainly used for typesetting technical documents which nonetheless produce professional-looking print.
TeX and Plain TeX
So TeX is the foundation of [Plain TeX and] LaTeX.
Much like PostScript, TeX offers thorough and free documentation. Here are the main copyleft books on TeX you may easily find and download legally on the internet:
- Paul W. Abrahams, Kathryn A. Hargreaves, and Karl Berry, TeX for the Impatient
- Victor Eijkhout, TeX by Topic
- Donald E. Knuth, The TeXbook
- Norman Walsh, Making TeX Work
Our First TeX Document
A TeX file is mostly made up of ASCII text which follows a number of conventions. For instance, a blank line, alternatively two ENTER strokes, separates two paragraphs. Commands are preceded by a backslash, and TeX recognizes about 900, or which about 300 are called primitive and are not made up of simpler functions. The remaining 600 are plain text definitions. For instance, \TeX is a built-in command sequence. Two paragraph may be separated by a \par command. You type \end at the end of what you intend to get printed, and the processor ignores the rest. This is a minimal TeX file:
Hello \TeX! \end
To use Eplain, simply put the command
\input eplain
at the top of your plain TeX document.
Characters
TeX uses the ASCII character set. To typeset accented characters you need to prepend operators, as explained further down.
Special or reserved characters
These are characters whose effect is to perform an action, unlike in ordinary text. To cancel there effect and show them they are usually preceded with a backslash.
- '\': backslash, escape character; it is escaped by \backslash:
- '%': remainder of line is a comment; it is escaped: \%
- '{': beginning of group; it is escaped: \{
- '}': end of group; it is escaped: \{
- '$': enter inline mathematical mode or leave it if in inline mathematical mode; it is escaped: \$
- '$$': enter display mathematical mode or leave it if in display mathematical mode; it is escaped: \$\$
- '_': subscript; it is escaped: \_
- '^': superscript; it is escaped: \^
- '~': non-breakable space; it is escaped: \~
- '#': parameter; it is escaped: \%
- '&': alignment tab; it is escaped: \&
An example:
Can you solve this? $$y^2 + xy + x^2 = 0$$ \end
Accents
Plain TeX makes it possible to typeset the most commonly used accents:
- \`o ò (grave accent)
- \'o ó (acute accent)
-
\^o ô(circumflex or
hat
) - \"o ö (umlaut or dieresis)
-
\~n ñ (tilde or
squiggle
) -
\=o (macron or
bar
) - \.o (dot accent)
- \u o (breve accent)
-
\v o (
check
) - \H o (long Hungarian umlaut)
- \t oo (tie-after accent)
Within the font, such accents are designed to appear at the right height for the letter 'o'; but you can use them over any letter, and TeX will raise an accent that is supposed to be taller. Notice that spaces are needed in the last four cases, to separate the control sequences from the letters that follow. You could, however, type \H{o} in order to avoid putting a space in the midst of a word.
To place an accent over a dotted character use an undotted variant: \i and \j.
Plain TeX also provides three accents that go underneath:
- \c cç (cedilla accent)
- \d o (dot-under accent)
- \b o (bar-under accent)
Of hyphens and dashes
TeX has four different signs:
- a hyphen: type a hyphen
- an en-dash: for ranges, type two hyphens
- an em-dash: for inserts, type three hyphens
- a minus sign: type a hyphen in math mode
Quoting
Just type two single-quote marks of the appropriate kind, that is grave-grave and then apostrophe-apostrophe:
``I understand.''
You can also use command sequences:
\lq\lqI understand.\rq\rq
Foreign, non-accented characters
- \oe,\OE (French ligature OE)
- \ae,\AEæ, Æ (Latin and Scandinavian ligature AE)
- \aa,\AA (Scandinavian A-with-circle)
- \o,\Oø, Ø (Scandinavian O-with-slash)
- \l,\L (Polish suppressed-L)
-
\ssß (German
es-zet
or sharp S)
Fonts in TeX
TeX provides the following control sequences for changing fonts:
-
\rm switches to the normal
roman
typeface; - \sl switches to a slanted roman typeface;
- \it switches to italic style;
- \tt switches to a monospace, typewriter-like face;
- \bf switches to bold face
Font sizes
TeX assumes font size = 10 points. You can determine a different overall size by setting \magnification before any page is output. The intended factor must be multiplied by 1000. Thus, \magnification=2000 sets a size twice as big. You probably want to stay between 1000 and 1800. You can also type: \magnification=\magstep0 for no magnification (1000), \magnification=\magstep1 for 1200 magnification, and so on geometrically.
Font size can be changed locally by redefining \rm and so on. To change to a bigger font:
\font\rm=cmr10 scaled 1200
Grouping
Local scope is created through pairs of matching curly braces. Changes between them do not affect the enclosing environment. Thus, to itilize a word type:
This is {\it absolutely} secret.
If you want changes to go beyond the local scope, prepend \global.
Boxes and glue
When building a wall, we put bricks in a pattern, and in between them we put mortar to hold the wall together and make it rigid. Similarly, TeX constructs lines (aka horizontal boxes) by putting words (horizontal boxes) one after the other, and in between them it puts a special rubber lenght called glue. Then it procedes to compose pages by putting lines one above the other, and in between them some more glue. Every blob of glue has a natural length and may stretch or shrink a bit on demand according to its stretchability and shrinkability.
Paragraphs themselves are made from lines stacked and glued together. And lines are made up from word-like components (bricks?) kept apart by glue. Paragraphs, lines and word-like components are instances of boxes.
Boxes have width, height and depth. A blob of glue has a natural length called space, as well as stretch or by how much it would stretch, and shrink. Glue is allowed to stretch infinitely far, but it will never shrink more than its stated shrinkability.
So what's the purpose of stating stretch if glue can stretch infinitely far? Well, if an box containing boxes and glue is to stretch further than its natural length, then each blob of glue will stretch in proportion to its shrink.
Boxes whose components are grouped horizontally are called hbox's. A line is an hbox. A word too may be seen as an hbox made up of type. And boxes whose components are grouped vertically or stacked
are called vbox's. A paragraph or a displayed list of items are instances of vbox.
Paragraph indentation
You can set a different glue to \parindent. A value of 0pt effectively prevents indentation. Also, typing \noindent at the very beginning of a paragraph prevents indentation, whereas \indent causes it.
Line breaking
You can prompt TeX to break a word by inserting '\-'. Also, you may define the hyphenation of words with command sequence \hyphenation:
\hyphenation{gal-axy}
TeX assigns a numerical value called badness
to each line that it sets, in order to assess the quality of spacing. Plain TeX normally stipulates that no line's badness should exceed 200.
Interline spacing*
Centered lines
\centerline{This is a centered line!}
Commands for Horizontal and Vertical Modes
This section covers commands that have corresponding or identical forms for both horizontal and vertical modes. These commands provide boxes, spaces, rules, leaders, and alignments.
Producing space*
Fixed-width horizontal space*
Fixed-length vertical space*
Variable-size space*
Manipulating boxes
Constructing hboxes and vboxes
\hbox {<horizontal mode material>}
\hbox to <dimen {<horizontal mode material}
\hbox spread <dimen {<horizontal mode material>}
This command produces an hbox (horizontal box) containing <horizontal mode materiali>. The braces around <horizontal mode material> define a group. TEX doesn't break the <horizontal mode material> into lines, since it's in restricted horizontal mode when it's assembling the box. TEX won't change the size of the box once it's been produced.
The width of the hbox depends on the arguments to
- If you specify only <horizontal mode material>, the hbox will have its natural width.
- If you specify to <dimen>, the width of the hbox will be <dimen
- If you specify
spread <dimen> , the width of the hbox will be its natural width plus <dimen>, i.e., the hbox will be spread out by <dimen>.
Example:
\hbox{ugly suburban sprawl}
\hbox to 2in{ugly \hfil suburban \hfil sprawl}
\hbox spread 1in {ugly \hfil suburban \hfil sprawl}
% Without \hfil in the two preceding lines,
% you’d get ‘underfull hbox’es.
For holding vertical mode material:
\vtop vertical mode material
\vtop to hdimeni { vertical mode material }
\vtop spread hdimeni { vertical mode material }
\vbox { vertical mode material }
\vbox to hdimeni { vertical mode material }
\vbox spread hdimeni { vertical mode material }
These commands produce a vbox (vertical box) containing vertical mode material. The braces around vertical mode material define a group. TEX is in internal vertical mode when it's assembling the box. TEX won't change the size of the box once it's been produced.
The difference between
The height of a vbox depends on the arguments to
- If you specify only vertical mode material, the vbox will have its natural height.
- If you specify to dimen, the height of the vbox will be dimen.
- If you specify spread dimen, the height of the vbox will be its natural height plus dimen, i.e., the height of the vbox will be stretched vertically by dimen.
For
Ordinarily, the width of a constructed vbox is the width of the widest item inside it. (More precisely, it's the distance from the reference point to the rightmost edge of the constructed vbox. Therefore, if you move any of the items right using
- For
\vtop , the height is the height of its first item, if that item is a box or rule. Otherwise the height is zero. The depth is whatever vertical extent remains after the height is subtracted. - For
\vbox , the depth is the depth of its last item, if that item is a box or rule. Otherwise the depth is zero. The height is whatever vertical extent remains after the depth is subtracted. (In fact, there's a further complication. Suppose that after the depth has been determined using the two rules just given, the depth turns out to be greater than \boxmaxdepth. Then the depth is reduced to \boxmaxdepth and the height is adjusted accordingly.)
The
Example:
\hbox{\hsize = 10pc \raggedright\parindent = 1em
\vtop{In this example, we see how to use vboxes to
produce the effect of double columns. Each vbox
contains two paragraphs, typeset according to \TeX’s
usual rules except that it’s ragged right.\par
This isn’t really the best way to get true double
columns because the columns}
\hskip 2pc
\vtop{\noindent
aren’t balanced and we haven’t done anything to choose
the column break automatically or even to fix up the
last line of the first column.\par
However, the technique of putting running text into a
vbox is very useful for placing that text where you
want it on the page.}}
Another example:
\hbox{\hsize = 1in \raggedright\parindent = 0pt
\vtop to .75in{\hrule This box is .75in deep. \vfil\hrule}
\qquad
\vtop{\hrule This box is at its natural depth. \vfil\hrule}
\qquad
\vtop spread .2in{\hrule This box is .2in deeper than
its natural depth.\vfil\hrule}}
Yet another example:
% See how \vbox lines up boxes at their bottoms
% instead of at their tops.
\hbox{\hsize = 1in \raggedright
\vbox to .5in{\hrule This box is .5in deep.\vfil\hrule}
\qquad
\vbox to .75in{\hrule This box is .75in deep.\vfil\hrule}}
\boxmaxdepth [ <dimen> parameter ]
This parameter contains a dimension D. TEX will not construct a box whose depth exceeds D. If you produce a box whose depth d would exceed D, TEX will transfer the excess depth to the height of the box, effectively moving the reference point of the box down by
\underbar [ <argument>]
This command puts argument into an hbox and underlines it without regard to anything that protrudes below the baseline of the box.
Example:
\underbar{Why not learn \TeX?}
Setting and retrieving the contents of boxes*
Shifting boxes
Use:
\moveleft dimen box \moveright dimen box
These commands move box left or right by dimen (which can be neg- ative). You can only apply \moveleft and \moveright to a box that's in a vertical list.
Example:
\vbox{\vbox{Phoebe}\vbox{walked}%
\moveleft 20pt\vbox{a}\moveright 20pt\vbox{crooked}%
\vbox{mile.}}
\lower dimen box \raise dimen box
These commands move box up or down by dimen (which can be negative). You can only apply
Another example:
Are you feeling \lower 6pt \hbox{depressed} about the
\raise 6pt \hbox{bump} on your nose?
Dimensions of box registers
\ht register \dp register \wd register [ dimen parameter ] [ dimen parameter ] [ dimen parameter ]
These parameters refer to the height, depth, and width respectively of box register register. You can use them to find out the dimensions of a box. You can also change the dimensions of a box, but it's a tricky business; if you want to be adventurous you can learn all about it from pages 388–389 of The TEXbook.
Example:
\setbox0 = \vtop{\hbox{a}\hbox{beige}\hbox{bunny}}
The box has width \the\wd0, height \the\ht0, and depth \the\dp0.
produces
The box has width 27.2223pt, height 4.30554pt, and depth 25.94444pt.
Struts, phantoms, and empty boxes
\strut
This command produces a box whose width is zero and whose height (8.5pt) and depth (3.5pt) are those of a more or less typical line of type in cmr10, the default plain TEX font. Its main use is in forcing lines to have the same height when you've disabled TEX's interline glue with
If you're setting type in a font that's bigger or smaller than cmr10, you should redefine
Example:
\noindent % So we're in horizontal mode.
\offinterlineskip % So we get the inherent spacing.
% The periods in this vbox are not vertically equidistant.
\vtop{\hbox{.}\hbox{.(}\hbox{.x}
\hbox{.\vrule height 4pt depth 0pt}}\qquad
% The periods in this vbox are vertically equidistant
% because of the struts.
\vtop{\hbox{.\strut}\hbox{.(\strut}\hbox{.x\strut}
\hbox{.\vrule height 4pt depth 0pt\strut}}
\mathstrut
This command produces a phantom formula whose width is zero and whose height and depth are the same as those of a left parenthesis. \vphantom(
. Its main use is for getting radicals, underbars, and overbars to line up with other radicals, underbars, and overbars in a formula. It is much like
Example:
$$\displaylines{
\overline{a_1a_2} \land \overline{b_1b_2}
\quad{\rm versus}\quad \overline{a_1a_2\mathstrut}
\land \overline{b_1b_2\mathstrut}\cr
\sqrt{\epsilon} + \sqrt{\xi} \quad{\rm versus}\quad
\sqrt{\epsilon\mathstrut} + \sqrt{\xi\mathstrut}\cr}$$
\phantom argument
This command produces an empty box having the same size and placement that argument would have were it typeset. One use of
Example:
$1\phantom{9}2$
produces:
\hphantom argument \vphantom argument
These commands produce phantom boxes that don't print anything:
- \hphantom produces a box with the same width as argument but zero height and depth.
- \vphantom produces a box with the same height and depth as argument but zero width.
Their main purpose is to force a subformula to have a certain minimum horizontal or vertical dimension.
Example:
$$\left[\vphantom{u\over v}t\right] \star
\left[{u\over v}\right]\quad
\{\hphantom{xx}\}$$
\smash argument
This command typesets argument, but forces the height and depth of
its containing box to be zero. You can use
Example:
$${\smash{r_m \brace r_n}\vphantom{r}} \Longrightarrow r$$
\null
This command produces an empty hbox.
Example:
\setbox0 = \null The null box \null has width \the\wd0, height \the\ht0, and depth \the\dp0.
which produces:
The null box has width 0.0pt, height 0.0pt, and depth 0.0pt.
Parameters pertaining to malformed boxes*
Retrieving the last item from a list*
Rules and leaders
\hrule \hrule height dimen width dimen depth dimen \vrule \vrule width dimen height dimen depth dimen
The
If you don't specify the width of a horizontal rule, the rule is extended horizontally to the boundaries of the innermost box or alignment that contains the rule. If you don't specify the height of a horizontal rule, it defaults to 0.4pt; if you don't specify the depth of a horizontal rule, it defaults to 0pt
Rules and leaders
If you don't specify the width of a vertical rule, it defaults to 0.4pt. If you don't specify the height or the depth of a vertical rule, the rule is extended to the boundary of the innermost box or alignment that contains the rule.
TEX treats a horizontal rule as an inherently vertical item and a vertical rule as an inherently horizontal item. Thus a horizontal rule is legal only in a vertical mode, while a vertical rule is legal only in a horizontal mode. If this seems surprising, visualize it—a horizontal rule runs from left to right and separates vertical items in a sequence, while a vertical rule runs up and down and separates horizontal items in a sequence.
Example:
\hrule\smallskip \hrule width 2in \smallskip \hrule width 3in height 2pt \smallskip \hrule width 3in depth 2pt
Example:
% Here you can see how the baseline relates to the
% height and depth of an \hrule.
\leftline{
\vbox{\hrule width .6in height 5pt depth 0pt}
\vbox{\hrule width .6in height 0pt depth 8pt}
\vbox{\hrule width .6in height 5pt depth 8pt}
\vbox{\hbox{ baseline}\kern 3pt \hrule width .6in}
}
Example:
\hbox{( {\vrule} {\vrule width 8pt} )}
\hbox {( {\vrule height 13pt depth 0pt}
{\vrule height 13pt depth 7pt} x)}
% the parentheses define the height and depth of each of the
% two preceding boxes; the ‘x’ sits on the baseline
\leaders box or rule skip command \cleaders box or rule skip command \xleaders box or rule skip command
These commands produce leaders, i.e., they fill a horizontal or vertical space with copies of a pattern. The box or rule specifies a leader, i.e., a single copy of the pattern, while the skip command specifies a window to be filled with a row or a column of the leaders. The pattern is repeated as many times as will fit into the window. If skip command is a horizontal skip, the window contains a row of leaders and TEX must be in a horizontal mode; if skip command is a vertical skip, the window contains a column of leaders and TEX must be in a vertical mode.
The commands differ in how they arrange the repeated pattern in the space and where they put any leftover space:
- For
\leaders , TEX aligns a row of leaders with the left end of the innermost box B that is to contain the result of the\leaders command. It aligns a column of leaders with the top of B. Those leaders that fall entirely within the window are retained. Any leftover space at the top and bottom of the window is left empty. - For
\cleaders , the leaders are centered within the window. - For
\xleaders the pattern is uniformly distributed throughout the window. If the leftover space is l and the leader is repeated n times, TEX puts space of width or heightl/(n + 1) between adjacent leaders and at the two ends (left and right or top and bottom) of the leaders.
Example:
\def\pattern{\hbox to 15pt{\hfil.\hfil}}
\line{Down the Rabbit-Hole {\leaders\pattern\hfil} 1}
\line{The Pool of Tears {\leaders\pattern\hfil} 9}
\line{A Caucus-Race and a Long Tale {\cleaders\pattern\hfil} 19}
\line{Pig and Pepper {\xleaders\pattern\hfil} 27}
Another example:
\def\bulletfill{\vbox to 3ex{\vfil\hbox{$\bullet$}\vfil}}%
\def\mybox{\vbox to 1in}
\def\myrule{\hrule width 4pt}\hsize=2in
\hrule \line{%
\mybox{\myrule depth 8pt \leaders\bulletfill\vfill}
\hfil
\mybox{\myrule depth 15pt \leaders\bulletfill\vfill}
\hfil
\mybox{\myrule depth 18pt \cleaders\bulletfill\vfill}
\hfil
\mybox{\myrule depth 12pt \xleaders\bulletfill\vfill}%
}\hrule
Alignments*
Tabbing alignments*
General alignments*
Programming TeX
Variables
TeX has 256 registers called \count0 to \count255, each capable of containing integers between -2147483647 and +2147483647, inclusive. TeX also has 256 registers called \dimen0 to dimen255, each capable of containing a dimen[sion]. There are another 256 registers called \skip0 to \skip255, each containing glue; and \muskip0 to muskip255, each containing glue in mathematical units. You can assign new values to these registers by typing: \varx=y, and you can add to or subtract from them by typing \advance\varx by y.
Multiplication and division are possible too, but only by integers. For example, \multiply\dimen4 by 3 triples the value of dimen4, and \divide\skip5 by 2 cuts in half all three components of the glue that is currently registered in \skip5.
The first ten \count registers, \count0 through \count9, are reserved for a special purpose[...]
It' usually desirable to have symbolic names for registers. TeX provides a
How do you declare a variable without worrying about whether its underlying match has already been booked? Plain TeX provides
Besides the numerical registers, TeX also has 256 box registers called \box0 to \box255. A box register gets a value when you say \setbox<n>=<box> for example, \setbox3=\hbox{A} sets \box3 to an hbox that contains the single letter A. 2\wd3 is a <dimen> that represents twice the width of \box3; similarly, ^\ht<n>; and \dp<n> can be used to refer to the height and depth of a given box register.
Making lines
A ready line, i.e. a string of type from left to right margin unless it is the last line in a paragraph, is a horizontal box or hbox. The spacing between words is stretched to make the end of the line the same x coordinate as the right margin. These words are themselves hboxes glue-ed together into a long line. If on the other hand this spacing is compressed, an overfull hbox is generated. If it is unacceptable large, an underfull hbox.
The only way to get rid of the overfull boxes is to change the \tolerance, i.e., to allow wider spaces between words. TeX assigns a numerical value called badness to each line that it sets, in order to assess the quality of the spacing. (The exact rules for badness are different for different fonts.) Plain TeX normally stipulates that no line' badness should exceed 200. TeX reports all boxes whose badness exceeds a certain threshold called \hbadness. Plain TeX sets \hbadness at 1000.
TeX treats 10000 as if it were infinite
tolerance, allowing arbitrarily wide space; thus, a tolerance of 10000 will never produce an overfull box, unless something strange occurs like an unhyphenatable word that is wider than the column itself.
A parameter called \hfuzz allows you to ignore boxes that are only slightly overfull. For example, if you set \hfuzz=1pt, a box must stick out more than one point before it is considered erroneous. Plain TeX sets \hfuzz at 0.1pt.
Baselines
Further, a line of printed glyphs has a baseline, that is an imaginary line below which each of its component boxes may have a depth and above which it usually has a height. The baselines of printable lines must be suitably separated.
TeX achieves this by means of three primitives: \baselineskip (glue), \lineskip (glue), and \lineskiplimit (dimension).
TeX inserts interline glue
between consecutive lines in order to make the distance between their baseline equal to \baselineskip.
But if the interline glue calculated by this rule would cause the top edge of the new box to be closer than \lineskiplimit to the bottom edge of the previous box, then \lineskip is used as the interline glue. In other words, the distance between adjacent baselines will be the \baselineskip setting, unless that would bring the boxes too close together (less that \lineskiplimit), in which case the \lineskip glue will be used.
Page dimensions in TeX
Use \hsize for line width and \vsize for total height of printed area. \hoffset is positive rightwards, and \voffset is positive downwards. Some reasonable settings without headers or footers are:
\hoffset=-0.33in \hsize=1.13\hsize \voffset=-0.5in \vsize=1.15\vsize
Mathematics
TeX is designed to handle complex mathematical expressions in such a way that most of them are easy to input. The basic idea is that a complicated formula is composed of less complicated formulas put together in a simple way; the less complicated formulas are, in turn, made up of simple combinations of formulas that are even less complicated; and so on. Stating this another way, if you know how to type simple formulas and how to combine formulas into larger ones, you will be able to handle virtually any formula at all.
Entering math mode
Mathematical formulas are set either inline or to stand alone (display mode). Inline formulas are typed between single dollar signs, while display formulas are typed between double dollar signs. Otherwise formulas are straightforward to compose and easy to read in TeX.
When you type $x$ the x
comes out in italics, but when you type $2$ the 2
comes out in roman type. In general, all characters on your keyboard have a special interpretation in math formulas, according to the normal conventions of mathematics printing: Letters now denote italic letters, while digits and punctuation denote roman digits and punctuation; a hyphen now denotes a minus sign, which is almost the same as an em-dash but not quite. The first $
that you type puts you into math mode and the second takes you out.
TeX does most of its own spacing in math formulas; and it ignores any spaces that you yourself put between dollar signs (inline math). For example, if you type $ x$ and $ 2 $, they will mean the same thing as $x$ and $2$.
Characters in math mode
The 52 letters (A to Z and a to z) denote italic symbols, which a mathematician would call variables
. TeX just calls them ordinary symbols because they make up the bulk of math formulas.
Plain TeX also treats the 18 characters
0 1 2 3 4 5 6 7 8 9 ! ? . || / ` @ "
as ordinary symbols; i.e., it doesn't insert any extra space when these symbols occur next to each other or next to letters. Unlike the letters, these 18 characters remain in roman type when they appear in formulas. There' nothing special for you to remember about them, except that the vertical line '|' has special uses that we shall discuss later.
About primes, as used in calculus notation and so on, although you can use the command
TeX does not treat '/' as a binary operation, even though a slash stands for division (which qualifies as a binary operation on mathematical grounds). The reason is that printers traditionally put extra space around the symbols '+', '-', and '*', but not around '/'.
Plain TeX treats the four characters =, <, >, and : as relations
because they express a relationship between two quantities. For example, ${x<y}$ means that x is less than y. Such relationships have a rather different meaning from binary operations like '+', and the symbols are typeset somewhat differently.
The two characters ',' (comma) and ';' (semicolon) are treated as punctuation marks in formulas; this means that TeX puts a little extra space after them, but not before them.
It isn't customary to put extra space after a '.' (period) in math formulas, so TeX treats a period as an ordinary symbol. If you want the ':' character to be treated as a punctuation mark instead of as a relation, just call it \colon.
If you want to use a comma as an ordinary symbol (e.g., when it appears in a large number), just put it in braces; TeX treats anything in braces as an ordinary symbol.
The characters '(' and '[' openings
, while ')' and ']' are called closings
; these act pretty much like ordinary symbols, but they help TeX to decide when a binary operation is not really being used in a binary way.
Greek letters for variables*
Accents in math mode
Mathematical accents are somewhat different, because spacing is not the same; TeX uses special conventions for accents in formulas, so that the two sorts of accents will not be confused with each other. The following math accents are provided by plain TeX and are exemplified atop letter 'a':
$\hat a$ $\check a$ $\tilde a$ $\acute a$ $\grave a$ $\dot a$ $\ddot a$ $\breve a$ $\bar a$ $\vec a$
The first nine of these are called \^, \v, \~, \', \`, \., \" , \u, and \=, respectively, when they appear in text; \vec is an accent that appears only in formulas. \TeX\ will complain if you try to use \^ or \v, etc., in formulas, or if you try to use \hat or \check, etc., in ordinary text.
When the letters i and j are accented in math formulas, dotless symbols \imath and \jmath should be used as provided in plain TeX.
Subscripts and superscripts
Subscripts and superscripts are preceded by a hat or an underscore. These apply only to the next single character. If you want several to be subscripted or superscripted, just enclose them in braces, as in $e^{\omega i}$, which prints eωi.
A subscript or superscript preceding a glyph can be printed by preceding the expression with an empty group, as in ${}_3A$, which prints 3A.
Operators
TeX puts some extra space before and after some operators. Also, operators consisting of letters are set in roman.
I have already discussed the arithmetic operators ('+', '-', '*', and '/'). Some other common glyph operators are \times and cdot (a vertically centered dot to denote multiplication, too), \cup and \cap for set union and intersection, \vee (or \lor), \wedge (or \land), and \xyz for logical OR, AND, and NOT, \pm and \mp for plus-minus and minus-plus, to and \mapsto to map a set (element) to another set (element), \le and \xyz for less or equal and greater or equal; \ne for not equal, \equiv and \not\equiv for equivalent and not equivalent, \subset and \subseteq, for inclusion and non-strict inclusion...
Roots
A square root is printed by command
Under and over
Fractions, binomials, and limits
Fractions are made by typing \over between numerator and denominator. Binomials are made by typing \choose between its terms. Subscripts and superscripts of summations are printed over and under the summation sign in display mode. Try these:
$$n+1\over n+2$$
$${x+y^2\over k}+1$$
$$n+1\choose3$$
$$\sum_{n=1}^3 Z_n^2$$
Notice the second expression: sometimes grouping is necessary.
If the numerator of a fraction is a fraction, it should be set as with a slash: $${a \over b} \over 2$$
An expression over another expression
TeX has another operation \atop, which is like \over except that it leaves out the fraction line, as in $$x \atop y + 2$$. (
Summations and Integrals
These are set through \sum and \int, with limits specified as subscripts and superscripts. In display mode they are printed larger, with limits over and under, whereas in text mode they are printed smaller with limits to the right, so as not to make too tall a box.
If you want the limits to be printed differently, you can type \limits or \nolimits right after the the large operator. For instance:
$$\int\limits_0^{\pi\over2}$$
$$\sum\nolimits_{n=1}^m$$
Lines under and over
TeX and Plain TeX provide four operators that span a group horizontally: \underline, \overline, \widehat and \widetilde. These are so straightforward to use that I will only provide two examples: $\underline 3$ and $\overline{\alpha^2}$.
Delimiters
Delimiters are important to mathematicians, because they provide good visual clues to the underlying structure of complex expressions; they delimit the boundaries of individual subformulas. Here is a list of the 22 basic delimiters provided by plain TeX:
In order to get a slightly larger version of any of these symbols, just precede them by \bigl| (for opening delimiters) or \bigr| (for closing ones). This makes it easier to read formulas that contain delimiters inside delimiters. Then you can also type \Bigl and \Bigr to get larger symbols suitable for displays. These are 50% taller than their \big counterparts. Displayed formulas most often use delimiters that are even taller (twice the size of
TeX has a built-in mechanism that figures out how tall a pair of delimiters needs to be, in order to enclose a given subformula; so you can use this method, instead of deciding whether a delimiter should be \big or \bigg or whatever. All you do is type
\left<delim1> <subformula> \right<delim2>
and TeX will typeset the subformula, putting the specified delimiters at the left and the right. The size of the delimiters will be just big enough to cover the subformula. But whenever you use \left and \right they must pair up with each other.
If you want to omit a delimiter, just type a dot, as in \left. or \right. and you get a null delimiter. Still, a null delimiter isn't completely void; it is an empty box whose width is a TeX parameter called \nulldelimiterspace. (We will see later that null delimiters are inserted next to fractions.) Plain TeX sets \nulldelimiterspace=1.2pt.
Axes
If you look closely at some examples of math typesetting, you will notice that large parentheses and brackets are symmetric with respect to an invisible horizontal line that runs a little bit above the baseline; when a delimiter gets larger, its height and depth both grow by the same amount. This horizontal line is called the axis of the formula. The bar line in every fraction is centered on the axis, regardless of the size of the numerator or denominator.
Sometimes it is necessary to create a special box that should be centered vertically with respect to the axis. TeX provides a simple way to do this: just type
\vcenter{<vertical mode material>}
and the vertical mode material will be packed into a box just as if \vcenter had been \vbox. Then the box will be raised or lowered until its top edge is as far above the axis as the bottom edge is below.
axisis meaningful for TeX only in math formulas, not in ordinary text; therefore TeX allows you to use \vcenter only in math mode. If you really need to center something vertically in horizontal mode, the solution is to say $\vcenter{...}$.
(Incidentally, the constructions \vcenter to<dimen> and \vcenter spread<dimen> are legal too, in math mode; vertical glue is always set by the rules for
Controlling height: mathstrut, smash, and phantom props
A \mathstrut is an invisible box whose width is zero; its height and depth are the height and depth of a parenthesis '('. Therefore subformulas that contain \mathstrut will always have the same height and depth. What for? Often you want to have uniformity between different members of a complex formula.
Not two but eight mathematical modes
Letters and other symbols sometimes get smaller when they appear in fractionsor in exponents. It's about time that we studied TeX' method for choosing the sizes of things. TeX actually has eight different styles in which it can treat formulas, namely
- display style (for formulas displayed on lines by themselves)
- text style (for formulas embedded in the text)
- script style (for formulas used as superscripts or subscripts)
- scriptscript style (for second-order superscripts or subscripts)
and four other cramped
styles that are almost the same except that exponents aren't raised quite so much. For brevity we shall refer to the eight styles as D, D', T, T', S, S', SS, and SS', where D is display style, D', is cramped display style, T is text style, and so on. TeX also uses three different sizes of type for mathematics. They are called text size, script size, and scriptscript size.
The normal way to typeset a formula with TeX is to enclose it in dollar signs $...$ to render it in text style, or in double dollar signs $$...$$ to render it in display style. The subformulas of a formula might, of course, be in different styles. Once you know the style, you can determine the size of type that TeX will use: text and display style are rendered in text size, script style is rendered in script size and scriptscript style is rendered y scriptscript size, of course.
Now, while in text or display style sub- and superscripts are render in script size. In script and in scriptscript style, sub- and superscripts are render in scriptscript size.
If you don't like the style that TeX selects by its automatic style rules, you can specify the style you want by typing \displaystyle or \textstyle or \scriptstyle or \scriptscriptstyle. The style that you select will apply until the end of the formula or subformula, or until you select another style.
\underline does not change the style, whereas the operations \sqrt and \overline change uncramped styles to their cramped counterparts.
Tables in TeX and LaTeX
http://www.volkerschatz.com/tex/halign.html
Low-level typesetting of tables (TeX) is a matter of aligning boxes horizontally. The TeX macro for horizontal alignment (\halign) is harder to use than the LaTeX tabular environment, but is more powerful. It can also save you a lot of work because things that have to be put into every cell of a given table column (eg font settings or mathematical mode) need to be specified only once. The actual table cells contain only what is different.
Tables in (Plain) TeX
The TeX command for horizontal alignment (\halign) must be followed by a group of commands enclosed by braces. This block contains all rows of the table with the cells separated by the character & and the rows separated by \cr. The rows containing the text actually to be printed are preceded by a special row called the preamble or template line. It is a template into which the content of the table cells are put before being typeset. '#' characters serve as placeholders for the cell entries. (Inside macro definitions, '##' is used to avoid confusion with the macro arguments denoted by #1, #2 etc.) One '#' must occur between every two '&'s.
The length n of the template line need not be equal to the actual number of columns in the alignment: the template is used only for as many items as are specified on a line.
Entries in an alignment are set to take the width of the largest element in their column. Glue for separating columns can be specified by assigning it to \tabskip. TeX inserts this glue in between each pair of columns, and before the first and after the last column.
Here's a simple example:
\tabskip=2em
\halign to \hsize{ \hfil ECO# & \hfil # kW\hfil & \hfil # \hfil euros \cr
A & 20 & 999 \cr
A00 & 22 & 2999 \cr
A20 & 27 & 3299 \cr}
which would produce the table:
| ECOA | 20 kW | 999 euros |
| ECOA00 | 22 kW | 2999 euros |
| ECOA20 | 27 kW | 3299 euros |
To typeset the heading in the preceding example you would like to omit much of the specifications in the preample. Use \omit before each cell of a line to be typeset bypassing the preamble. Remember to repeat all your alignment done through \hfill and such. Thus:
\tabskip=2em
\halign to \hsize{ \hfil ECO# & \hfil # kW\hfil & \hfil # \hfil euros \cr
\omit\bf \hfil engine \hfil & \omit\bf\hfil power\hfil & \omit\bf\hfil price \hfil \cr
% \noalign{\hrule}
A & 20 & 999 \cr
A00 & 22 & 2999 \cr
A20 & 27 & 3299 \cr}
which now looks nicer, something like:
| engine | power | price |
|---|---|---|
| ECOA | 20 kW | 999 euros |
| ECOA00 | 22 kW | 2999 euros |
| ECOA20 | 27 kW | 3299 euros |
TeX first calculates widths (for \halign) or heights (for \valign) of all entries; then it typesets the whole alignment using in each column (row) the maximum width (height) of entries in that column (row).
As an example, in the following table there is no tabskip glue before the first and after the last column; in between all columns there is stretchable tabskip.
\tabskip=0pt \halign to \hsize{
\vrule#\tabskip=0pt plus 1fil\strut&
\hfil#\hfil&
\vrule#&
\hfil#\hfil&
\vrule#&
\hfil#\hfil&
\tabskip=0pt\vrule#\cr
\noalign{\hrule}
&\multispan5\hfil Just a table\hfil&\cr
\noalign{\hrule}
&one&&two&&three&\cr &a&&b&&c&\cr
\noalign{\hrule}
}
Lines around table cells
First you want to cancel interline skip within a block delimited by curly braces (type \offinterlineskip). Then you use empty (=no content) columns to typeset vertical lines.
{
\offinterlineskip
\tabskip=0pt
\halign{
\vrule height2.75ex depth1.25ex width 0.6pt #\tabskip=1em &
\hfil 0.#\hfil &\vrule # & \qquad$0.#\,\pi$\hfil &\vrule # &
\hfil 0.#\hfil &#\vrule width 0.6pt \tabskip=0pt\cr
\noalign{\hrule height 0.6pt}
& \omit$\alpha_s$ &&\omit star angle && \omit diquark size [fm] & \cr
\noalign{\hrule}
& 3 && 22 && 34 &\cr
& 4 && 14 && 22 &\cr
& 5 && 095 && 15 &\cr
\noalign{\hrule height 0.6pt}
}
}
...
Let's now go through the TeX code line by line. The first command switches off the spacing between lines. Normally TeX automatically inserts line spacing before starting a new line, even in tables. When typesetting framed tables, one has to disable this because otherwise the vertical lines of the frame don't join up. To make this change apply only to the table, everything is included in braces.
The second command sets the spacing between table cells to zero. This is necessary for the first column because the vertical lines have columns of their own. Without the \tabskip=0pt, a space would be put before the vertical lines, and as a result the horizontal ones would stick out to the left of the table. (One could of course put vertical lines within the table cells containing the text, but usually it is done this way.)
Next comes the \halign command. The first item in the first cell template is a vertical ruler of the width 0.6 point. Its height (above the base line) and depth (under the base line) is given explicitly to force the table cells to be higher than they would normally be. One can also use this trick in tables without frames by setting the ruler width to zero point. Each template also has to contain a '#', even when the column is meant to remain empty as here. The last command in this template sets the column spacing back to something greater than zero.
The next column contains the first text entry. It is a numerical entry containing numbers which are smaller than 1. They are centred (since there are \hfil commands to both sides), and the zero and the decimal point are already written into the template to save me some work in the entries. Then comes another vertical rule. Its height does not have to be specified again; it will be as high as the table row. The width is the default width of 0.4 point, somewhat narrower than the outer frame. The next column contains multiples of pi. Therefore the template already contains the symbol \pi besides the zero and decimal point, in math mode. It is aligned left (\hfil on the right) but has a large space to the left (\qquad) so that the decimal points are approximately in the middle of the column. Next comes another vertical line, then the third column (centred again), and the final thick vertical line. In the template for the last column \tabskip is again set to zero to avoid horizontal lines overlapping to the right. The first \cr marks the end of the preamble.
The next command, \noalign, is often useful in tables. It allows one to insert commands between table lined which would normally only be permitted in vertical mode, ie between paragraphs. One of these commands is a horizontal line (ruler). It extends over the whole width of the table and has the height 0.6 point. One can use \noalign for other things, too, for example inserting spaces between table lines or allowing or disabling page breaks between them (see here for an example).
Now comes the first table row. It starts with an alignment tab character (&) since the first column contains just the vertical line, no text. Likewise, later there are double '&'s between text entries, and the line is concluded with a '&'. All text entries \omit their templates since they don't contain zeros. Here no alignment is forced. In this case this results in left alignment but the result is very sensitive to spaces in the table entries. It is usually better to insert a few \hfils. After the \cr indicating the end of the table row there is another horizontal line (of default width), followed by three rows with numerical entries which are not separated by horizontal lines. After the last row there is a thick line which completes the frame. The following two braces close the \halign command and the enclosing group.
Cells spanning several columns
\span disables the alignment of the following alignment character (&) and thereby makes it possible to extend table cells over several columns. The templates of all columns are used unless one writes \omit\span\omit\span\omit...; otherwise just the restriction that the ampersand in this row line up with the others is removed.
An example for this is the following table which seems to contain only one column. The alignment mechanism is used to make the decimal points line up by putting the digits before and after the point into different columns. The decimal points are aligned by putting an ampersand after each of them. In order not to introduce a space after the point, \tabskip is set to zero before the corresponding alignment character (&). The title line is also interesting. The template of the first (text) column is omitted. The source code is:
{
\offinterlineskip
\tabskip=0pt
\halign{\vrule height2.75ex depth1.25ex #\tabskip=1em &
\qquad\hfil#\tabskip=0pt &# \hfil\tabskip=1em &#\vrule\tabskip=0pt \cr
\noalign{\hrule}
& \omit\hfil\bf value\span &\cr
\noalign{\hrule}
& 109.&589 &\cr
& 104.&411 &\cr
& 88.&321 &\cr
& 74.&7105 &\cr
& 88.&5942 &\cr
\noalign{\hrule}
}
}
Alignment primitives
- \halign
-
Horizontal alignment.
- \valign
-
Vertical alignment.
- \omit
-
Omit the template for one alignment entry.
- \span
-
Join two adjacent alignment entries.
- \multispan
-
Macro to join a number of adjacent alignment entries.
- \tabskip
-
Amount of glue in between columns (rows) of an \halign (\valign).
- \noalign
-
Specify vertical (horizontal) material to be placed in between rows (columns) of an \halign (\valign).
- \cr
-
Terminate an alignment line.
- \crcr
-
Terminate an alignment line if it has not already been terminated by \cr.
- \everycr
-
Token list inserted after every \cr or non-redundant \crcr.
- \centering
-
Glue register in plain TEX for centring \eqalign and \eqalignno. Value: 0pt plus 1000pt minus 1000pt
- \hideskip
-
Glue register in plain TEX to make alignment entries invisible. Value: -1000pt plus 1fill
- \hidewidth
-
Macro to make preceding or following entry invisible.
Accessing the PS and PDF engines through \special
Non-TeX commands, possible further downstream (e.g. PostScript and PDF), can be scheduled within a TeX file, from including an image to inserting a hyperlink, by means of the
The argument of
Knuth, in the TeXbook, suggests that the argument of
dvipdfm and dvips. Still, some
TEX is a programming language. A DVI file is a page description consisting of very simple program instructions that have no branching or decision instructions. Similarly PostScript is a complete programming language, while PDF is a page description language consisting of simple program instructions without any branching or decision capabilities. TEX is like PostScript (without the graphics) while DVI is like PDF (without the graphics or the hyper-links). Creating PDF from DVI using Distiller requires converting a page description to a program, and converting that program back to a page description. To continue this analogy, Pdfmarks are PostScript escapes
and are meant for the Distiller. TEX \special primitives are TEX escapes
and are meant for the DVI driver.
according to the creators of dvipdfm, it seems natural to go directly from DVI to PDF, where TEX replaces PostScript, the DVI driver replaces Distiller, and TEX \special primitives replace the pdfmarks. On the other hand, it makes sense to enable access to PostScript from TeX, which is the main reason for PostScript programmers to choose dvips, which is discussed first.
dvips \special's
Papersize
The format of the
You specify landscape orientation through \special{landscape}.
Including Encapsulated PostScript files
Scaling and including PostScript graphics is easy if the PostScript file is correctly formed, i.e. it includes an accurate bounding box comment, on the pattern %%BoundingBox: llx lly urx ury, such as:
%%BoundingBox: 0 0 150 100
Further, the first should start with the two magic characters %!
.
Next, if you are using plain TEX, you need epsf.tex, therefore bring it in through a line \input epsf.
Last, at the point you want to include a file, enter a line such as \epsffile{<filename>.eps}. If you are in the middle of a paragraph, the EPS figure will be incorporated as a box in the current line, which will cause the common baseline to drop if the height of the figure is greater than the
Here is a simple EPS file to test inside a tex file:
%!PS-Adobe-2.0 EPSF-2.0 %%BoundingBox: 0 0 100 19 /Times-Roman 22 selectfont 0 0 moveto (Hello EPS!) show
(If your file does not have a bounding box comment, you can supply the numbers as determined in the previous section, in the same order they would have been in a normal bounding box comment: \epsffile[0 0 100 19]{hello.eps}.)
The \epsffile macro typesets the figure as a TEX
EPSF scaling
Usually, you will want to scale an EPSF figure to some size appropriate for your document, since its natural size is determined by the creator of the EPS file. The best way to do this is to assign the desired size to the TEX
EPSF clipping
By default, clipping is disabled for included EPSF images. This is because clipping to the bounding box dimensions often cuts off a small portion of the figure, due to slightly inaccurate bounding box arguments. The problem might be subtle; lines around the boundary of the image might be half their intended width, or the tops or bottoms of some text annotations might be sliced off. If you want to turn clipping on, just use the command
An example including EPS with graphics and text printed in a scaled inherited font:
\input epsf
%Hello \TeX !
% \epsfbox{square.eps} % include EPS file in horizontal mode, i.e. after the text, not below.
\hbox
{
\epsfxsize=25pt \epsfbox{square.eps} % include EPS file in vertical mode
\vbox {
\noindent The four numbers in square brackets tell \TeX to use only part of the size of the graphic. In this example, \TeX would pretend that only the rectangle from (10,30) to (150,80) is actually used. The dimensions are points, so the graphic would have an effective size (for TeX's purposes) of (150-10) or 140 points wide by (80-30) or 50 points tall.
}
}
\noindent The graphic is not actually cropped to the given size, it is only shifted on the page so that the lower left corner of the bounding box coincides with the lower left corner of the area \TeX reserves for it. In the example above, location (10,30) in the figure would be located at the lower left corner of the box in which TeX places the figure, but any part of the image outside the rectangle from (10,30) to (150,80) would still appear on the page.
\hbox {
Bye \TeX !
\special{ps: 200 200 moveto 500 dup rlineto 0.33 0.33 0 setrgbcolor 10 setlinewidth stroke}
% What about...?
\special{ps: gsave
currentfont 2 scalefont setfont
900 dup 2 mul moveto
0.2 setgray
(Test: currentfont 2 scalefont setfont) show grestore}
%\epsfbox{square.eps} % include EPS file BELOW the text, not below.
\vtop { \epsfxsize=10pt \epsfbox{square.eps} \epsfxsize=12pt \epsfbox{square.eps} \epsfxsize=33pt \epsfbox{square.eps}}
}
\bye
Including PostScript files
The basic special for file inclusion is as follows:
\special{psfile=<filename>.ps [<key>=<value>] ... }
This brings in the PostScript file <filename>.ps such that the current point will be the origin of the PostScript coordinate system. The optional key=value assignments allow you to specify transformations on the PostScript. The possible keys are:
The offsets and sizes are given in PostScript units (big points).
Including headers from TEX
In order to get a particular graphic file to work, a certain font or header file might need to be run first. The dvips program provides support for this with the header
Literal PostScript
For simple graphics, or just for experimentation, literal PostScript code can be included. Simply use a
Generally, Dvips encloses specials in a PostScript
\special{ps:<text>}
\special{ps::<text>}
\special{ps::[begin]<text>}
\special{ps::[end]<text>}
\special{ps::[nobreak]<text>}
You can download literal PostScript header code in your TEX document, for use with (for example) literal graphics code that you include later. The text of a
\special{ps:
[ /Rect [602 1083 1087 1320]
/Border [0 0 2]
/Color [1 0 0]
/Dest link_child_page
/Subtype /Link
/ANN pdfmark
}
PostScript hooks
Besides including literal PostScript at a particular place in your document (as described in the previous section), you can also arrange to execute arbitrary PostScript code at particular times while the PostScript is printing. If any of the PostScript names
When these macros are executed, the default PostScript coordinate system and origin is in effect. Such macros can be defined in headers added by the -h option or the header= special, and might be useful for writing, for instance, DRAFT
across the entire page, or, with the aid of a shell script, dating the document. These macros are executed outside of the
The single argument to
As an example of what can be done, the following special will write a light grey DRAFT
across each page in the document:
\special{!userdict begin
/bop-hook{
gsave
200 30 translate
65 rotate
/Times-Roman findfont 216 scalefont setfont
0 0 moveto
0.7 setgray (DRAFT) show
grestore
} def
end}
(Using
HyperTeXt
Dvips has support for producing hypertext PostScript documents. If you specify the -z option, the
The resulting PostScript can then be processed by a distiller program to make a PDF file. (It can still be handled by ordinary PostScript interpreters as well.) Various versions of both PC and Unix distillers are supported; Ghostscript includes limited distiller support.
If you intend to go all the way to PDF, you may want to use the standard 35 PostScript fonts exclusively, since other fonts are embedded as bitmaps by default. The Adobe PDF readers are extremely slow when dealing with bitmap fonts and the results look terrible on the screen. Printouts will probably look fine, but may not take full advantage of a high- resolution printer. Alternatively, you can have your fonts embedded as Type 1 scalable outlines. The resulting PostScript files may be larger, but can be effectively rasterized at any resolution. They can also be converted to PDF files that can be used effectively at any screen or printer resolution.
To get the TeX fonts embedded in the PostScript file as Type 1 fonts, add -Ppdf to the dvips command line switches.
You can convert a PostScript file to PDF using
Arthur Smith (apsmith@aps.org), Tanmoy Bhattacharya, and Paul Ginsparg originally proposed and implemented the following specials:
html:<a href="xurl"> html:<a name="name"> html:</a> html:<img src="xurl"> html:<base href="xurl">
- href
-
Creates links in your TEX document. For example: \special{html:<a href="http://www.tug.org/">}\TeX\ Users Group\special{html:</a>}. The user will be able to click on the text
TEX Users Group while runningXdviand get to the TUG home page. (By the way, this is for illustration. In practice, you most probably want to use macros to insert the \special commands.) - name
-
Defines URL targets in your TEX documents, so links can be resolved. For example: \special{html:<a name="paradise">}Paradise\special{html:</a>} is exactly where you are right now.
This will resolve an href="#paradise". You'll also have to change the catcode of '#', etc. It's usually easiest to use existing macro packages which take care of all the details.
- img
-
Links to an arbitrary external file. Interactively, a viewer is spawned to read the file according to the file extension and your mailcap file (see the Xdvi documentation).
- base
-
Defines a base URL that is prepended to all the name targets. Typically unnecessary, as the name of the DVI file being read is used by default.
Color
Besides the source code support itself, there are additional TEX macro files: colordvi.tex and blackdvi.tex (and corresponding .sty versions for use with LaTeX).
All the color macro commands are defined in colordvi.tex (or colordvi.sty). To access these macros simply add to the top of your plain TEX file the command: \input colordvi.
These macros provide two basic kinds of color macros: ones for local color changes (a few words, a single symbol) and one for global color changes (the whole document). All the color names use a mixed case scheme to avoid conflicts with other macros. There are 68 predefined colors, with names taken primarily from the Crayola crayon box of 64 colors, and one pair of macros for the user to set his own color pattern. You can browse the file colordvi.tex for a list of the predefined colors. The comments in this file also show a rough correspondence between the crayon names and Pantones.
A local color command has the form \<ColorName>{<colored text>} where ColorName is the name of a predefined color, e.g.,
The global color command has the form \textColorName. These macros take no arguments and changes the default color from that point on to ColorName.
The color commands will even work in math mode and across math mode boundaries. This means that if you have a color before going into math mode, the mathematics will be set in that color as well.
User-defined colors
There are two ways for the user to specify colors not already defined. For local changes, there is the command this color is pretty
to appear in a color which is 50% cyan, 85% magenta, 40% yellow and 20% black. You would use the command: \Color{.5 .85 .4 .2}{this color is pretty}. For global color changes, there is a command
Color macros are defined via
\headline{\Black{My Header}}
\footline{\Black{\hss\tenrm\folio\hss}}
This warning also applies to figures and other insertions, so be careful!
Color support details
To support color, Dvips recognizes a certain set of specials. These specials start with the keyword
What is a color specification? One of three things. First, it might be a PostScript procedure as defined in a PostScript file that sets the current color to some value. To set it to
The second possibility is the name of a color model (initially, one of
The third and final type of color specification is a double quote followed by any sequence of PostScript. The double quote is stripped from the output. For instance, the color specification "AggiePattern setpattern will set the
I shall describe the
The
Dvips correctly handles these color specials across pages, even when the pages are repeated or reversed.
pdfTeX
pdfTEX (formerly known as TEX2PDF) is an extension to TEX which allows the user to generate (either DVI or) PDF as the primary output format without requiring the use of DVI as an intermediate language.
Although TEX has traditionally generated DVI as its primary output format, TEX's creator and author (Prof. Donald E. Knuth) has himself said or written on more than one occasion that he had long envisaged that a variant of TEX might elect to use an alternative output format, and although Knuth had PostScript in mind, Adobe's PDF turns out to be an even better candidate for such purposes. It is a very compact language, already well-established as a de facto standard portable document format both on and off the web, and its deliberate omission of the procedural elements of PostScript ensures that it is efficient enough to be used for direct screen display as well as for less time-critical applications such as printing.
Why not generate PDF from PS from DVI?
Because by the time TEX has shipped out a completed page of DVI, much potentially useful information has already been lost. Only by modifying TEX to output PDF directly, and by integrating the generation of PDF with TEX's "digestive tract", can such information be retained and captured within the PDF file. This allows, for example, an extremely simple and elegant implementation of hyperlinks, the beginning and end of which can span multiple lines or even pages. To accomplish this using DVI as an interlanguage requires heavy use of \specials and even then some functionality is lost unless TEX is modified. PDF also allows the re-use of (potentially large) data structures, a concept completely unknown within DVI.
Because the PDF which is generated by pdfTEX is usually more compact than that generated using DVI as an interlanguage, since only TEX has detailed knowledge of the data structures (boxes, etc.) of which the PDF is a representation.
(And finally, because only by integrating PDF generation within TEX itself can we gain access to the font-mutating possibilities which may in the future allow the implementation of dynamic font mutation for microjustification, etc.)
Basics
When PDF output is selected, TEX's \special command is ignored (that is, it does not contribute anything to the page(s) being shipped out, although its other, more subtle, effects still take place). A new primitive, \pdfliteral, allows raw PDF to be inserted into the PDF output stream at well-defined points.
pdfTEX allows the direct inclusion of bitmap graphics (as opposed to bitmap fonts). Graphics for inclusion must be expressed in PNG (Portable Network Graphics) format. Although facilities for the inclusion of EPS images are thought highly desirable by many, the overheads of PostScript interpretation make this an unreasonably demanding task. More likely is the development of a facility for the incorporation of (E)PDF images, but this is not currently implemented. Hans Hagen and Tanmoy Bhattacharya have developed a suite of macros which allow the inclusion of both METAPOST output and of a subset of PDF files (those that do not contain fonts, bitmaps and/or similar resources).
Hyperlinks
One of the most powerful features of the PDF format is the ability to establish both intra- and inter-document hyperlinks. This facility is accessible to pdfTEX users who have only to tag their documents to indicate the start, end and target of the link. All of the underlying housekeeping is performed by pdfTEX itself, including taking care of such difficulties as intervening line and/or page breaks. The only requirement is that the hyperlink shall start and end at the same level of box nesting. Any and all intervening boxes of the same depth are treated as a part of the hyperlink, but boxes nested to a greater depth are not.
\special commands available in dvipdfm
The program dvipdfm (in package texlive) recognizes several commonly used
The following features are supported:
- Support for outline entries (also called bookmarks), named destinations, and annotations (including hyperlinks, forms and widgets). Nearly every Acrobat Distiller pdfmark is approximated.
- Support for
standard
DVI specials such as HyperTEX (HTML), TPIC, color specials, PSfile, and other PostScript specials. - Native support for inclusion of MetaPost output and inclusion of arbitrary PostScript files with help from an external program.
- Support for thumbnails with a little help from GhostScript to generate the thumbnails.
- Support for arbitrary, nested linear transformations of typeset material. Any material on the page, including TEX text, may be scaled and rotated.
- Ability to include the first page of a PDF file as an encapsulated object along with its embedded resources such as fonts. Included PDF images may be cropped by supplying a bounding box. Note: Currently, this doesn't work if the contents stream has multiple segments.
- Ability to include JPEG and PNG bitmapped images as encapsulated objects.
- An internal color stack. A color stack allows you to change the current color, pushing the current color onto a stack. At any time, the original color can be popped from the stack. This is useful, for example, in headlines, that may have a different color from the current text. The headline macro can restore the current color without knowing what it is.
Each TEX pdf:
are immediately followed by a dvipdfm command.
Interaction with the dvipdfm driver consists of short commands with a few arguments delimited by white space. Typically the arguments are PDF objects. Two exceptions are dimension specifications and transformations.
TeX Packages
For Ubuntu linux, you may install texlive-plain-extra, which comprises some add-on packages and macros that work with plain TeX
. The documentation is to be found in /usr/share/doc/texlive-doc/plain/, not in /usr/share/doc/texlive-plain-extra/.
This package includes the following CTAN packages:
- epsf-dvipdfmx
- Plain TeX file for using epsf.tex with (x)dvipdfmx.
- figflow
- Flow text around a figure.
- fixpdfmag
- Fix magnification in PDFTeX.
- font-change
- Macros to change text and mathematics fonts in plain TeX.
- fontch
- Changing fonts, sizes and encodings in Plain TeX.
- getoptk
- Define macros with sophisticated options.
- gfnotation
- Typeset Gottlob Frege's notation in plain TeX
- graphics-pln
- LaTeX-style graphics for Plain TeX users.
- hyplain
- Basic support for multiple languages in Plain TeX.
- js-misc
- Miscellaneous macros from Joachim Schrod.
- mkpattern
- A utility for making hyphenation patterns.
- newsletr
- Macros for making newsletters with Plain TeX.
- pitex
- Documentation macros.
- placeins-plain
- Insertions that keep their place.
- plipsum
- Lorem ipsum for Plain TeX developers.
- plnfss
- Font selection for Plain TeX.
- plstmary
- St. Mary's Road font support for plain TeX.
- present
- Presentations with Plain TeX.
- resumemac
- Plain TeX macros for resumes.
- timetable
- Generate timetables.
- treetex
- Draw trees.
- varisize
- Change font size in Plain TeX.
- xii
- Christmas silliness.
TeX Tricks, Techniques and Recipes
Including a file
\include file
or
\include file.tex
From XML to TeX
There is a powerful transformation language for XML: XSLT. Assuming you can transform from XML to any other mark-up format, we are better off writing material in an XML vocabulary (such as DocBook) and then transform it into uploadable HTML or/and TeX, further to be processed into PDF. Once automated, the conversion would take a few seconds.
Conversion to HTML is straightforward and problem free. Difficulties arise when trying to convert to TeX, which I shall next.
Diacritics, escaped sequences, and special characters
Some languages are written or typed in a richer character set than ASCII. In Spanish, a vowel may bear an acute accent ('á' and so on), and there is also 'ñ' '¡', '¿' and 'ü'. Other languages have grave accents, or hat accents. So most non-ASCII characters can be produced by accenting an ASCII character.
Since XSLT does not perform character transactions, these might be effected by means of regular expressions applied either before or after creating your TeX file. Most text editors include a
My tool of choice for this task is sed. Here is a handy script for Spanish to take your file from XML characters to TeX:
s/á/\\'a/g
s/é/\\'a/g
s/í/\\'\i{}/g
s/ó/\\'o/g
s/ú/\\'u/g
s/ü/\\"u/g
s/ñ/\\~n/g
s/Á/\\'A/g
s/É/\\'E/g
s/Í/\\'I/g
s/Ó/\\'O/g
s/Ú/\\'U/g
s/Ü/\\"U/g
s/Ñ/\\~N/g
s/¿/\\?`/g
s/¡/\\!`/g
Another sed script for non-Spanish non-ASCII character transformations is:
s/ä/\\"a/g
s/æ/\\ae{}/g
s/è/\\`e/g
s/ë/\\"e /g
s/ï/\\"\\i{}/g
s/ö/\\"o/g
s/ø/\\o{}/g
s/Ø/\\O{}/g
s/Æ/\\AE{}/g
s/È/\\`E/g
s/Ö/\\"O/g
s/ß/\\ss{}/g
s/ç/\\c c/g
s/Ç/\\c C/g
Mathematical formulas
DocBook, which is just an XML vocabulary, includes tags
<equation format='non-tex'><varname>x</varname><superscript>2</superscript> = -1</equation> <equation format='tex'>$$x^2 = -1$$</equation>
...
Encoding PostScript graphics in Plain TeX
After you have created an eps file named fig.eps or whatever, type:
\input epsf
\epsfbox{fig.eps}
Providing a Bounding Box
If you want to provide your own bounding box (figure size), use a call something like this:
\epsfbox[10 30 150 80]{whatever.eps}
The four numbers in square brackets tell TeX to use only part of the size of the graphic. In this example, TeX would pretend that only the rectangle from (10,30) to (150,80) is actually used. The dimensions are points, so the graphic would have an effective size (for TeX' purposes) of (150-10) or 140 points wide by (80-30) or 50 points tall.
The graphic is not actually cropped to the given size, it is only shifted on the page so that the lower left corner of the bounding box coincides with the lower left corner of the area TeX reserves for it. In the example above, location (10,30) in the figure would be located at the lower left corner of the box in which TeX places the figure, but any part of the image outside the rectangle from (10,30) to (150,80) would still appear on the page.
You can use a text editor to look at the PostScript file to find the figure' size. Look for a line that looks similar to this:
%%BoundingBox: 0 0 360 72
Scaling the Included EPS File
To scale a figure, use put the line:
\epsfxsize=<dimen>
before the \epsffile{} or \epsfbox{} command. You may use any standard TeX dimension units, though the system may default to points (pt). This command specifies the horizontal dimension, and the vertical dimension scales proportionally.
TeX Pros and Cons
Why is TeX still used? What are some good, modern alternatives? (stackexchange.com)
The reason TeX is still used is because it is open source and beautiful, because it is the best at handling mathematical notation, and because of its inertial dominance in math and the hard sciences in Academia. The reason TeX has so, so many fixable problems after 30 years is because there is no financial incentive for anyone to fix it.
The answer is not to find a TeX alternative. This will not be possible in Academia for a very long time. The answer is for someone to plunk down a million dollars to hire some full-time developers to fix it. Honestly, the TeX language is wonderful; it's the editors which are terrible. A TeX editor should...
- [] seamlessly hide the compilation process
- [] feature a modern debugging environment
- [] make 99% of commands (including everything you can do in MS Word) discoverable within the editor, rather than sending the user to the internet or some pdf guide, and
- [] robustly handle all modern image types
...without becoming an unstable WYSIWYG hybrid like LyX. The only thing about the language itself that might need to be changed is some standardization of common packages. I shouldn't need to download anything to get appendices and sub-figures to behave sensibly.
The amount of professor, post-doc, and grad student time wasted on TeX is staggering, and easily justifies paying for an overhaul...if only the government or some benefactor would step up.
xetex*
A simple book*
Setting Up the Page*
Importing Graphics
Including Embedded PS Files
First convert them to eps, which consists of adding Bounding Box information and some other decoration. Here is an almost minimal hello-type PS script:
%!.PS−Adobe−2.0 /Times-Roman 22 selectfont 1 1 moveto (Hello!) show
which can be converted with
Next, you include the perquisite packages in your latex file and then the eps file, as in:
\usepackage{graphicx}
\begin{figure}[htbp]
\includegraphics[height=1cm,angle=0]{Hello.eps}
\caption{includegraphics[height=1cm,angle=0]\{Hello.eps\}}
\label{hllo01}
\end{figure}
Exporting Graphics with dvipng*
eplain for Expanded Plain TeX
Eplain is a set of macros that provide functionality for plain TEX. It is intended to be useful regardless of how your document is formatted, unlike with LaTeX.
Invoking eplain
The simplest way to use Eplain is simply to put:
\input eplain
at the beginning of your input file. The macro file is small enough that reading it does not take an unbearably long time—at least on contemporary machines.
Lists
Many documents require lists of items, either numbered or simply enumerated. Plain TEX defines one macro to help with creating lists, \item, but that is insufficient in many cases. Therefore, Eplain provides two pairs of commands:
and
which are actually synonymous and produce a list with the items numbered sequentially, starting from one. A nested \numberedlist labels the items with lowercase letters, starting with 'a'. Another nested \numberedlist labels the items with roman numerals. Yet more deeply nested numbered lists label items with '*':
This produces a list with the items labelled with small black boxes (square bullets
). A nested \unorderedlist labels items with em-dashes. Doubly (and deeper) nested unordered lists label items with '*'s.
The two kinds of lists can be nested within each other, as well.
In both kinds of lists, you begin an item with \li. An item may continue for several paragraphs. Each item starts a paragraph.
You can give \li an optional argument, a cross-reference label. It's defined to be the marker
for the current item. This is useful if the list items are numbered. You can produce the value of the label with \xrefn.
Eplain can create hypertext links for the markers produced by \xrefn pointing to the relevant list item.
You can also say \listcompact right after \numberedlist or \unorderedlist. The items in the list will then not have any extra space between them. You might want to do this if the items in this particular list are short.
Here is an example:
\numberedlist\listcompact \li The first item. \li The second item. The second paragraph of the second item. \endnumberedlist
Formatting Lists
Several registers define the spacing associated with lists. It is likely that their default values won't suit your particular layout.
- \abovelistskipamount, \belowlistskipamount
- The vertical glue inserted before and after every list, respectively.
- \listleftindent, \listrightindent
- \listrightindent is the amount of space by which the list is indented on the right; i.e., it is added to \rightskip. \listleftindent is the amount of space, relative to \parindent, by which the list is indented on the left. Why treat the two parameters differently? Because (a) it is more useful to make the list indentation depend on the paragraph indentation; (b) footnotes aren't formatted right if \parindent is reset to zero.
The three vertical glues are inserted by macros, and preceded by penalties: \abovelistskip does \vpenalty\abovelistpenalty and then \vskip\abovelistskip. \belowlistskip and \interitemskip are analogous.
In addition, the macro \listmarkerspace is called to separate the item label from the item text. This is set to \enspace by default.
If you want to change the labels on the items, you can redefine these macros: \numberedmarker or \unorderedmarker. The following registers might be useful if you do:
- \numberedlistdepth, \unorderedlistdepth
- These keep track of the depth of nesting of the two kinds of lists.
- \itemnumber, \itemletter
- These keep track of the number of items that have been seen in the current numbered list. They are both integer registers. The difference is that \itemnumber starts at one, and \itemletter starts at 97, i.e., lowercase 'a'.
You can also redefine the control sequences that are used internally, if you want to do something radically different: \beginlist is invoked to begin both kinds of lists; \printitem is invoked to print the label (and space following the label) for each item; and \endlist is invoked to end both kinds of lists.
Verbatim Text
It is sometimes useful to include a file verbatim in your document; for example, part of a computer program. The \listing command is given one argument, a filename, and produces the contents of that file in your document. \listing expands \listingfont to set the current font. The default value of \listingfont is \tt.
You can take arbitrary actions before reading the file by defining the macro \setuplistinghook. This is expanded just before the file is input.
If you want to have line numbers on the output, you can say \let\setuplistinghook = \linenumberedlisting. The line numbers are stored in the count register \lineno while the file is being read. You can redefine the macro \printlistinglineno to change how they are printed.
Normally, the \listing command will add a final empty line at the end of the output, even if the file does not end in a newline. To suppress this final line, you can say \let\setuplistinghook = \nolastlinelisting. This also works with line numbers (say \def\setuplistinghook{\linenumberedlisting \nolastlinelisting}), but only if \printlistinglineno consists exclusively of boxes at the top level (i.e., any \kerns or glue should be wrapped up in a box).
You can use the form feed control character ( ASCII code 12, typed as CTRL-L) in the file to force a page break in the output.
You can produce in-line verbatim text in your document with \verbatim. End the text with |endverbatim. If you need a '|' in the text, double it. If the first character of the verbatim text is a space, use | . (| will work elsewhere in the argument, too, but isn't necessary.)
For example:
\verbatim| ||\#%&!|endverbatim
produces |\#%&!.
Line breaks and spaces in the verbatim text are preserved.
You can change the verbatim escape character from the default '|' with \verbatimescapechar char; for example, this changes it to '@': \verbatimescapechar \@.
The backslash is not necessary in some cases, but is in others, depending on the catcode of the character. The argument to \verbatimescapechar is used as \catcode 'char, so the exact rules follow that for \catcode.
To reset the category code of all special characters to 12 (other
), \verbatim uses \uncatcodespecials. If you make additional characters special
, you should extend \dospecials to include those characters, lest they be given special treatment inside verbatim environments. For example,
\catcode'\A=\active
% Try commenting out the following line.
\expandafter\def\expandafter\dospecials\expandafter{\dospecials\do\A}
\verbatimA#$%_^|endverbatim
Because \verbatim must change the category code of special characters, calling inside a macro definition of your own does not work properly. For example:
\def\mymacro{\verbatim &#%|endverbatim}% Doesn't work!
To accomplish this, you must change the category codes yourself before making the macro definition. Perhaps \uncatcodespecials will help you.
Links in eplain
Cross-references in eplain*
Hyperlinks in eplain*
\xrefn*
Latex
A simple LaTeX Example
Let's start with the simplest working example:
\documentclass{article}
\begin{document}
First document. This is a simple example, with no
extra parameters or packages included.
\end{document}
...
The preamble of a document
In the previous example the text was entered after the \begin{document} command. Everything in your .tex file before this point is called the preamble. In the preamble you define the type of document you are writing, the language you are writing in, the packages you would like to use (more on this later) and several other elements. For instance, a normal document preamble would look like this:
\documentclass[12pt, letterpaper]{article}
\usepackage[utf8]{inputenc}
As said before, this defines the type of document. Some additional parameters included in the square brackets can be passed to the command. These parameters must be comma-separated. In the example, the extra parameters set the font size (12pt) and the paper size (letterpaper). Of course other font sizes (9pt, 11pt, 12pt) can be used, but if none is specified, the default size is 10pt. As for the paper size other possible values are a4paper and legalpaper; see the article about Page size and margins for more details about this.
Below a detailed description of each line:
\usepackage[utf8]{inputenc}
This is the encoding for the document. It can be omitted or changed to another encoding but utf-8 is recommended. Unless you specifically need another encoding, or if you are unsure about it, add this line to the preamble.
Larger Fonts and Narrower Margins in LaTeX
Insert:
\fontsize{19pt}{19pt} \selectfont
Follow up with some margin and page width adjustments:
\addtolength{\oddsidemargin}{-.9in}
\addtolength{\evensidemargin}{-1.44in}
\addtolength{\textwidth}{1.8in}
Translating LaTeX to Plain TeX
Unfortunately, no "general", simple, automatic process is likely to succeed at this task.See How does LaTeX relate to Plain TeX for further details.
Obviously, trivial documents will translate in a trivial way. Documents that use even relatively simple things, such as labels and references, are likely to cause trouble (Plain TeX doesn't support labels). While graphics are in principle covered, by the Plain TeX.
Translating a document designed to work with LaTeX into one that will work with Plain TeX is likely to amount to carefully including (or otherwise re-implementing) all those parts of LaTeX, beyond the provisions of Plain TeX, which the document uses.
Some of this work has (in a sense) been done, in the port of the LaTeX graphics package to Plain TeX. However, while graphics is available, other complicated packages (notably hyperref) are not. The aspiring translator may find the Eplain system a useful source of code. (In fact, a light-weight system such as Eplain might reasonably be adopted as an alternative target of translation, though it undoubtedly gives the user more than the "bare minimum" that Plain TeX is designed to offer.)
ConTeXt
ConTeXt (originally entitled pragmatex
) is a general-purpose document processor. It is especially suited for structured documents, automated document production, very fine typography, and multi-lingual typesetting. It is based in part on the TeX typesetting system, and uses a document markup language for manuscript preparation. The typographical and automated capabilities of ConTeXt are extensive, including interfaces for handling microtypography, multiple footnotes and footnote classes, and manipulating OpenType fonts and features. Moreover, it offers extensive support for colors, backgrounds, hyperlinks, presentations, figure-text integration, and conditional compilation. It gives the user extensive control over formatting while making it easy to create new layouts and styles without learning the low-level TeX macro language.
ConTeXt provides a multi-lingual user interface with support for markup in English, Dutch, German, French, and Italian and support for output in many languages including western European, eastern European, Arabic-script, Chinese, Japanese, and Korean. It also allows the user to use different TeX engines like pdfTeX, XeTeX, and LuaTeX without changing the user interface.
ConTeXt Strong Points
Some of ConTeXt's strong points are:
- There aren't really any extra packages with
ConTeXt, just a few modules, so that you don't have to deal with package conflicts. - It sports a Built-in XML processor, which you may use with TEI and Docbook XML. You gain the typesetting sophistication of a TeX backend, coupled with the validation features of XML.
- PDF-X compliance pretty much right out of the box, whereas LaTeX lacks it. Useful if you are doing any kind of serious publishing.
- simplefonts package: load your system fonts like XeLaTeX
- UTF-8 support by default: important if you write a language other than english.
Comparison of ConTeXt with LaTeX and Other Typesetting Systems
ConTeXt may be compared and contrasted with LaTeX, but the primary thrust of the two are rather distinct. ConTeXt from the ground up is a typography and typesetting system meant to provide users easy and consistent access to advanced typographical control—important for general-purpose typesetting tasks. The original vision of LaTeX is to insulate the user from typographical decisions—a useful approach for submitting, say, articles for a scientific journal. LaTeX has evolved from that original vision; at the same time, ConTeXt's unified design avoids the package clashes that can happen with LaTeX.
Should I Use ConTeXt or LaTeX?
LaTeX is more of a standard document preparation system in academia. So if you ever want to submit a paper to a journal or conference and want to do it in TeX, LaTeX is your option.
It is safe to say that in general ConTeXt focuses a bit more on typography and a bit less on structure than LaTeX. There is quite a lot of functionality to handle page layouts, page arrangements, and page layering, for example.
Installing ConTeXt
On I have installed the following Debian packages: context, context-doc-nonfree, and context-modules. context-doc-nonfree contains documentation in PDF format which get installed in subdirectory /usr/share/texmf/doc/context/base/, whereas context-modules gets installed in /usr/share/texmf/doc/context/third/.
Package context itself is huge and gets installed in several key subdirectories. It does not seem to include any documentation, so we have to rely on context-doc-nonfree.
Installing the Minimals Distribution
These are the steps to install ConTeXt on Linux and Mac OS:
- Create a directory for ConTeXt, for example /home/user/context and change to it
- Download ConTeXt minimals installer: wget http://minimals.contextgarden.net/setup/first-setup.sh
-
To download the latest ConTeXt MKIV, run:
sh ./first-setup.sh.
Hence forward, every time you want to use context, you first need to tell bash where to find it. This is done by running:
- source /home/user/context/tex/setuptex if you are using
bash - source /installation-dir/tex/setuptex.csh if you are using
(t)csh
You can put the line for example in your ~/.bashrc.
Installing Minimals ConTeXt Modules
ConTeXt has a good selection of third party modules for different purposes. You can install them by:
./first-setup.sh --modules=all
Installing Everything in Minimals
You can install all things in the ConTeXt minimal distribution with:
first-setup.sh --context=beta --fonts=all --modules=all --goodies=all
Using ConTeXt
ConTeXt Basics
ConTeXt is a lot simpler than LaTeX especially when you want to achieve custom look for your documents. The examples from now on expect you to use a text editor which is UTF-8 compatible. Start by entering the following into your favourite text editor:
\starttext \ConTeXt is so easy! \stoptext
And compile it by typing:
context yourfile.tex
As you can see, no document class or anything need to be defined to produce valid ConTeXt output. By default, ConTeXt produces PDF output.
A Simple Structured-Text Example
Now, let's try something more complicated:
\mainlanguage[fi]
\starttext
\completecontent
\part{Something}
Lorem ipsum
\chapter{Something else}
Dolor sit amet
\stoptext
Now we've set to Finnish both the hyphenation and the auto generated element names (such as Table of Contents). We've also defined a part and a chapter, and generated a ToC with the
A More Advanced Structured-Text Example
Here we will additionally be using the macros
\starttext
\startsection[title={Testing ConTeXt}]
This is my {\em first} ConTeXt document.
\stopsection
\stoptext
A Still Richer Example
Here is another example from the wikipedia page:
% This line is a comment because % precedes it.
% It specifies the format of head named 'title'
% Specifically the style of the font: sans serif
% + bold + big font.
\setuphead[title][style={\ss\bfd},
before={\begingroup},
after={John Doe, the author\smallskip%
\currentdate\bigskip\endgroup}]
\starttext
\title{\CONTEXT}
\section{Text}
\CONTEXT\ is a document preparation system for the
\TEX\ typesetting program. It offers programmable
desktop publishing features and extensive
facilities for automating most aspects of
typesetting and desktop publishing, including
numbering and cross-referencing (for example to
equation \in[eqn:famous-emc]), tables and figures,
page layout, bibliographies, and much more.
It was originally written around 1990 by Hans
Hagen. It could be an alternative or complement
to \LATEX.
\section{Maths}
With \CONTEXT\ we could write maths. Equations
can be automatically numbered.
\placeformula[eqn:famous-emc]
\startformula
E = mc^2
\stopformula
with
\placeformula[eqn:def-m]
\startformula
m = \frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}}
\stopformula
\stoptext
ConTeXt Top Ten Commands
A novice user might be put off by the number of ConTeXt commands. Satisfying results can be obtained by only using the next ten groups of commands:
-
\starttext,
\stoptext -
\chapter,
\section ,\title ,\subject , \setuphead, \completecontent -
\em,
\bf ,\cap -
\startitemize ,\stopitemize ,\item ,\head -
\abbreviation ,\infull ,\completelistofabbreviations -
\placefigure ,\externalfigure ,\useexternalfigures -
\placetable ,\starttable ,\stoptable -
\definedescription ,\defineenumeration -
\index ,\completeindex -
\setuplayout,
\setupfootertexts ,\setupheadertexts
Basic Text Formatting
ConTeXt Font Switches
In ConTeXt there are four ways to switch fonts:
- font style/alternative commands (
\rm ,\ss , etc.), - font size commands (
\tfa ,\tfb , etc.), - mnemonic command aliases (
\bold ,\sans , etc.), - a complete font change (
\setupbodyfont ,\switchtobodyfont ).
Before you start...
-
Placing a font switch at the begin of a paragraph can sometimes generate unexpected side-effects. This can be avoided by forcing horizontal mode before any font change:
\dontleavehmode{\bf Warning!} Care must be taken when a font switch is used at the beginning of a paragraph.\par -
It is usually a bad style to use explicit font switches in the text. It is better to define a semantic command that takes care of the font switching. For example, instead of using {\bf\red important text}
\definehighlight[important][style=bold, color=red]
and then use \important{important text} in the text.
Font styles and alternatives
There are three main types of font styles: serif, sans serif, and teletype. To switch between these styles, use
Each of these styles comes in different alternatives: normal, bold, italic, slanted, bold-italic, bold-slanted, and small-capped. To switch to a different alternative, use typeface
) for normal,
You can generally combine font styles with alternatives, so if you want to switch to bold sans serif, you can use either
A font switch remains valid for the rest of the group. So, if you want to temporarily switch to a different font, use the font style command inside a group. The easiest way to start a group is to enclose the text within braces (also called curly brackets), for example
This is serif text
{\ss This is sans serif}
This is serif again
{\tt and this is typewriter}
And serif again
Emphasizing text
There is a font switch
ConTeXt uses the Latin Modern fonts by default; these fonts look similar to the original Computer Modern fonts, but have a much larger character repertoire. As it happens, in the Latin Modern (and Computer Modern) fonts, the slanted font does not stand out from the upright font enough for some tastes; so, many people prefer to use the italic font for emphasis. To do that use
\definebodyfontenvironment[default][em=italic]
For Opentype fonts, italic correction needs to be set using:
\definefontfeature[default][default][itlc=yes]
ConTeXt Font Sizes
Occasionally one needs to use a font size different from the bodyfont. ConTeXt provides two series of commands for that. For a larger font size, you can use \tfa to scale the font size by a factor of 1.2, \tfb to scale by a factor of (1.2)^2 = 1.44, \tfc to scale by (1.2)^3 = 1.728 and \tfd to scale by (1.2)^4 = 2.074. The scale is relative to the current bodyfont size.
To decrease the font size, you can use \tfx to scale the font by a factor of 0.8 and \tfxx to scale by a factor of 0.6.
The mapping of particular command suffixes (a, x, etc.) and current bodyfont size to effective font size can be changed by \definebodyfontenvironment. The default values defined in font-ini are:
\definebodyfontenvironment
[\s!default]
[ \s!text=1.0,
\s!script=0.7,
\s!scriptscript=0.5,
\c!a=1.200,
\c!b=1.440,
\c!c=1.728,
\c!d=2.074,
*=\currentfontscale, % wildcard
\c!x=0.8,
\c!xx=0.6,
\c!big=1.2,
\c!small=0.8,
\c!interlinespace=,
\c!em=\v!slanted]
It is also possible to set the scaling factors for specific font sizes. For example, if you want
\definebodyfontenvironment [10pt] [a=12pt] \definebodyfontenvironment [11pt] [a=14pt]
Font size can be combined with font styles. As a shortcut, you can use
These quick font switches are meant for changing the font style, alternative, or size of a few words: they do not change the bodyfont, so they don't affect interline spacing or math font sizes. So, if you want to change the font size of an entire paragraph, use \switchtobodyfont described below in Complete Font Change. However, it is fine to use them as style directives in setup commands, that is, using them as an option for style=... in any setup command that accepts style option.
Mnemonic font switches
While learning a document markup language like ConTeXt, it can be hard to remember all the commands. ConTeXt provides other, easy-to-remember font switches. So for bold you can use
-
\normal -
\slanted -
\boldslanted -
\slantedbold -
\bolditalic -
\italicbold -
\small -
\smallnormal -
\smallbold -
\smallslanted -
\smallboldslanted -
\smallslantedbold -
\smallbolditalic -
\smallitalicbold -
\sans -
\sansserif -
\sansbold -
\smallcaps
In addition, the commands
These mnemonic font switches are pretty smart. You can either use them as font style switches inside a { group }, or as a font changing command that takes an argument. For example,
This is {\bold bold} and so is \bold{this}. But this is not.
These mnemonic font switches can also be used for all style=... options, and while using them as style options, you can just give the command name without the backslash. For example:
\setuphead[section][style=bold]
Complete Font (BodyFont) Change
If you need to change to a different font size and take care of interline spacing, you can change the bodyfont by using
ConTeXt provides two relative sizes, called big and small. So, to increase the bodyfont size, use
The
Simple Typescript Example
This section describes how to map a Sans Serif font to the \ss command and a Serif font to the \rm command. This section also describes how typefaces differ from typescripts.
Requirements
This example uses Nimbus, which is a GPL font. Check whether Nimbus is available by running the following command:
mtxrun --script fonts --list --all --pattern=nimbus*
This should reveal a list similar to... If the font is not shown, you might have to install the font, which can be found on some systems at /usr/share/fonts/type1/gsfonts. You may use a different font; please see how to install fonts to MkIV for details.
The Code for Configuring a Font
% Enable Unicode fonts
\enableregime[utf]
% Enable Capital Letter use
\setupcapitals[sc=yes]
% Define a script named [serif][nimbus]
\starttypescript [serif] [nimbus]
\definefontsynonym [Serif] [name:nimbusromno9lregu]
\definefontsynonym [SerifBold] [name:nimbusromno9lbold]
\definefontsynonym [SerifItalic] [name:nimbusromno9lreguital]
\definefontsynonym [SerifSlanted] [name:nimbusromno9lreguital]
\definefontsynonym [SerifBoldItalic] [name:nimbusromno9lboldital]
\definefontsynonym [SerifBoldSlanted] [name:nimbusromno9lboldital]
\definefontsynonym [SerifCaps] [name:nimbusromno9lregu]
\stoptypescript
% Define a second script named [sans][nimbus]
\starttypescript [sans] [nimbus]
\definefontsynonym [Sans] [name:nimbussanlregu]
\definefontsynonym [SansBold] [name:nimbussanlbold]
\definefontsynonym [SansItalic] [name:nimbussanlreguital]
\definefontsynonym [SansSlanted] [name:nimbussanlreguital]
\definefontsynonym [SansBoldItalic] [name:nimbussanlboldital]
\definefontsynonym [SansBoldSlanted] [name:nimbussanlboldital]
\definefontsynonym [SansCaps] [name:nimbussanlregu]
\stoptypescript
% Define the typeface nimbus; use serif for rm-fonts, sans serif for ss-fonts.
\definetypeface [nimbus] [rm] [serif] [nimbus]
\definetypeface [nimbus] [ss] [sans] [nimbus]
% Indicate the typeface to use.
\usetypescript[nimbus][uc]
\setupbodyfont[nimbus,rm,10pt]
\starttext
Regular, {\it Italic}, {\bf Bold}, {\bi Bold-Italic}, {\sc KaPiTaLe}
\showbodyfont
\stoptext
Both scripts (serif and sans nimbus) map the fonts names to the different (existing) font style. Usage is implemented as follows:
- The
\setupbodyfont command calls the typeface nimbus. - The typeface nimbus calls the typescript [serif][nimbus] for
\rm fonts, or typescript [sans][nimbus] for the\ss fonts.
The scripts then map the fonts to different font styles.
Extension
The fonts can be changed by extending the script:
... \definefontsynonym [SansCaps] [name:nimbusromno9lregu] \stoptypescript % Define a typescript named nimbus. \starttypescript [nimbus] \definetypeface [nimbus] [rm] [serif] [nimbus] \definetypeface [nimbus] [ss] [sans] [nimbus] \stoptypescript % Use the nimbus typescript, which defines the nimbus typeface. \usetypescript[nimbus] \setupbodyfont[nimbus,rm,10pt] \starttext ...
Note that typeface [nimbus] and typescript [nimbus] are different.
Calling
\definetypeface [nimbus] [rm] [serif] [nimbus] \definetypeface [nimbus] [ss] [sans] [nimbus]
Linux Libertine on MKIV
Starting from Context 2010.05.21 there is the libertine typescript already defined. It points to the fonts shipped with TeXlive2010 (they have a different name than the upstream). You have to define script=latn if you want the ligatures in the Bold Italic font (until the upstream doesn't set a default script). See http://archive.contextgarden.net/thread/20101108.150757.a6a9040d.en.html
% use microtypography \definefontfeature[default][default][protrusion=quality,expansion=quality,script=latn] \usetypescript[libertine] \setupalign[hz,hanging] \setupbodyfont[libertine,10pt] \starttext \input tufte \stoptext
The complete code, which should work for ConTeXt shipped with TeXlive 2010 is:
\definefontfeature[default][default]
[protrusion=quality,
expansion=quality,
script=latn]
\starttypescriptcollection[linuxlibertine]
\starttypescript [serif] [linuxlibertine]
\definefontsynonym [Libertine-Regular] [file:fxlr.otf]
\definefontsynonym [Libertine-Italic] [file:fxlri.otf]
\definefontsynonym [Libertine-Bold] [file:fxlb.otf]
\definefontsynonym [Libertine-BoldItalic] [file:fxlbi.otf]
\stoptypescript
\starttypescript [serif] [linuxlibertine] [name]
\setups[font:fallback:serif]
\definefontsynonym [Serif] [Libertine-Regular] [features=default]
\definefontsynonym [SerifItalic] [Libertine-Italic] [features=default]
\definefontsynonym [SerifBold] [Libertine-Bold] [features=default]
\definefontsynonym [SerifBoldItalic] [Libertine-BoldItalic] [features=default]
\definefontsynonym [SerifCaps] [Libertine-Regular] [features=smallcaps]
\stoptypescript
\starttypescript [sans] [biolinum]
\setups[font:fallback:sans]
\definefontsynonym [Biolinum-Regular] [file:fxbr.otf]
\definefontsynonym [Biolinum-Bold] [file:fxbb.otf]
\definefontsynonym [Biolinum-Italic] [file:fxbri.otf]
\definefontsynonym [Biolinum-Slanted] [file:fxbro.otf]
\definefontsynonym [Biolinum-BoldItalic] [file:fxbbo.otf]
\stoptypescript
\starttypescript [sans] [biolinum] [name]
\setups[font:fallback:sans]
\definefontsynonym [Sans] [Biolinum-Regular] [features=default]
\definefontsynonym [SansBold] [Biolinum-Bold] [features=default]
\definefontsynonym [SansItalic] [Biolinum-Italic] [features=default]
\definefontsynonym [SansSlanted] [Biolinum-Slanted] [features=default]
\definefontsynonym [SansBoldItalic] [Biolinum-BoldItalic] [features=default]
\definefontsynonym [SansCaps] [Biolinum-Regular] [features=smallcaps]
\stoptypescript
\starttypescript [linuxlibertine]
\definetypeface [linuxlibertine] [rm] [serif] [linuxlibertine] [default]
\definetypeface [linuxlibertine] [ss] [sans] [biolinum] [default]
\definetypeface [linuxlibertine] [tt] [mono] [default] [default]
%definetypeface [libertine] [mm] [math] [times] [default]
\quittypescriptscanning
\stoptypescript
\stoptypescriptcollection
\usetypescript[linuxlibertine]
\setupbodyfont[linuxlibertine,10pt]
% use the microtype
\setupalign[hz,hanging]
\starttext
\input tufte
\stoptext
Capitalizing words
Note that \WORD, \Word and all following macros aren't switches, but commands (brackets behind, not around): {\em switch}, vs \Word{macro}.
Underline, strike through, and overline
Underlined, struck, and overlined text can be achieved with
Verbatim Code
- single commands: \tex{a tex command}
- oneliners: \type{tex code}
- source code: \starttyping etc.
Quotes
Don't try to type quotation marks, but use logical markup! Quotation marks and formatting are language dependent.
- single quotes: \quote{some text}
- double quotes: \quotation{some text}
- long quotations: try \startquote or \startquotation etc. See also Long quotations and Extracts below.
Long quotations and Extracts*
Nested Quotations*
(For alternate nesting of double and single quotes.)
Language
For short quotes you can switch the language (and depending setups like quotation marks) with the language code like {\de das ist Deutsch}. If you switch between longer sections or if the two-letter language code has some other meaning (like \sl stands for slanted and can't be used to start Slovenian) you should use \language[sl].
To switch the document language, and not just the hyphenation rules, use \mainlanguage[de]. This will replace e.g. Chapter
with Kapitel
, and Figure
with Abbildung
, in the case of German.
Drawing in ConTeXt
As its native drawing engine, ConTeXt integrates a superset of MetaPost called MetaFun, which allows the users to use the drawing abilities of MetaPost for page backgrounds and ornaments. Metafun can also be used with stand alone MetaPost. ConTeXt also supports the use of other external drawing engines, like PGF/TikZ and PSTricks.
ConTeXt Page Layout
Typesetting areas
The 25 typesetting areas of a ConTeXt page are divided into 5 columns and 5 rows. From left to right, one encounters leftedge, leftmargin, text, rightmargin, and rightedge. From top to bottom, the areas are called: top, header, text, footer, bottom. E.g. leftmargin is the margin area to the left of the main text area; {leftmargin,bottom} is below it, at the same height as the bottom area. In between the two lies the area {leftmargin,footer}.
Defining the layout in ConTeXt
Positioning the areas is by setting the following dimensions using
You always define a right page; if you use a double page layout, right and left values are mirrored on a left page. Doublesided typesetting is activated with
- Set the backspace and width, and the topspace and height. The width is the width of the main typesetting area; the backspace is its distance from the left edge of the page. The height is the distance from the top of the header to the bottom of the footer; the topspace is the distance from the top edge of the page to the top of the header.
- Set the header and headerdistance, and the footer and footerdistance. The header is the vertical size of the header area; the headerdistance is the distance from the header area to the text area. The footer and footerdistance work likewise.
- Once the header(distance) and footer(distance) are subtracted from the height, what remains is the textheight: the height of the main typesetting area. Although it would be very useful, you cannot set this dimension directly.
- If you want to typeset anything above the header, define topdistance (the distance from the top of the header to the bottom of the topmost typesetting area) and top (the height of the topmost typesetting area). For typesetting below the footer, define bottomdistance and bottom.
- As for the horizontal dimensions apart from the width: starting at the left edge of the main text area, and moving away from the center, one first sets the leftmargindistance; then one sets the width leftmargin of the margin typesetting area; then one sets the leftedgedistance; and then there is the leftedge typesetting area. On the right: rightmargindistance, rightmargin, rightedgedistance, rightedge.
Paper size
Page size and paper size are set with
Example layout
\setuppapersize[A4][A4] % this is the default and may be omitted
\setuplayout[backspace=20mm,
width=160mm,
topspace=20mm,
header=0mm,
footer=0mm,
height=250mm]
Multiple layouts
If you need to use different layouts in some parts of the document, you can set up a global layout, and then define additional named layouts for the deviating parts. You only need to specify the dimensions that differ: unspecified dimensions will be inherited from the global layout.
To switch to a different layout, call it up in the appropriate place in the document. To revert back to the global layout, use
\setuplayout[...] % global layout \definelayout[wide][...] % layout of the first page \setuplayout[wide] % switch to layout called 'wide' \setuplayout[reset] % switch back to the global layout
To specify in advance that you want to change layouts starting from page 4 (e.g.), use
% different layout for first two pages \definelayout[1][wide] \definelayout[3][reset]
For the page numbers you can use absolute numbers (as above), relative numbers (like +1, -2) or the keywords
\setuplayout[ % default layout (right page) ... ] \definelayout[even][ % different layout on left pages ... ]
If you define additional layouts in a doublepage (duplex) setup, remember to think mirrored: leftmargin defines the right margin, backspace is the distance from the spine to the right edge of the text area etc.
ConTeXt Layout Advanced features
-
To allow Acrobat Reader users (among others?) to make layers visible/invisible at will, add the following command at the start of your file:
\showlayoutcomponents
-
If you have a certain run of text that you want to keep together, you can test for the number of lines available on the current page with
\testpage[n] , where n is the number of lines required. If there are not n lines available, a page break will be inserted at the location of the\testpage command. -
If you need absolute positioning of objects (text, pictures) on the page, but ad-hoc rather than systematic, the Layers mechanism is more suitable.
-
For layout from a XML/FO perspective, with some descriptive pictures, see At Paul Tremblay's XML ConTeXt site.