4

I would like to redefine the \section macro in my document and I found that LaTeX3e was one of the easiest way to make integer operations inside it. But I get a "Missing $ inserted" error when I compile. A minimal example is the following :

\documentclass{article}
\usepackage{expl3}

\ExplSyntaxOn
    \int_zero_new:N \g_int
\ExplSyntaxOff

\newcommand\fooinc{
    \ExplSyntaxOn
        \int_incr:N \g_int
    \ExplSyntaxOff
}

\begin{document}
    \fooinc
\end{document}

Why doesn't the above code work ?

3
  • The \ExplSyntaxOn and \ExplSyntaxOff markers should go around the definition, not inside it.
    – egreg
    Jul 8, 2016 at 12:57
  • I thought it only made _ and : letters. If you turn your comment into a more detailed answer (why wouldn't it work), I will accept it.
    – fyusuf-a
    Jul 8, 2016 at 12:58
  • Analogous with \makeatletter here.
    – Manuel
    Jul 8, 2016 at 13:22

1 Answer 1

3

You should read What do ExplSyntaxOn and ExplSyntaxOff do? and its sibling What do \makeatletter and \makeatother do?

When TeX reads a definition, it just stores the tokens it is given, without doing any assignment. In particular, \ExplSyntaxOn in your definition is not performed and so \fooinc is defined to expand to the following tokens (I use • as token separator, for better reading):

\ExplSyntaxOn•\int•_•i•n•c•r•:•N• •\g•_•i•n•t• •\ExplSyntaxOff

so the macro \ExplSyntaxOn will be executed too late.

The correct way is

\ExplSyntaxOn
\int_zero_new:N \g_florian_whatever_int

\cs_new_protected:Npn \fooinc
 {
  \int_gincr:N \g_florian_whatever_int
 }
\ExplSyntaxOff

You have declared your integer parameter as global, so it should always be managed with global assignments. And \g_int is a badly chosen name.

Instead of \newcommand, it's better to use \cs_new_protected:Npn, if not \NewDocumentCommand of xparse (probably even a better choice).

4
  • I would like to use large portions of text inside my macros, is there a way not to replace all the spaces with ~ ?
    – fyusuf-a
    Jul 10, 2016 at 12:07
  • @Florian Not sure what you mean.
    – egreg
    Jul 10, 2016 at 12:12
  • If I put \ExplSyntaxOn and \ExplSyntaxOff around my macro, then spaces inside it are ignored. But I would like to put a large portion of text with spaces inside it. Is there a way to write them normally (" " instead of "~") to ensure legebility ?
    – fyusuf-a
    Jul 10, 2016 at 12:19
  • @Florian There are several ways. An example in a new question would be better.
    – egreg
    Jul 10, 2016 at 12:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .