Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Consider the common LaTeX way of defining environments, for example:

\begin{summary}
In olden times when wishing still helped one, there lived a
king whose daughters were all beautiful, but the youngest was 
so beautiful that the sun...
\end{summary}

Contrast this, with Knuth's way and ConTeXt which tend to omit the braces.

\summary
In olden times when wishing still helped one, there lived a
king whose daughters were all beautiful, but the youngest was 
so beautiful that the sun...
\endsummary

The latter is more readable in an editor and makes the life of the author easier. Personally I prefer the latter, and although one can argue about the advantages of the LaTeX way of having arguments and commands, I suggest that these styling commands do not belong in the text but in a setsummarystyle and should go in the preable, i.e, try and keep the text with structural commands only (no styling).

Have you got your own strategies to keep the text as clean and readable as possible? Any suggestions to alternatives and problem areas?

MWE example if you want to experiment.

\documentclass{book}
\usepackage[paperwidth=4.75in,paperheight=7.25in,
            textwidth=4.2in,textheight=6.5in,
            headsep=0.1in, footskip=0.15in,
            marginratio=1:1]{geometry}
\usepackage{lipsum}
\long\def\summary#1\endsummary{{%
 \baselineskip11pt
 \leftskip3em\rightskip3em
 \noindent
 {\bf Summary}.\quad#1
 \bigskip
\par}}%

\begin{document}
\chapter*{Introduction}

\summary
 In olden times when wishing still helped one, there lived a
king whose daughters were all beautiful, but the youngest was 
so beautiful that the sun itself, which has seen so much, was
astonished whenever it shone in her face. Close by the king's
castle lay a great dark forest, and under an old lime-tree in the
forest was a well, and when the day was very warm, the
king's child went out into the forest and sat down by the side
of the cool fountain, and \ldots
\endsummary

\lipsum[1]
\end{document}
share|improve this question
    
As you are asking for multiple answers this probably should become CW? –  Daniel Oct 30 '11 at 21:17
2  
@Daniel Btw. the intention of CW has changed a bit. –  Stefan Kottwitz Oct 30 '11 at 21:32
    
The example code reads in the whole paragraph as an argument; I find this suboptimal. –  Andrey Vihrov Oct 30 '11 at 21:53
    
@AndreyVihrov A lot of times it has the advantage that you can box the argument and do all sorts of things with it. It is a quick and dirty way to provide an example and it takes one millionth of a second longer to process. –  Yiannis Lazarides Oct 30 '11 at 21:59
1  
@YiannisLazarides \def\document#1\enddocument{...} :) –  egreg Oct 30 '11 at 23:22
show 4 more comments

5 Answers

up vote 22 down vote accepted

I like more the LaTeX way of marking environments, because it provides a neat distinction between environments and commands: when something goes wrong I can always search for \begin or \end. The ConTeXt way is not more readable, in my opinion.

In general I never indent the contents of environments: I find that distracting and a waste of space on the screen. A good syntax highlighter is sufficient to find visual clues. But I always put \begin and \end commands on a new line in the document and use at least two blank lines before sectioning commands. And my editor highlights \begin and \end differently than normal commands. This can't be done with \summary-\endsummary pairs, unless you teach the editor all such pairs.

I always try to properly indent macro definitions, as Didier Verna seems to recommend, especially when \if... are involved. Of course

\newcommand{\macro}{\@ifstar{\@macros}{\@macro}}

won't receive the "proper" treatment

\newcommand{\macro}{%
  \@ifstar
    {\@smacro}
    {\@macro}%
 }

but more complicated things will.

As an aside, I find also that \def\summary#1\endsummary{...} is not a good way to define your environment:

\def\summary{%
\baselineskip11pt
\leftskip3em\rightskip3em
\noindent
\textbf{Summary.}\quad}
\def\endsummary{\bigskip\par}

would be much better as it doesn't have to read all the argument just to reread it again for typesetting, but I understand it's just an example.

If you prefer this way of doing, then

