




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















TUGboat, Volume 0 (2001), No. 0 preliminary draft, 1 Apr 2002 7:30 1001
LATEX Editing Support
Nelson H. F. Beebe
Contents
1 Introduction 1001 2 Emacs history 1002 3 Emacs editing model 1002 4 Emacs documentation 1003 5 Learning an Emacs editing mode 1004 6 LATEX support 1004 6.1 Preliminaries 1005 6.2 Creating a new LATEX file 1007 6.3 LATEX macros 1008 6.4 LATEX environments 1009 6.5 Common commands 1010 6.6 Math mode 1010 6.7 Dots, commas, and quotation marks 1011 6.8 Font changes 1012 6.9 Comments 1012 6.10 Mismatched delimiters 1013 6.11 Mismatched environments 1013 6.12 Word abbreviations 1014 6.13 Bibliographies 1014 6.14 Indexing 1015 6.15 Cross-references 1015 6.16 French typography 1016 6.17 Miscellaneous functions 1017 6.18 Miscellaneous variables 1017 6.19 Customizing lists 1018 7 SliTEX support 1018 8 Letter support 1019 9 Bug reporting 1020 10 Conclusion 1020 Index 1022
List of Figures
1 Online summary of LATEX mode. 1004 2 More about LATEX mode. 1005 3 Online help for LaTeX-index. 1005 4 Local bindings in LATEX mode. 1006 5 More local bindings. 1006 6 .emacs file additions. 1006 7 Letter template. 1019
1 Introduction
The structured markup of LATEX can be easy to read and understand, but tedious to type. Its syntax of environment groups bears a strong resemblance to the begin/end groups of the Algol family of
computer programming languages, which can be de- scribed by rigorous grammars that in turn permit the automatic construction of lexical analyzers and parsers, and structured editors to support program- ming in those languages [4, pp. 97–116, pp. 128–140, pp. 232-239]. This article describes a powerful facil- ity for the preparation of LATEX documents using the Emacs text editor. The convention here is that material displayed in a typewriter font is computer output, a pro- gram name, or all or part of a file name. A sans serif font is used for key names and Emacs functions, and a slanted font for Emacs variable names. Emacs is very likely the world’s most power- ful text editor, because it is highly programmable and customizable. The popularity of the original Emacs on the DEC PDP-10 architecture in the 1970s led to several reimplementations on other op- erating systems, particularly on UNIX and VAX VMS. The wide availability of the excellent im- plementation from the Free Software Foundation, known as GNU Emacs, has made Emacs the editor of choice for many programmers on machines more powerful than personal computers. Smaller Emacs- like editors have also been developed, including
1002 preliminary draft, 1 Apr 2002 7:30 TUGboat, Volume 0 (2001), No. 0
2 Emacs history
Emacs was developed by Richard M. Stallman start- ing about 1974 on a PDP-10 running MIT’s ITS (Incompatible Timesharing System) operating sys- tem. The kernel of the editor was written in PDP- 10 assembly language, which could be made to pro- duce versions for DEC’s TOPS-10 and TOPS-20 sys- tems and Stanford’s SAIL system as well, thanks to the availability of conditional compilation facilities. SAIL was the home of the original TEX development. Because PDP-10 machines formed the back- bone of the original Arpanet, the precursor to to- day’s Internet linking millions of computers, and be- cause Emacs’ author believed fervently in the value of sharing of software, Emacs was soon in wide use throughout the Arpanet. Like Topsy in Uncle Tom’s Cabin [21, p. 277], PDP-10 Emacs just grew; the final version from the mid 1980s had about 150 libraries and perhaps 2000 editing functions. What made this possible was the architectural division of the editor into two parts:
Emacs supports simultaneous editing of multi- ple files in multiple buffers, with the screen divided horizontally and/or vertically to provide windows into one or more buffers. It also supports an ex- tensive on-line help system, with self-documenting commands, and the full text of many user manuals accessible inside the editor. All of this power requires a lot of code to sup- port it, and about a megabyte of central memory to run satisfactorily; that is why GNU Emacs has not been ported to personal computer environments. At version 18.57, GNU Emacs consists of about 73600 lines of C code in 188 source files, 55300 lines of Lisp in 145 libraries, 594 functions written in C, and 2718 functions written in Lisp. The LATEX support code described here consists of about 4200 lines of Lisp defining 91 functions and 54 variables, together with an additional 900 lines and 30 functions of auxiliary support. Some people argue that such a powerful editor ‘wastes machine resources’; I disagree—computers should work for people, not the reverse.
3 Emacs editing model Some vendor-provided text editors, such as edt in VAX VMS and vi in UNIX, have two modes: com- mand mode, and text insertion mode. The meaning of a key depends on which mode you are in, and some users find themselves frequently making mis- takes because they type in the wrong mode. Emacs does not make a distinction between these two. Instead, each character you type runs a function. The function attached to most printing characters just inserts them in the buffer, so entry of normal text works just like in other editors. How- ever, certain keys invoke editing functions that do other tasks. For example, pressing the DELete key results in a call to a function that deletes the char- acter on the screen immediately before the cursor. The execution of editing functions in response to keystrokes requires character-at-a-time input. Some older mainframe operating systems do not support this, but all newer ones do. Because most printing characters are needed for themselves, and most ASCII control characters have no useful printable representation, commonly- needed editing functions are assigned to control characters, with mnemonic significance where possi- ble. For example, the character generated by hold- ing down the control key while pressing the e key, represented by the compact notation C-e, runs a function that moves the cursor to the end of the current line, and C-d runs a function that deletes the character under the cursor.
1004 preliminary draft, 1 Apr 2002 7:30 TUGboat, Volume 0 (2001), No. 0
down, and sideways through the branches, jump- ing temporarily into cross-references or to arbitrary nodes by name, and retracing one’s node path which info always remembers. Since the info text is al- ways viewed in an Emacs buffer, which might be visible in one of several windows on the screen, doc- umentation can be read (and edited) while you are inside Emacs. You can enter and leave info at will. Emacs always remembers where you were, so reentry brings you back to the exact spot in the documen- tation that you were reading before.
5 Learning an Emacs editing mode
When faced with a new editing mode (i.e. set of key- function bindings), an Emacs user wants to be able to find out how to use it. This can be done in several ways:
6 LATEX support
Now that you understand how Emacs works, we can move on to a discussion of the LATEX editing sup- port. The material that you are now reading is con- tained in the distribution as two files, ltxmode.ltx for the TUGboat article, and ltxinfo.ltx for LATEXinfo.
LaTeX Mode: Major editing mode for LaTeX and SLiTeX, with tex-mode underneath.
To create a new LaTeX document, use make- LaTeX-document (on C-c d), or make-SLiTeX- document (on C-c s). With an argument, they will provide some additional helpful comments. The functions will prompt for document style and options. Type? to see the standard ones; you can enter them with name completion. You can also enter your own, since it is possible to have private styles and options unknown to make-LaTeX-document or make-SLiTeX-document.
The most frequent LaTeX construct is the \begin{}...\end{} grouping; you can generate it by LaTeX-begin-end-block (on C-c b). With an argument, a helpful comment may be printed. Type? to see the standard environments, or enter your own. If you type a \begin{...} manually, you can later generate a matching \end{...} with the function LaTeX-end (on C-c n).
Other common constructs are the insertion of labels, citations, cross-references, index entries, verbatim strings, and additional items in a list. The functions C-c. LaTeX-add-word-to-index C-c C-b LaTeX-bibitem C-c c LaTeX-cite C-c k LaTeX-counter C-c f LaTeX-footnote C-c x LaTeX-index C-c i LaTeX-item C-c l LaTeX-label C-c m LaTeX-macro C-c p LaTeX-pageref-with-completion C-c C-p LaTeX-protect C-c r LaTeX-ref-with-completion C-c v LaTeX-verb C-c d make-LaTeX-document C-c s make-SLiTeX-document provide for these.
LaTeX-tab (on C-c TAB) will indent a line to the current \begin{}...\end{} nesting level.
Most major LaTeX macros can be entered by LaTeX-macro (on C-c m). This will supply the correct set of following braces, brackets, and parentheses, and with an argument, will insert a short comment about the expected command arguments.
For SLiTeX, the function renumber-slides can be used to put a numbered comment on each
Figure 1: Online summary of LATEX mode.
TUGboat, Volume 0 (2001), No. 0 preliminary draft, 1 Apr 2002 7:30 1005
slide environment for handy reference in the \onlynotes{...} and \onlyslides{...} commands.
You can move over \begin{} ... \end{} groups with LaTeX-to-begin (on C-c a) and LaTeX-to-end (on C-c e).
Insertion of paired angle brackets, braces, square brackets, and parentheses is provided by C-c < LaTeX-angles C-c { LaTeX-braces C-c [ LaTeX-brackets C-c ( LaTeX-parentheses With an argument, the last three insert backslash prefixes for literal braces, math mode, and displaymath mode.
Unbalanced character pairs are found by C-c > LaTeX-check-angle-balance C-c } LaTeX-check-brace-balance C-c ] LaTeX-check-bracket-balance C-c $ LaTeX-check-dollar-balance C-c ) LaTeX-check-parenthesis-balance
You can test for undefined labels with check-LaTeX-labels, display the labels and their line numbers with show-LaTeX-labels, and fetch labels from an .aux file with update-LaTeX-labels.
Environment nesting errors can be caught by check-LaTeX-nesting.
Use indent-LaTeX-begin-end-groups to get environments nested for improved visibility.
Use LaTeX-comment (on C-c %) to comment out the current paragraph (no arg) or region (arg); undo with M-X undo (C-_). LaTeX- uncomment (on C-c u) is the inverse function.
One or more words can be set in any standard LaTeX font using the commands C-c C-c b LaTeX-font-bf C-c C-c e LaTeX-font-em C-c C-c i LaTeX-font-it C-c C-c r LaTeX-font-rm C-c C-c u LaTeX-font-sc C-c C-c f LaTeX-font-sf C-c C-c s LaTeX-font-sl C-c C-c t LaTeX-font-tt
Please report bugs, comments, and enhancements by e-mail to [email protected] (Internet) LaTeX-gripe (on C-c g) makes this easier.
Figure 2: More about LATEX mode.
LaTeX-index: Insert \index{ ... } at point (on C-c x).
If a prefix argument is given, the string is prompted for, and inserted both as text and as an index entry, e.g. gnats and gnus\index{gnats and gnus}. All horizontal space preceding \index is removed to prevent an intervening page break causing an off-by-one page number error.
If LaTeX-index-start-with-newline is non-nil, insert a percent to start a comment, then put \index at the start of a following new line. If LaTeX-index-end-with-newline is non-nil, follow the entry with a new line.
Figure 3: Online help for LaTeX-index.
6.1 Preliminaries The first job is to arrange for LaTeX-mode to be selected automatically when required. Because the latex.el file of Lisp code is not yet a standard part of the GNU Emacs distribution, its association with particular file extensions is un- known to Emacs. To remedy that, the Lisp code in Figure 6 on page 1006 should be inserted into the .emacs file in your login directory; that file is pro- cessed each time Emacs starts up. The load com- mand there tells where latex.el is found; it may need adjustment for your system. The peculiar if commands attach LaTeX-mode to the auto-mode-alist variable, which is a list of pairs of file extensions and their mode names; the attachment is omitted if the file extensions are al- ready in the list. Once this startup code has been executed, Emacs will automatically select LaTeX-mode when you visit files with extensions .ltx (LATEX docu- ment), .stx (SliTEX document), or .sty (LATEX style). Others can be easily added according to taste. File extension .tex is already attached to GNU Emacs tex-mode which comes with the sys- tem, so different extensions are needed for different editing modes. If you don’t have these associations of file exten- sions with editing modes in effect, you can always select the mode manually with the command M-x LaTeX-mode. Experienced Emacs users may wonder why the autoload facility is not used instead of the explicit load command in the startup file; the reason lies in a conflict with the standard tex-mode. I expect
TUGboat, Volume 0 (2001), No. 0 preliminary draft, 1 Apr 2002 7:30 1007
that conflict will be removed when latex.el be- comes part of the standard GNU Emacs distribu- tion. A modification of tex-mode.el that eliminates all LATEX-specific code has been prepared locally, and that new version removes the incompatibility with latex.el, allowing autoload to be used. In GNU Emacs Lisp, named functions, and variables defined outside functions, are known glob- ally. There is no provision for file scoping or mode scoping to limit name visibility. Consequently, to avoid collision with the thousands of names from other libraries, each library usually includes a dis- tinctive phrase in its global names. Naturally enough, LaTeX and SLiTeX are the phrases chosen in latex.el. They are almost always used as pre- fixes in variable names, and usually also in func- tion names, although a few functions have embed- ded phrases for better readability (e.g. show-LaTeX- labels).
6.2 Creating a new LATEX file
When you visit a new LATEX file, Emacs starts up with an empty buffer. The mode line at the bottom of the screen will look something like
---Emacs: foo.ltx (LaTeX Abbrev Fill)----All---
The first thing you want to do is get a standard template of a LATEX file inserted; you do this by typing C-c d (make-LaTeX-document). This function will first prompt you with
Document style:
to which you can respond either with a complete style file name, or with the first few characters of a standard style, followed by a space to request Emacs to complete the name, and a RETurn to accept the completion. If you are unsure of what to supply, just type a query (?); Emacs will respond with something like
Possible completions are: aaai amsart amsbook amstex aps article book deproc letter ltugproc refman report siam slides tugboat ucthesis uoftoronto usafmemo uuthesis xxxslides
Completion can also be requested on partial names: the input a? in the above command will respond with
Possible completions are: aaai amsart amsbook amstex
aps article Suppose you type article or ar , followed by a RETurn. Then Emacs will respond with Document option (RET when done): to which you can then supply an option name fol- lowed by a RETurn. As before, a query will show you what is available: Possible completions are: 11pt 12pt a4 a4wide acm acronym agugrl agujgr alltt amsbsy amscd amsfonts amssymb amssymbols amstext apalike archmemo array bezier biihead boxedmini changebar chapterbib cite clsc clscmemo concrete cropmark ctagsplt cyrillic dblspace doublespace draft drafthead drop dvidoc eqsecnum espo fleqn format fullpage geophysics german gnuindex ifthen intlim ist21 leqno listing longtab ltugboat makeidx math merge mfr mitthesis moretext natsci nl nonamelm nopageno nosumlim openbib pandora preprint proc psmavg psmbkm psmncs psmpal psmtim remark resume revtex righttag sc sc21-wg1 sfwmac showidx showlabels slem spacecites supertab suthesis tablisting tapeseal texindex texnames tgrind theorem thp threepart titlepage trademark troffman troffms twocolumn twoside
1008 preliminary draft, 1 Apr 2002 7:30 TUGboat, Volume 0 (2001), No. 0
underline uofutah vdm verbatim
You can keep on selecting options until you finally just type a bare RETurn, at which point make- LaTeX-document completes, and you have a buffer that looks like this: % --latex-- % Document name: /u/beebe/foo.ltx % Creator: Nelson Beebe [[email protected]] % Creation Date: Sun Jul 28 08:44:46 1991 \documentstyle[11pt,makeidx]{article} \newcommand{\X}[1]{{#1}\index{{#1}}} \begin{document} 2 \end{document} The cursor, represented by 2 , is left positioned on the line following the \begin{document}, ready for text entry. The initial comment with the tag --latex-- is a special one. It requests an automatic mode selec- tion when the file is freshly visited in Emacs, over- riding any mode that might otherwise be selected based on the file name extension. latex-mode is made equivalent to LaTeX-mode in latex.el so that the comment tag can be written in lower-case letters, as is conventional. The % Creator: comment information is ob- tained from Emacs’ operating system interface, which in turn fetches the user’s personal name and login name from system authorization files. On net- worked systems, the hostname is included as well, creating a valid electronic mail address. Had you given make-LaTeX-document an argu- ment, it would have been somewhat more verbose: % --latex-- % Document name: /u/beebe/tex/tugboat/foo.ltx % Creator: Nelson Beebe [[email protected]] % Creation Date: Sun Jul 28 08:46:33 1991 %---------------------------------------------- % EVERYTHING TO THE RIGHT OF A % IS A REMARK % TO YOU AND IS IGNORED BY LaTeX. % % WARNING! DO NOT TYPE ANY OF THE FOLLOWING 10 % CHARACTERS AS NORMAL TEXT CHARACTERS: % & $ # % _ { } ^ ~
% % The following seven are printed by typing a % backslash in front of them: % $ & # % _ { and }. %---------------------------------------------- \documentstyle[11pt,makeidx]{article} \newcommand{\X}[1]{{#1}\index{{#1}}} \begin{document} 2 \end{document}
The extra commentary is a useful reminder for be- ginning LATEX users. Several other commands in LaTeX-mode use the presence of an argument to sup- ply additional helpful commentary. The \X command is one I have found helpful for preparing indexes; typing \X{gnats and gnus} will put that phrase in both the document and the index. Further discussion is given in the Indexing section beginning on page 1015. The lists of standard styles and options are em- bedded in the latex.el code. They cannot be de- termined automatically from the file system for sev- eral reasons:
6.3 LATEX macros Every one of the 589 LATEX macros in the index to the LATEX User’s Guide and Reference Manual [15] is known to the function LaTeX-macro (on C-c m), and as before, Emacs command completion is avail- able with the query (?) and space ( ) characters. Thus, you can type
1010 preliminary draft, 1 Apr 2002 7:30 TUGboat, Volume 0 (2001), No. 0
If you have private environments, you can still use C-c b; you just have to type the complete en- vironment name. If you use some private ones fre- quently in different documents, it is possible to ex- tend the list of environments known to LaTeX-mode. See the section Customizing lists on page 1018 for details. In those environments that have \item com- mands, four are generated by default; that number can be changed by modifying the value of the Emacs variable LaTeX-item-count. Their indentation is de- fined by the variable LaTeX-item-indentation; the default is two spaces. Additional indentation of text under a \item command is set by the variable LaTeX-item-info-indent; the default is six spaces. You can generate additional \item commands as needed with the function LaTeX-item on C-c i. With an argument, it supplies the alternate form \item[] instead. If you forgot about the C-c b command, and manually typed a \begin{conjecture}, you can get the matching \end{conjecture} generated au- tomatically by typing C-c n (LaTeX-end). That is also sometimes helpful when you have forgotten what environment you are in: you can generate the \end{...}, and then kill it. You can type C-c a (LaTeX-to-begin) to move backward to the enclosing \begin; with an argu- ment, you can move backward over a specified num- ber of \begin{...}s. If the argument is negative, you move forward over \end{...}s instead. Usu- ally, you would use C-c e (LaTeX-to-end) instead to move forward over \end{...}s; that command han- dles numeric arguments too, and reverses direction for negative arguments. These two movement commands are analogous to the standard Emacs commands for moving back- ward and forward in sentences, normally bound to M-a and M-e. They also require that the \begin and \end macros be preceded on their lines only by optional whitespace, and immediately followed by open braces. This helps to enforce the discipline of keeping the \begin{...}... \end{...} grouping properly nested and readable, and also avoids hav- ing to deal with more complex input parsing.
6.5 Common commands
Some LATEX macros are used so often that it is desir- able to have them bound directly to keys, instead of having to type their first few characters with LaTeX- macro as described earlier. You can find a list of these convenience functions in the fourth paragraph of Figure 1 on page 1004.
For example, typing C-c l (that’s the letter ‘l’) generates ~\label{ 2 } at the cursor position, leaving the cursor after the open brace.
6.6 Math mode TEX’s math mode uses paired dollar signs to delimit the math text. Single dollar signs mark inline math, and doubled ones mark display math. If you for- get to type a closing dollar sign, or type the wrong number of dollar signs, TEX will complain bitterly. The start and finish of these math regions are indistinguishable, making it hard for simple pro- grams (and sometimes, readers) to distinguish the ‘inside’ from the ‘outside’. Consequently, LATEX additionally supports two bracketing forms: (... ) for $ ... $, and [... ] for $$ ... $$, as well as more readable forms \begin{math} ... \end{math}
\begin{displaymath} ... \end{displaymath} for the single and double dollar sign pairs, respec- tively. All of these have unique opening and closing sequences. LaTeX-mode supports all of these forms. The variants selected are determined by the vari- ables LaTeX-math-option and LaTeX-displaymath- option. Values of 0, 1, and 2 select the dollar, back- slashed delimiter, and \begin{...}... \end{...} environment forms respectively; all other values are equivalent to 0. The default values select the single dollar and displaymath forms. Normally, when you type a dollar sign, you get an inline math environment. If the dollar sign hap- pens to be at the beginning of a line, it expands instead into a display environment. On the other hand, if the preceding character was a backslash, you just get a plain dollar sign. Spacing around the inserted text is controlled by two more variables. If LaTeX-newline-after- opening-delimiter is non-nil (the default), the open- ing delimiter is followed by a newline, with the cursor positioned immediately after the delimiter for the inline case, and on a new line for the dis- play form. If LaTeX-newline-after-closing-delimiter is non-nil (the default), the closing delimiter is fol- lowed by a newline.
TUGboat, Volume 0 (2001), No. 0 preliminary draft, 1 Apr 2002 7:30 1011
This pleasantness is our first example of having an alternate function bound to a normal printing character. Instead of running the usual self-insert- command attached to printing characters, $ is bound to LaTeX-dollar which has been programmed to deal with the three different meanings of the dollar sign. Few editors outside the Emacs family could do this; the critical feature is that any character can run any function. What if you really just wanted a single plain dollar sign, with no preceding backslash? Well, that is easy. In Emacs, any character can be quoted, which causes it to be inserted directly into the buffer; the quoted-insert function is normally bound to C-q, but that too can be changed. Thus, C-q $ will get you a literal dollar sign, if that is what you really want. The function LaTeX-equation on C-c = gener- ates \begin{equation} 2 \end{equation} with the cursor between them. LaTeX-displaymath on C-c C-c = inserts \begin{displaymath} 2 \end{displaymath} All math mode environments (array, eqnarray*, eqnarray, math, and theorem) can be also generated by LaTeX-begin-end-block on C-c b, and additional ones can be easily added; see Customizing lists on page 1018. LaTeX-subscript on _ and LaTeX-superscript on ˆ generate braced subscript and superscript se- quences, leaving the cursor between the braces [22].
6.7 Dots, commas, and quotation marks
The dot or period (full stop, to some of you) is an overloaded character. Normally, it just means end of sentence. Sometimes, it ends an abbreviation in the middle of a sentence. It can also be a decimal point, as in 3.14159. Still other times, it appears in ellipses, as in · · · (\cdots),
.. (\ddots),^...^ (\ldots), and .. (\vdots).
In typography, these uses are distinguished by small changes in spacing after the dots. That is why TEX provides control sequences for the ellipses, and the LATEX book [15, p. 14] recommends that you type a \ sequence after a period that does not end a sentence. TEX assumes that a period following an upper- case letter does not end a sentence (it might be someone’s initial) [14, pp. 74, 311], and follows it with a smaller amount of space. The LATEX User’s
Guide and Reference Manual recommends insertion of @ before a sentence-ending dot that follows an upper-case letter in order to get additional space af- ter the dot. LaTeX-mode handles these intricacies by bind- ing dot to the function LaTeX-dot. That function examines what is immediately before the dot in the buffer, and takes one of several actions:
TUGboat, Volume 0 (2001), No. 0 preliminary draft, 1 Apr 2002 7:30 1013
variable LaTeX-comment-prefix; its default value is %%:. A unique prefix is desirable to distinguish such lines from ordinary comments. You should avoid using any regular-expression matching char- acters in it. You can remove the comments inserted by LaTeX-comment by using the function LaTeX- uncomment on C-c u. It should normally be used with an argument to act on a region, instead of a paragraph. The reason for this is that paragraphs are recognized according to the regular expression in the Emacs variable paragraph-separate; the de- fault setting is such that a line containing only a comment ends a paragraph. Consequently, LaTeX- uncomment will do nothing because its ‘paragraph’ is always empty. Invoking it with an argument to process a marked region solves the problem.
6.10 Mismatched delimiters
TEX gets very unhappy when it finds mismatched braces, and in complex documents, it can sometimes be difficult to find them. The job is not made easier on low-resolution screen displays where braces and parentheses are virtually indistinguishable. Finding such mismatches is a job for a computer, not a hu- man, and LaTeX-mode offers you help. Braces are not the only things you might want assistance with. Checking for mismatched paren- theses, square brackets, and angle brackets is also supported. These normally insert themselves when you type them, but LaTeX-mode has commands that insert pairs: typing C-c { gets you a pair of open and close braces, and similarly for C-c [, C-c (, and C-c <. These are the default bindings of the functions LaTeX-braces, LaTeX-brackets, LaTeX- parentheses, and LaTeX-angles. If you get in the habit of using these instead of typing the delimiter pair yourself, you will rarely have mismatch problems. Emacs itself has native delimiter matching support: as you type a close de- limiter, the cursor flashes briefly to the matching open delimiter. But what if you didn’t follow my advice, typed a lot of braces yourself, and then when TEX com- plained about unbalanced braces, you couldn’t find the errors? Well, the function LaTeX-check-brace- balance bound to C-c } will scan the buffer from the current point to the end, checking for unbalanced braces, and brace pairs separated by unusually long strings, but ignoring backslashed braces. It com- plains if it finds a paragraph break between braces, unless you give it an argument. If mismatches are detected, you are so informed, and the positions of
the mismatches are remembered on Emacs’ stack of marks, so you can easily get to them. Similar functions LaTeX-check-angle- balance, LaTeX-check-bracket-balance, and LaTeX- check-parenthesis-balance are provided on C-c >, C-c ], and C-c ), for checking those delimiter balances. Note the key binding symmetry: C-c open-delimiter inserts the pair, and C-c close-delimiter checks the balance. The characters < and > are likely to be used in math mode, and not require balancing. However, you might also have used them for other purposes. In such a case, you can just add matching delimiters inside comments in your math mode uses, and then C-c > will work satisfactorily. There is also LaTeX-check-dollar-balance on C-c $. It looks for dollar pairs separated by long strings, ignoring backslashed dollars. It also complains about paragraph breaks between dollar pairs, un- less it is given an argument. There is no way for a computer program that is much less complex than TEX to tell the inside of math mode from the out- side, so you can confuse this function by starting it inside math mode. The Emacs variables LaTeX-angle-interval, LaTeX-brace-interval, LaTeX-bracket-interval, LaTeX-dollar-interval, and LaTeX-parenthesis- interval set the limiting between-delimiter string length before a warning is raised; their default val- ues are each set to 500 characters.
6.11 Mismatched environments If you have a complex document where \begin{...}
... \end{...} groups have been typed manually, you can also end up with mismatched environments that are hard to find. The command M-x check-LaTeX-nesting scans the buffer to ensure the correctness of \begin{...} ... \end{...} nesting. If, for example, your buffer contains a nesting error like this \begin{verse} ... \begin{quote} ... \end{verse} ... \end{quote} the command will terminate with the cursor in front of the \end{verse} with the error message This \end{verse} is matched by preceding \begin{quote} at mark. The Emacs function exchange-point-and-mark on C-x C-x will move the cursor to the mismatching
1014 preliminary draft, 1 Apr 2002 7:30 TUGboat, Volume 0 (2001), No. 0
\begin{quote}. After fixing the error, you can re- run the nesting check by typing C-x ESCape (repeat- complex-command) until it finally reports
[done] -- all \begin{}-\end{}s balance. The command M-x indent-LaTeX-begin-end- groups indents \begin{...}... \end{...} groups according to their nesting level, which helps to make the input file more readable. You don’t need these commands very often, so they do not have default key bindings.
6.12 Word abbreviations
Emacs provides a convenient word abbreviation fa- cility that permits the automatic expansion of a string of letters when the following space or punctu- ation is typed. LaTeX-mode provides this by default with a set of abbreviations in a table that can be customized for personal use. You can find the complete set of abbrevia- tions by examining the value of the variable LaTeX- mode-abbrev-table, or by invoking the function list- abbrevs. You can make changes most easily with M-x edit-abbrevs. The commonest abbreviations recognized in LaTeX-mode are for macro names that are awkward to type: the input latex expands to \LaTeX{} , tex to \TeX{} , and so on. Note particularly that the expansion here is to \TeX{}, and not \TeX! There are good reasons for this:
The form {\TeX} has the almost same advan- tages over \TeX\ as \TeX{} does, but has one draw- back: if you need to \protect it, then you must do so inside the braces. Use of a final empty brace pair therefore seems the best choice. By Emacs convention, word abbreviation mode is never turned on automatically; you must explicitly toggle it on a case-by-case basis by executing the command M-x abbrev-mode. If you always want it selected in LaTeX-mode, add it to your .emacs file in a mode hook: (setq LaTeX-mode-hook ’(lambda () (abbrev-mode 1) ) ) If you have other things to set in that mode hook, they should go on the lines immediately before or after the (abbrev-mode 1) line, since there can be only one mode hook for each editing mode.
6.13 Bibliographies Literature citations are conveniently provided for on C-c c (LaTeX-cite), which generates a \cite{} com- mand with the cursor after the open brace. With an argument, it produces \cite[]{} instead, with the cursor between the square brackets. There is another function, LaTeX-bibitem, on C-c C-b, which generates a \bibitem{} for you; with an argument, it produces \bibitem[]{}. Normally, you should be using a program like BibTEX [15, Ap- pendix B] or Tib [1, 2] for preparation of bibliogra- phies from a data base and the citations recorded in the LATEX .aux file. If you find yourself using this command, you are doing the job the hard and inflexible way. LaTeX-mode automatically invokes the function update-LaTeX-bibtags to extract the list of bibliog- raphy files from the \bibdata command in the .aux file, or the \bibliography command in the LATEX file. Each such file is then located in the BIBIN- PUTS search path, and scanned to extract citation tags which are stored as an association list in the variable LaTeX-bibtags. Each list entry contains a citation tag and the name of the file in which the tag was found. If the BIBINPUTS environment variable is not set, then the Emacs variable LaTeX-BIBINPUTS is used instead to get a suitable search path. You can view the citation tag list by invoking the function show-LaTeX-bibtags. You can request completion on a citation tag in- side a \cite command by using the function LaTeX- bibtag-with-completion normally bound to C-c C.
1016 preliminary draft, 1 Apr 2002 7:30 TUGboat, Volume 0 (2001), No. 0
LaTeX-label-reference; it contains a regular expres- sion that normally matches both \pageref and \ref. If you have defined private macros that also receive labels as arguments, you may wish to extend it. For example, this document has \FIGREF and \PAGEREF macros that simplify cross-referencing. Similarly, these functions locate label defini- tions by searching for the string defined by the vari- able LaTeX-label-definition, another regular expres- sion that normally matches \label. You may wish to customize it if private macros also generate labels. Multi-file documents pose a challenge: labels defined in one file may be referenced in another file, and it would be helpful to be able to show a list of all currently-defined labels when one is needed for a cross-reference. It is not feasible for the code in latex.el to attempt to figure out what files are used for a par- ticular document, nor is it acceptable to ask the user to provide those file names. Yet we somehow need to scan those files to find all of the labels. The solution is that LATEX can do part of this job for us: LATEX processing of the master file pro- duces in the corresponding .aux file all defined la- bels embedded in \newlabel commands. The func- tion update-LaTeX-labels does the remainder of the job: it prompts for the name of the master .aux file, and then scans it to extract a list of labels from the \newlabel commands. This list is then appended to the current contents of the variable LaTeX-aux-file- label-tags. Augmentation, rather than replacement, permits selective construction of list subsets by mul- tiple invocations of update-LaTeX-labels on different files. check-LaTeX-labels includes the values from LaTeX-aux-file-label-tags in its list of defined labels. For convenience, whenever LaTeX-mode is run (normally when a file is first visited), it will search the buffer for the first TEX macro which is pre- ceded only by optional whitespace on its line. If that macro is \documentstyle, then the file must be the master file for the document, so LaTeX-aux- file-label-tags is set to nil, and update-LaTeX-labels is automatically called on the corresponding .aux file. This means that manual invocation of update- LaTeX-labels is needed only when you visit a sub-file without first visiting the master file. In recent versions of latex.el, the functions LaTeX-pageref and LaTeX-ref have been augmented by LaTeX-pageref-with-completion and LaTeX-ref- with-completion. The new functions are bound to C-c p and C-c r, replacing the bindings to the older functions. The new ones use an internal function to dynamically scan the buffer for \label{} def- initions, add the contents of LaTeX-aux-file-label-
tags to the labels collected, and construct a list that can be used for command completion. They then prompt for a label, and if you type a query, they will display the current list of labels. You can use completion to select any one of them, or you can en- ter an arbitrary label that is not in the completion list. Here is what the completion list looks like for this document: Possible completions are: X-command customizing-lists fig-bindings-1 fig-bindings- fig-latex-index fig-latex-mode- fig-latex-mode-2 fig-letter fig-startup-code gnu-emacs-size indexing latex-support mode-hook word-abbreviations Because the dynamic label scan that happens each time these functions are executed may be slow in large documents, the old functions remain avail- able for rebinding to keys. The Emacs variable LaTeX-label-start-with- newline can be set to a non-nil value if you prefer to have the inserted label entry start a new line. The variable LaTeX-label-end-with-newline can be set to a non-nil value to have a newline generated after the inserted label entry. The default for both is nil, so that no additional lines are generated.
6.16 French typography English typographical conventions for spacing around punctuation are at odds with good French typography. TEX’s \frenchspacing macro [14, p. 74] [15, p. 154] does not entirely satisfy French conventions: it only makes spaces after punctuation the same as interword spaces. In French typography, the punctuation charac- ters : ;?! are preceded by an unbreakable inter- word space (in TEX language, a tie). Em-dashes (—) are always surrounded by spaces; in English typog- raphy, such spacing is a matter of personal style. Quotations are made with guillemets as ^... , in- stead of as “... ”; the open guillemet is followed by a space, and the close one is preceded by a space. The GUTenberg organization has developed a standard TEX and LATEX style file, french.sty, to provide suitable definitions of the guillemets as the control sequences "< (or \flqq) and "> (or \frqq), as well as more convenient accent primitives. It is tedious to remember to type the TEX tie command everywhere that special French punctua- tion spacing is required, so the minor mode function French-LaTeX-mode is provided in latex.el. Each time it is invoked, it toggles between French and
TUGboat, Volume 0 (2001), No. 0 preliminary draft, 1 Apr 2002 7:30 1017
non-French conventions. It can be used in either TEX or LATEX files. When French mode is selected, the Emacs mode line contains the string French, and new functions LaTeX-French-colon, LaTeX-French- exclamation, LaTeX-French-langle, LaTeX-French- minus, LaTeX-French-query, LaTeX-French-rangle, and LaTeX-French-semicolon are bound to the ap- propriate keys. The quotation mark is rebound to self-insert-command so that the special handling nor- mally provided by LaTeX-quote (see Dots, com- mas, and quotation marks on page 1012) is sup- pressed. The French angle bracket functions insert an angle bracket, expand << to "<, and >> to ">, and then supply the necessary ties. Isolated an- gle brackets are inserted without further modifica- tion. Guillemets can thus be inserted either by typ- ing their named control sequences, or by "< or <<, and "> or >>. LaTeX-French-minus inserts a minus sign, and if it is the end of an em-dash, supplies surrounding spaces (not ties). While it would be possible to have TEX pro- vide for the French spacing requirements by suitable macro definitions of active characters, such redefini- tions risk interfering with other macros. It seems best to provide for the spacing requirements in the input file itself, letting Emacs remember the neces- sary rules. French mode can be customized by defining a suitable value of the French-LaTeX-mode-hook vari- able; see LATEX macros on page 1009.
6.17 Miscellaneous functions
LaTeX-counter on C-c k generates a counter name with completion, using the names stored in the vari- able LaTeX-standard-counters. LaTeX-footnote on C-c f generates a \footnote{}. Not only does this save typing, but it also prevents my fingers from producing \bootnote{}, which looks reasonable enough, but makes TEX unhappy. Non-nil values of the vari- ables LaTeX-footnote-end-with-newline and LaTeX- footnote-start-with-newline request that newlines be generated before and after the footnote; the default values are nil. LaTeX-news on C-c C-n views the latex.el file to show the revision history recorded in it. LaTeX-tab on C-c Tab indents to the current \begin{...}... \end{...} nesting level. LaTeX-protect on C-c C-p inserts a \protect macro at the current point. It is needed when- ever fragile commands (e.g. any LATEX command
that has a star form [15, p. 27]) are present in a moving argument [15, p. 151]. In particular, all macros in \index{} entries should be preceded by \protect. Otherwise, you can get long macro ex- pansions that cause buffer-overflow problems for in- dexing programs, and make the index file hard to read. Also, macro expansions can introduce special characters which cause problems for indexing pro- grams like makeindex. LaTeX-set-indentation on C-c , sets the current indentation column to the value of its argument, or to the cursor column if there is no argument. It is only rarely necessary to use this function, because the indentation is reset by several other functions. LaTeX-verb on C-c v generates a \verb|...| command with the cursor after the first vertical bar. With an argument, it creates the \verb*|...| form, which makes spaces visible. The delimiter character can be changed from a vertical bar by reassigning the Emacs variable LaTeX-verb-delimiter. For example, to set it to a plus sign instead of a vertical bar: (setq LaTeX-verb-delimiter ?+) The funny ?\ prefix is one of Lisp’s character quotes. As shown on page 1009, this assignment should nor- mally be placed inside a mode hook. It can also be executed dynamically inside the Emacs minibuffer. Alternatively, you can use M-x set-variable; it will prompt for the variable name and value. There are several other functions in latex.el that I shall not document here; they are intended for internal use only, and are subject to change without warning. They all begin with the reserved prefix internal-.
6.18 Miscellaneous variables There are a number of variables that we have not yet described. You should not have to modify any of them, but you occasionally might want to know what they are. LaTeX-current-indentation tracks the current environment indentation as the number of spaces from the left margin. It is updated dynamically by many functions. LaTeX-mode-map holds the map that asso- ciates keys with functions. LaTeX-mode-version is a string containing the version number and date of the last revision to the code. You should cite its value when reporting bugs; LaTeX-gripe puts it in the e-mail subject line. LaTeX-standard-environments contains the list of environment names used by LaTeX-begin-end- block.
TUGboat, Volume 0 (2001), No. 0 preliminary draft, 1 Apr 2002 7:30 1019
\onlyslides commands. The function renumber- slides on C-c 0 modifies relevant commands in the buffer to read something like this:
\begin{slide}{} % slide number 1 ... \begin{slide}{} % slide number 2 ... \begin{overlay}{red} % overlay number 2-a ... \begin{overlay}{green} % overlay number 2-b ... \begin{note} % note number 2- ... \begin{slide}{} % slide number 3 ... \begin{note} % note number 3- ... \begin{note} % note number 3-
Any existing comments on the commands are dis- carded. Notice the special handling accorded the SliTEX note and overlay environments; they re- ceive a major number equal to that of the closest preceding slide, followed by a hyphen and a minor number or letter [15, pp. 136–137]. The Emacs variable SLiTeX-begin-slide defines the regular expression used to find the start of the note, overlay, and slide environments.
8 Letter support
LATEX [15, pp. 66ff] provides a letter document style, but there is a fair amount of constant ‘boil- erplate’ that has to be typed each time you use it. This suggests that the best approach is to have pri- vate template files that already have a letter out- line in them, and then arrange to start each let- ter with a copy of the template already inserted into the buffer. Emacs’ programmability makes this straightforward. The startup file code in Figure 6 on page 1006 loads a small Lisp file, letter.el. It defines a letter-mode function, and associates it with files with extension .ltr. If I then visit a new file rb-jones.ltr, I immediately get the buffer shown in Figure 7, with the cursor positioned in the empty brace pair in \begin{letter}{}, ready for entry of the address. The query in \opening{Dear ?} is a reminder to enter something there, and then the body of the letter can be typed in following the \opening line. My personal style option nhfb-letter provides for a University and Department letterhead on the first page, and defines a few private macros that I often need in my correspondence.
% --LaTeX-- % Document name: /u/beebe/rb-jones.ltr % Creator: Nelson Beebe [[email protected]] % Creation Date: Mon Jul 29 20:06:18 1991
%--------------------------------------------- % EVERYTHING TO THE RIGHT OF A % IS A REMARK % TO YOU AND IS IGNORED BY LaTeX. % % WARNING! DO NOT TYPE ANY OF THE FOLLOWING % 10 CHARACTERS AS NORMAL TEXT CHARACTERS: % & $ # % _ { } ^ ~
% % The following seven are printed by typing a % backslash in front of them: % $ & # % _ { and }. %---------------------------------------------
\documentstyle[nhfb-letter]{letter} \begin{document} \begin{letter}{ 2 }
\opening{Dear ?}
\closing{Sincerely,} \ps{{$\cal NHFB$}/\LaTeX} \end{letter} \end{document}
Figure 7: Letter template.
Once the letter file has been saved, I suspend Emacs, or switch to another workstation window, and then process the letter by typing make LET=rb-jones The UNIX make utility is a wonderful tool; here it directs the execution of commands to expand tabs to blanks, changes the file protection to remove ac- cess to all but its owner, runs LATEX, and then runs a PostScript DVI driver, sending the output to a nearby printer. Then it sends the output PostScript through a shell filter that modifies the showpage command to print the string File Copy in outline letters diagonally across each page, and queues that to the printer as well. On those occasions where I require multiple copies of the original letter, I just type something like make LET=rb-jones C= This gives me one file copy, and three originals for signing and mailing. With this support, preparation of typeset let- ters is just as easy as typewritten ones, and the re- sult looks much better. And I can use mathematics and a variety of fonts too!
1020 preliminary draft, 1 Apr 2002 7:30 TUGboat, Volume 0 (2001), No. 0
9 Bug reporting
LaTeX-gripe on C-c g makes it easy to complain about LaTeX-mode; it puts you in an e-mail buffer with a mail header something like this:
To: [email protected] Subject: LaTeX-mode gripe report {beta test 0.23 [08-May-1991]}
The standardized subject field makes it easy for the author to identify such messages in his voluminous e-mail correspondence, and also automatically iden- tifies the code version. If you don’t have an electronic mail connection yet, you probably soon will. For now, just send me your comments in postal mail. Machine-readable submissions can be sent on IBM PC or Apple Mac- intosh floppy disks.
10 Conclusion
LaTeX-mode editing support in GNU Emacs pro- vides a very powerful, and pleasant, way to prepare LATEX and SliTEX input. The original TOPS-20 version written in TECO was begun in October 1984, and used extensively at Utah until our DEC-20/60 retired on October 31,
empty lines, and ignoring the initializations of large tables, the average is about 22 lines of code and doc- umentation per function. This is close to the 20-line average for all of GNU Emacs, computed from the statistics given earlier on page 1002. Documenta- tion contributions are included here because Emacs functions, and some variables, carry their own docu- mentation with them, even after compilation. That documentation is readily available for viewing in the editor. I believe that this code could serve as a model for other Emacs-like editors that have an exten- sion language in which new functions can be writ- ten. I had planned to write an EEL version for the epsilon editor on PC DOS, but alas, have not found the time to do so. This is not a small job, but it should be straightforward for someone famil- iar with both Lisp and EEL. The latex.el file is over 4200 lines long, with about 155KB of text; Emacs compiles it into about 100KB of byte codes. The latter figure should give some idea of the mem- ory requirements for implementations in other edi- tors. I hope some reader will prepare such a transla- tion and make it freely available, as latex.el is. A large portion of the TEX community uses personal computers that are inadequate for GNU Emacs, but have smaller Emacs-like editors available, and such editing support would be a great boon for them. If you plan to undertake such a translation ef- fort, check with the author of latex.el first to find out if anyone else is already working on one. Some other work in the TEX community for editing support has been reported in the TEX Users Group TEXniques series [17, 18, 22] and in TUGboat [8, 9, 10, 11, 12, 13, 23]. I believe that latex.el is much more powerful, however. Those who use UNIX workstations or VAX VMS systems where GNU Emacs is already available should eventually find latex.el in the emacs/lisp directory, and until then, can obtain it directly from the author, provided they have Internet electronic mail or ftp access. If you have a UNIX or VAX VMS system, but do not yet have GNU Emacs, you can get Emacs from any site that already has it, or better, you can get the latest version directly from the Free Soft- ware Foundation. The latter is accessible either via Internet anonymous ftp to the machine prep.ai. mit.edu, or through postal mail to Free Software Foundation, Inc. 675 Massachusetts Ave Cambridge, MA 02139 USA