Stage 1 · Foundations 8 / 48 ≈ 16 min read

How LaTeX Reads Your Source: Comments, Spaces, Line Breaks

Almost every mysterious LaTeX bug is a whitespace bug: a percent sign that ate the next line, a blank line inside a command argument, a source line break that silently split a word. This page explains the small set of reading rules behind them — category codes, token boundaries, the end-of-line and the paragraph — and turns them into habits that make a source file readable by other people.

    TeX reads tokens, not characters

    Before anything is typeset, the input reader turns your file into tokens, and it does so by giving every character a category code. The ones that matter in daily use: \ is the escape character, { and } open and close groups, $ switches to maths, & is the alignment tab, # introduces a macro parameter, letters are letters, spaces are space tokens, and % is a comment. Everything else — underscore, caret, tilde, hash, a digit, a full stop — is an "other" character.

    That table explains the single most useful rule in the whole language: a control word is a backslash followed by letters, and it ends at the first non-letter. \alpha is one token; \alpha1 is \alpha followed by 1. If the terminating character is a space, that space is consumed as the terminator and does not become a space in your text. So \alpha \beta, \alpha\beta and \alpha \beta are all exactly two tokens, and this is why the space after a command name never shows up in the output.

    The corollary is where people lose an afternoon. \alph ab is not \alpha and b; it is the undefined control word \alph followed by ab. And \LaTeX is great works only because the space terminates \LaTeX — but it also eats the space, which is why \LaTeX\ is great or \LaTeX{} is great is the correct form. The empty group {} is the standard way to say "command over, and here is some text".

    Category codes are why @ cannot appear in your macro names while it appears freely inside the kernel: \@startsection and \new@ifnextchar are legal only because a class file is read with @ promoted to a letter. The two commands that flip it are \makeatletter and \makeatother, and any style file you write that pokes at internals needs them around it.

    How one stretch of LaTeX source becomes tokens: discarded leading spaces, comment truncation, the absorbed space after a control word, and a blank line as a paragraph token the source, with every space written as · and the comment in red ····The·ratio·$\rho$·is·about·0.7·%·this·note·never·reaches·the·page ····and·it·glues·onto·the·next·line·with·no·space·at·all ····\alpha\beta·\alpha \beta·but·never·\alph ab ↑ % ends the line here the input reader the token stream that reaches the typesetter The ␣ ratio ␣ $␣\rho␣$ ␣ is ␣ about ␣ 0.7 ␣ nothing comment + its newline are both discarded and the three rules that produced it 1 · runs of spaces collapse four spaces or forty give one ␣, and spaces at the start of a line are dropped outright — so source indentation is always free …and it is why \hspace{1em} at a line start needs the starred form 2 · a control word ends at a non-letter, and eats one space \alpha\beta → \alpha \beta \alpha \beta → \alpha \beta same \alph ab → \alph + "ab" undefined: the space only terminated a name that was already complete 3 · end of line = ␣, blank line = ¶ line A line B → "A ␣ B" line A (blank) line B → "A ¶ B" ␣ = space token ¶ = \par
    One input line, its token stream, and the three reading rules that produced it: comment truncation, discarded leading spaces, and end-of-line as a space.

    What a percent sign really swallows

    % means: ignore the rest of this line and the line break itself. That second half is the part people miss. A normal end of line becomes a space token; an end of line that follows a % disappears completely. So a % at the end of a line does not just comment text, it also removes the space that the newline would have inserted.

    This is why a % hangs off the end of almost every multi-line macro definition: without it, each line break inside the replacement text contributes a space token, and the command produces a gap in the middle of your sentence that you cannot see in the source. It is also why % is used to "glue" the two halves of a title block back together. Once you know to look for it, a mysterious extra space in the output is usually a missing % rather than a broken package.

    It is also the cause of a subtle class of bugs: a commented-out }, or a commented-out \end{itemize}, leaves the opening half unpaired, and LaTeX reports a runaway argument somewhere far away. If you comment out one half of a pair, comment out both.

    To get a literal percent sign, escape it: 50\%. Inside \verb|%|, inside \begin{verbatim}, and inside a listings block, % is just a character — and there the backslash is literal too, so \verb|\%| prints a backslash and a percent. In a .bib file there is no comment character at all, because BibTeX is a different language with its own reader.

    The kernel makes one exception worth knowing: the document-environment scan still looks for \end{document} inside comments. Comment out the last line of a file and the document can still end there, which surprises exactly one person per project per year.

    Commenting out a block without deleting it

    Four ways, with different trade-offs. One % per line is universal and free; every editor can do it to a selection (Ctrl+ and Ctrl- in TeXstudio, Ctrl-/ in VS Code), and it survives being pasted anywhere. \iffalse ... \fi needs one line at each end and works without any package, but it does not make the contents inert: TeX still has to find the matching \fi, so skipped text containing an unbalanced \if, a { or a stray $ will still break the run.

    The comment environment comes from the verbatim package: \begin{comment} ... \end{comment}, and inside it every character is literal, which means it can hold code samples, maths and percent signs. Its limits are real, though: it cannot nest, it cannot appear inside another command's argument, and the closing \end{comment} must start a line on its own. If you want nesting, there is a package literally called comment that provides it, and luacomment if you compile with LuaLaTeX.

    Your own named environment is the option that scales to a project, and it takes one line: \excludecomment{discussion} in the preamble creates a discussion environment whose contents are read and dropped, and \includecomment{discussion} turns the same blocks back on. Then "hide all the author discussions" and "show them again" are both a one-word edit rather than a search-and-replace across forty files, which is the difference between annotations you actually use and annotations you delete before submission.

    For review notes with a paper trail, use the purpose-built tools rather than comments: the changes package records \added{}, \replaced{new}{old} and \todo{} in the margin or inline and can emit a change list at the end; todonotes gives \todo{} balloons in the margin plus a \listoftodos summary. Both are designed to be switched off with a class option for the version you send out.

    \documentclass[11pt,a4paper]{article}
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage{verbatim}   % the comment environment, plus \excludecomment
    \usepackage[colorinlistoftodos,prependcaption,textsize=tiny]{todonotes}
    
    % One line creates a private environment for author discussion.
    % \includecomment{discussion}  brings every block back;
    % \excludecomment{discussion}  -- the default here -- deletes them.
    \excludecomment{discussion}
    
    \title{Comment and note machinery}
    \author{A. Student}
    \date{}
    
    \begin{document}
    \maketitle
    
    \section{Working notes}
    The figure in this section needs a second panel.
    \todo{add panel (b), then re-number the reference}
    Somebody should check the constant in equation~\eqref{eq:k}.
    
    \begin{discussion}
      B: the constant came from the 2019 appendix, not the paper.
      A: then cite the appendix, and note that \% is just a character
      in here -- braces, maths and ampersands are all ignored too.
    \end{discussion}
    
    \begin{equation}
      \label{eq:k}
      K = \tfrac{1}{2}mv^{2}
    \end{equation}
    
    \listoftodos   % a one-page summary of what is left, for your own copy
    
    \end{document}

    Spaces: the rules that never vary

    Five rules cover ordinary text. Any number of consecutive spaces produce one space. A line break produces one space. Leading spaces at the start of a line are discarded, which is why you can indent source freely. A blank line produces a \par, ending the paragraph; two or five blank lines produce exactly the same thing as one. And a space is not inserted where a control word ended, because it was used up as its terminator.

    When you need a space that behaves differently, there is a command for each case. \ (backslash-space) is an ordinary space that cannot be absorbed — Mr\ Smith needs it, because Mr\Smith would be read as the undefined \Smith. ~ is a non-breaking space: Section~\ref{sec:a} and 10~kg can never be split across a line, and skipping it is why you sometimes see "10" at the end of one line and "kg" at the start of the next. \hspace{1em} is an explicit space that can be broken at, and \hspace*{1em} is the variant that survives at the beginning of a line.

    The last of those two has a genuine trap in it: ordinary glue at a line start is thrown away by the line breaker, so \hspace{2em} at the beginning of a paragraph does nothing while \hspace*{2em} indents it. This is the whole difference between the starred and unstarred form of many spacing commands, and it is the reason \noindent and a manual \hspace are not interchangeable.

    Thin, medium and thick spaces — \,, \:, \; — belong to maths mode, where they are the correct way to write \,dx or separate the arguments of a function. Outside maths they are at best meaningless and at worst the cause of a Missing { inserted error, so reach for \quad or \hspace{...} in text.

    \int_{0}^{1} x^{2}\,dx = \frac{1}{3}
    \int_{0}^{1} x^{2}\,dx = \frac{1}{3}
    The two blocks above come from different source lines — the second has extra spaces in places the first does not — and they are byte-for-byte identical on the page. In maths mode, whitespace in the source is free.
    \int_{0}^{1} x^{2} \, dx = \frac{1}{3}
    \int_{0}^{1} x^{2} \, dx = \frac{1}{3}

    Line breaks in the source versus line breaks on the page

    Because an end of line is a space, the position of your line breaks is invisible in the output as long as you break between words. This is what makes the source layout a matter of taste and collaboration policy rather than typography, and it is why one-sentence-per-line source compiles to exactly the same page as a single 900-character line.

    It stops being invisible in two situations, and both are common. Break inside a word and the break becomes a real space in the middle of it: typeset\nting prints "typeset ting". And put a space where the syntax needs none, next to a % or inside \verb| |, and the space becomes content.

    To actually break a line on the page, the tools are different and have different meanings. \\ ends the current line inside the same paragraph — correct in tabular rows, in aligned, in center blocks, and after a \par-less forced break; \newline does the same and is sometimes better behaved inside a command argument. \par or a blank line ends the paragraph, which means indent, spacing and a new first line for the breaker to optimise. They are not interchangeable: \\ between two paragraphs is the classic beginner layout, and it produces a line with no paragraph indent and no inter-paragraph space, which looks like a bug in the class rather than a bug in the source.

    Never use \\ to create vertical space. It leaves a short line in the middle of a paragraph, and the page breaker has to work around it. The correct tools are a real paragraph break, a list, or — for the rare case where a title page really needs it — a \vspace that you can point at and defend.

    Four source layouts and the four different things they produce on the page what you type in the file what appears on the page Alpha Beta ↵ ↵ two source lines, no blank line Alpha Beta one paragraph · the break became a space Alpha Beta ↵ ↵ (a blank line) the only thing that means "new paragraph" Alpha Beta two paragraphs, each indented, grid spaced by the class Alpha\\ Beta a forced line break, no ¶ token Alpha Beta same paragraph: no indent, no inter-paragraph space ...the argument is typeset-ting correctly wrapped inside a word the argument is typeset ting correctly the newline became a real space and split the word The one sentence to remember A line break is a space. A blank line is a paragraph. A double backslash is a line with no paragraph meaning — for the text, for a tabular row, or for the next line of an aligned derivation.
    Four source layouts, three different results: the break is a space, the blank line is a paragraph, and the double backslash is a line with no paragraph semantics.

    Whitespace inside maths, where it is completely free

    In maths mode, spaces are ignored entirely — not collapsed, ignored. \int_{0}^{1}x^{2}dx and \int _ { 0 } ^ { 1 } x ^ { 2 } d x produce the same box. The only exceptions are the spaces that terminate a control word and the explicit space commands \,, \:, \;, \quad and \!, which are real objects in the formula, not formatting.

    This is the reason complex maths is readable at all. You can put every & of an aligned block in one column, give each row its own line, and indent a derivation the way you would indent code, and none of it leaks into the output. Compare the two listings on this page: the maths is identical, and one of them is reviewable.

    Two things in maths are not whitespace and will bite you. A blank line inside a display is a \par token where a formula was expected, and the message you get is usually about a missing $ rather than about the blank line, so it looks unrelated to what you did. And \\ inside aligned, cases, matrix or tabular is the row terminator, not a space — a missing one is reported as a misplaced alignment tab on the following line.

    One more convention worth adopting: write x^{12}, never x^12. A superscript attaches to a single token, so x^12 means x to the power 1 followed by an unrelated 2, and the output looks almost right — which is the worst kind of error to have in a document nobody proofreads character by character. The same applies to a_{ij} versus a_ij.

    \begin{cases} 2x + y = 7 & \text{row one} \\ x - 3y = -1 & \text{row two} \end{cases}
    \begin{cases} 2x + y = 7 & \text{row one} \\ x - 3y = -1 & \text{row two} \end{cases}

    Habits that make a source file readable

    Treat the source as a document other people read. Indent freely, because leading spaces are discarded: indent the contents of every environment one space, and a mismatched \end{} becomes obvious by eye instead of by log file. Keep one paragraph per editing unit, or one sentence per line if the file is collaborative. Break long arguments onto separate lines — \usepackage options, \begin{tabular}{...} preambles and hyperref colour lists all read better split, and it is legal for everything except a control word's name.

    Use banner comments so that scrolling has landmarks: % ---- Preamble: fonts ------------------------------------ costs nothing and is findable with a search. Put a marker in front of anything unresolved — % TODO:, % FIXME:, % DRAFT-ONLY: — because a project you grep is a project you can finish, and grep -rn "TODO" *.tex is the honest status report of a manuscript.

    Keep whitespace behaviour out of your editor's way and write it down once. An .editorconfig file in the repository root sets UTF-8, LF line endings and a final newline for everyone at once. The one LaTeX-specific setting is trailing-whitespace trimming: inside verbatim, lstlisting or a \verb|...| span, a trailing space is data, and an editor that deletes it has quietly changed your quoted program output. Both line-ending styles typeset identically — the engine does not care — but mixed endings make every diff look like a rewrite, which is a version-control problem with a one-line fix.

    Finally: if a page looks wrong and the source looks right, suspect the reader before the writer. Blank lines, % signs and the space after a command name account for a large share of "LaTeX is ignoring me" reports, and all three are now things you can check in about ten seconds.

    # .editorconfig -- the whitespace rules a LaTeX project should agree on.
    # Every serious editor reads this file; git reads nothing here, so it is
    # the cheapest way to make five people's editors behave like one.
    root = true
    
    [*]
    charset = utf-8
    end_of_line = lf
    insert_final_newline = true
    indent_style = space
    indent_size = 2
    trim_trailing_whitespace = true
    
    [*.tex]
    # Inside \begin{verbatim}, lstlisting and \verb|...| a trailing space is
    # DATA, not layout: trimming it silently alters the code you are quoting.
    # Turn trimming off for prose files that quote program output.
    trim_trailing_whitespace = false
    
    [*.bib]
    trim_trailing_whitespace = true
    max_line_length = off
    
    [*.{png,jpg,pdf}]
    insert_final_newline = false
    trim_trailing_whitespace = false

    Lesson cheat sheet

    One key line of code from each section — jump to it or copy it straight from here.

    Section Key code
    \documentclass[11pt,a4paper]{article}
    \int_{0}^{1} x^{2}\,dx = \frac{1}{3}
    \begin{cases} 2x + y = 7 & \text{row one} \\ x - 3y = -1 & \text{row two} \end{cases}
    # .editorconfig -- the whitespace rules a LaTeX project should agree on.

    Common mistakes

    • Typing 50% in text: the rest of the line vanishes from the PDF with no error at all. Write 50\%.
    • Commenting out \end{itemize} or a closing } and then debugging a Runaway argument forty lines later.
    • Chaining sentences with \\ between them because you want them on separate lines: that is a forced line break inside one paragraph, not a paragraph. Use a blank line.
    • Wrapping a long source line in the middle of a word. The newline becomes a space and the page shows the word split in two.
    • Expecting source indentation to indent the output. Leading spaces are discarded; indentation is a \parindent and \noindent affair.
    • Putting a blank line inside \section{...}, a macro argument or a display equation, and getting an error message that names neither the blank line nor the command.
    • Using \alph ab for \alpha b, or \LaTeX is when you meant \LaTeX{} is — a control word ends at the first non-letter and eats a single space doing it.
    • Relying on \iffalse to comment a block containing unbalanced braces or maths, then getting a scanner error from text you believed was switched off.

    Questions about this lesson

    How do I comment out multiple lines in LaTeX?
    Put a % at the start of each line — every editor does it for a selection. For a large block use the comment environment from the verbatim package, or wrap it in \iffalse ... \fi. The comment environment accepts anything, but it cannot be nested and cannot sit inside another command's argument.
    Does a new line in the LaTeX source start a new line in the document?
    No. An end-of-line character is read as a space, so breaking a paragraph anywhere between words does not change the page at all. Only a blank line ends a paragraph, and only an explicit double backslash forces a line break without ending it.
    How do I type a percent sign in LaTeX?
    Escape it as \%. Inside a verbatim or listings block, or between the delimiters of \verb, the percent sign is already literal and must not be escaped, because backslashes there are printed as typed.
    Why did LaTeX ignore the spaces I typed?
    Because any run of spaces collapses to one, and a space that follows a command name is used up ending that name instead of printing. To keep a space use \ (backslash-space), use ~ when it must not break, and in maths use an explicit spacing command such as \, or \quad.
    What is the difference between a blank line and \par?
    None in effect: a blank line is read as a \par token, which is what closes a paragraph. Both start a new paragraph with indentation and inter-paragraph spacing. A double backslash instead gives you a new line inside the same paragraph, with no indent and no extra space.
    Why is there a % at the end of every line in this macro definition?
    To stop the newline inserting a space. Without the trailing %, each line break inside the definition contributes a space token to the replacement text, which shows up as an unexpected gap in the output. The % swallows the newline and keeps the definition tidy.

    Live playground: edit the LaTeX, see it render

    The preview updates as you type — break it on purpose to see how errors look.

    KaTeX error
    Try an example

    Keep reading

    Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.