\newcommand{\newTeXenvironment}[1]{%
  \expandafter\def\csname #1\endcsname{\begin{#1+}}%
  \expandafter\def\csname stop#1\endcsname{\end{#1+}}%
  \newenvironment{#1+}}

\newTeXenvironment{summary}
  {\baselineskip16pt
    \leftskip3em\rightskip3em
    \noindent
    \textbf{Summary.}\quad}
   {\bigskip\par}

will allow you to say

\summary
<text of the summary>
\stopsummary

in pure ConTeXt style. Well, kind of.

share|improve this answer
2  
Regarding Context: The macros bounding environment always begin with \start or \stop, and the usual editors (e.g., Auctex/Emacs) do highlight these macros correctly. –  Charles Stewart Oct 31 '11 at 13:55
    
@CharlesStewart Nice to know! –  egreg Oct 31 '11 at 14:31
add comment

Didier Verna mentioned good practices in his talk Toward LaTeX coding standards at TUG 2011:

  • Use indentation for readability: indent the content of the environment, and indent the closing command at the same level as the opening command (even in the rare case, when the corresponding closing command appears in a second macro)

  • Use the @ convention, but wisely: it can be used in internal command names, but should not be overused. For example, consistently starting your internal style macros by \@ is ok, but \intr@ducti@nis bad

  • Choose names which cannot cause name conflicts:

    • You could consistently use a prefix, such as your style file name
    • In cases where LaTeX adds a prefix, such as \c@<counter>, consider using a postfix
    • Avoid common names, which might already be used by classes or packages, so natural names are sometimes not the best choice, even if readable.

And with LaTeX, I would use \newcommand or \newenvironment instead of \def to be able to notice when a conflict occurs - or check yourself for existence of a command name before defining it.

share|improve this answer
    
@Stephan Kottwitz Thanks, I am looking more for the commands exposed to the user i.e., the author rather than the package or class writer, although this is also relevant to an extent. Is there a more detailed preprint for the talk you linked to? –  Yiannis Lazarides Oct 30 '11 at 21:30
    
@YiannisLazarides Soon you will be able to see the talk on video on river-valley.tv. Perhaps the paper will appear in the TUGboat TUG 2011 proceedings. –  Stefan Kottwitz Oct 30 '11 at 21:35
    
Stephan I particularly used \def to enable use for it both for TeX as well as LaTeX. You wouldn't also be able to define the structure I have used with newcommand, you would need newenvironment. –  Yiannis Lazarides Oct 30 '11 at 21:51
    
@YiannisLazarides: regardig the 3rd point: \summary is defined for example in ieeepes.sty, sdrt.sty and gatech-thesis.cls. That's what I mean with the recommendation for avoiding name clashes. –  Stefan Kottwitz Oct 30 '11 at 21:53
    
Stephan Agreed that one needs to check if the macro name has been defined, which I omitted for brevity in my example, normally I would either check with one of the defined or undefined conditionals or use newcommand. For document structural commands, such as chapter, section and I believe summary or abstract would qualify for this, one has to override previously defined commands (we doing this all the time) rather than burden the user with another set of command names. I used to distinguish via capitalization, i.e, chapter into Chapter but lately I would rather carefully override. –  Yiannis Lazarides Oct 31 '11 at 18:57
show 1 more comment

I disagree with the assertion that \summary...\endsummary is more readable or "cleaner" than \begin{summary}...\end{summary}. The problem is that it does not clearly indicate the intent of \summary: it could mean "begin summary", as it does, or it could mean "emit a previously saved summary", as in \tableofcontents. Even if it means "begin summary", it could mean that the summary follows until the next newline, like Knuth's \proclaim, which reads to \par (not obviously the terminating entity based on the command words!). Basically, plain macros can create the functionality of an environment without communicating the appearance of one to the user.

A more subtle advantage to \begin...\end is that they are enforcement mechanisms. With \summary...\endsummary, one can capriciously change the definitions so that, say, \summary now does read just to the end of the line and \endsummary means \relax. Since it doesn't look like an environment, there is nothing preventing the author from breaking the contract to make it act like one. But with \begin...\end, the environment behavior is imposed by LaTeX itself: even if you do something absurd with \summary itself (which is called internally by \begin{summary}) you will still get the grouping, which prevents your whimsies from damaging the rest of the document. The macro \@currenv (I think) is set, and LaTeX therefore checks for the end of the environment, not something you are guaranteed depending on how you might define your \summary...\endsummary pair by hand.

A final benefit, though not one that is actually realized in practice, is that in theory, having named environments rather than macro pairs means that you have the option to provide uniform styling to your environments. If \begin and \end had hooks, you could use them to insert common code into every environment. For example, you could cause the contents of every environment to be indented, or to have its words counted, and so on. Try that with \summary!

To answer your boldfaced question in more generality, I do in fact have a strategy for keeping my "code" clean in TeX: don't program in TeX! It is now obsolete as a programming language: most control-flow logic can be implemented far more understandably by pgfkeys than by screwing with TeX's crazy expansion semantics. (See my favorite answer.) This means:

  • Keys in pgfkeys do not have name conflicts because of the key tree: you create a directory for your keys, and no one else uses the same namespace. The slashes are more readable than @'s and don't require catcode hacking, yet are still secure.

  • When defining macros with options, use pgfkeys to give them key-value semantics rather than letting your macro take four arguments, of which the second and fourth are optional, and mean similar things, but are not interchangeable (cough \newtheorem).

  • When processing your options, use pgfkeys to do all the decision-making. It doesn't just set booleans; it also executes arbitrary commands, jumps to any other key according to various default handlers, expands (without TeX's complications) to any list of secondary keys, and its keys themselves can behave as TeX macros taking one or two arguments, meaning that the only time you need to "drop out" of the processing is when you return control to the input file itself.

  • It is true that you can't do pattern matching without using \def. However, using pattern matching in macros is evil, and the reason that LaTeX disallows it in \newcommand (as I see it) is that you don't need to do it. Pattern matching means that you have to write your document to look a certain way even if it doesn't appear that you are giving a command. One possible use for it is to write a parser if it strikes your fancy to create a descriptive language like some of TikZ's commands (\path (0,1) node (name) to (3,3) circle;, for example). To my knowledge, TikZ does not do it like this, but you could use pgfkeys to process all the keywords and have a simple collection of "grabber" macros, i.e. \def\getpoint(#1,#2){...}, \def\getword#1 {...}, and of course \ignorespaces is a useful primitive. This cuts down on having to reinvent the wheel when you define your syntax: just make each keyword have a certain behavior as a pgfkeys key that enforces its behavior in your language.

Somehow I think that's not what you were asking. However, I think it definitely answers "how to write readable commands". Use pgfkeys.

share|improve this answer
add comment

I think you are confusing the ConTeXt style with the Knuth style. The ConTeXt style is to use \start<whatever> and \stop<whatever>, as opposed to the Knuth style of \<whatever> and \end<whatever>. And, something that is perhaps not that well known, in ConTeXt \start[<whatever>]... \stop[<whatever] gets mapped to \start<whatever>... \stop<whatever> (similar to \begin{<whatever>} and \end{<whatever} getting mapped to \<whatever> and \end<whatever> in LaTeX).

But when it comes to readability of macros, I find the ConTeXt way of defining macros to be much more readable that LaTeX's. For example, this is how I will define the summary environment in ConTeXt:

\definenarrower 
  [summarynarrower] 
  [left=3em, 
   right=3em, 
   after={\blank[big]\endgraf}, 
  ] 

\defineenumeration 
  [summary] 
  [before={\startsummarynarrower[middle]}, 
   after=\stopsummarynarrower, 
   headstyle=bold, 
   width=fit, 
   distance=1em, 
   text={Summary}, 
   number=no, 
   location=serried, 
   style={\setupinterlinespace[11pt]}, 
  ] 

Except for location=serried, you can read the rest of the definition and understand what it does even if you have no experience in defining ConTeXt macros. That is, you can read a macro written by someone else (or by a younger you!) and understand what it does. That is much more important that the difference between \begin{...} and \start.....

This definition may then be used as:

\starttext                                                                                                                             
\startsummary
  In olden times when wishing still helped one, there lived a
  king whose daughters were all beautiful, but the youngest was 
  so beautiful that the sun itself, which has seen so much, was
  astonished whenever it shone in her face. Close by the king's
  castle lay a great dark forest, and under an old lime-tree in the
  forest was a well, and when the day was very warm, the
  king's child went out into the forest and sat down by the side
  of the cool fountain, and \unknown
\stopsummary
\stoptext

or if you prefer the LaTeX style:

\starttext                                                                                                                             
\start[summary]
  In olden times when wishing still helped one, there lived a
  king whose daughters were all beautiful, but the youngest was 
  so beautiful that the sun itself, which has seen so much, was
  astonished whenever it shone in her face. Close by the king's
  castle lay a great dark forest, and under an old lime-tree in the
  forest was a well, and when the day was very warm, the
  king's child went out into the forest and sat down by the side
  of the cool fountain, and \unknown
\stop[summary]
\stoptext

In principle, a similar key-value interface is possible in LaTeX; in fact, some LaTeX packages like TikZ already provide such an interface, and, IIUC, having such a key-value driven interface is one of the objectives of LaTeX3. But I find the ConTeXt interface to be much more consistent.

EDIT Some other ConTeXt specific ideas for maintaining code readability

  • Use \start<...> and \stop<...> version of \section and \enumeration commands and indent all environments.

    ConTeXt allows you to use

    \startchapter[title=,label=...,ref=...,mark=...]
      ....
    \stopchapter
    

    instead of the traditional \chapter commands. The same is also true for commands defined using \defineneumeration and \definedescription. If you always use the \start... \stop... version of the block level commands, and indent each nested level by 2 or 4 spaces, the source code is much easier to use

  • Use empty lines after environments In plain TeX and LaTeX, an empty line means an end of paragraph. Strictly speaking, this is not true in ConTeXt. Whether the \stop... ends a paragraph or not depends on the setting of the indentnext key. Thus, if you set \setupformulas[indentnext=yes] or \setupformulas[indentnext=no], then

    some text      
    \startformula
      ....
    \stopformula
    some text
    

    and

    some text
    
    \startformula
      ....
    \stopformula
    
    some text
    

    are equivalent. Almost all block environments in ConTeXt accept indentnext key. I personally prefer the latter version because it is easy to determine the end of a block when visually scanning the source code. (If you really want the plain TeX type of behaviour of empty line determining the end of paragraph, then use indentnext=auto).

  • Use full names when defining environments and macros: Try no to add extra cognitive load on the reader (i.e. you!) by using macro names like \infty instead of \infinity and multline instead of multiline. The slightly shorter macro names may speed up the tex processing, but it considerably slows down the reader and writer as well.

share|improve this answer
    
Thanks for clarifying some of the concepts of ConTeXt. I could not agree more with you on your last item to use full names when defining environments and macros. –  Yiannis Lazarides Oct 31 '11 at 19:00
    
I like your last point. multline gets me every time; I can never load the fancyhdr package either, and it's fortunate that I have already buried fncylab inside one of my other macro files. \infty is okay, but probably only because \infinity is so large. I very much doubt they speed up anything, but they probably reflect a superstition about eight-character identifiers. –  Ryan Reich Nov 1 '11 at 15:39
    
@Ryan: IIUC, smaller macro names take less space to store and retrieve (remember that TeX was written in the 70s), but I doubt if the difference is measurable in today's computers. I also think that most people type fast enough that there is not much difference in typing a five letter word vs a eight letter word...the minor saving in typing speed are lost in the time needed to develop the muscle memory to type these shorter abbreviations (and leads to a larger learning curve for TeX). –  Aditya Nov 1 '11 at 16:44
add comment

If I have to pick a single thing that improved the readability of my latex documents recently, it is the use of unicode. Consider the following sentence (sorry, German)

Der Strom $I$ und der magnetische Fluss $Φ$ können über die Induktivität $L=Φ/I$ verknüpft werden.

It is clear even in the latex source.

It started when I got upset with the 'post-processing' of auto-generated .bib files. I had the following publication (Rutherford, 1911) with

The Scattering of α and β Particles by Matter and the Structure of the Atom

in the title field. Now, I can directly use the generated file without the need of a modified filter.

All these little things sum up.

share|improve this answer
    
Thanks this is a very good tip. –  Yiannis Lazarides Oct 31 '11 at 7:47
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.