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.

How could I create a command that will automatically escape all curly braces within the current environment?

For instance, I would like a command (or environment, I suppose) that allows me to write something like this:

Kuratowski identified the ordered pair $\langle x,y \rangle$ with the set $\{\{x \},\{x,y\}\}$ whereas Wiener identified it with the set $\{\{x,\emptyset\},\{y\}\}$.

Without having to put in all of the obnoxious \'s to escape the curly braces.

Is there an easy (and, hopefully, versatile) fix to this? I want something that will let me auto-escape the curly braces when I know I'm going to be using a lot of set-theoretic notation in the next few lines (or current environment).

share|improve this question
Would the "current environment" necessarily be a math environment, or could it be any environment whatsoever? –  Mico Jan 21 '13 at 22:13
@Mico in most instances it would be a math environment, but not necessarily. For instance, what I have quoted above would just be a normal part of the document and so not a math environment. I am, however, fine if solutions could be provided piecemeal (e.g., one that works in math environments and something else otherwise). –  Dennis Jan 21 '13 at 22:29
@Dennis as mico says: don't do this. Absolutely none of the surface syntax is fixed in Tex you can change the interpretation of any character, but if you use this flexibility (especially with \ and {} then you will be incompatible with virtually everything. the \ in \{ is no different to the \ in \section or \langle It is just how LaTeX is. –  David Carlisle Jan 21 '13 at 22:40
@Dennis changing catcode would mean that the command has all the restrictions of \verb which also changes catcodes, in particular will not work in the argument of another command. what you could do is have a command say \sets that braces every argument in a list so \sets{a,b,c} makes \{a\},\{b\},\{c\} \sets{a,{b,c}} makes \{a\},\{b,c\} That requires no catcode tricks –  David Carlisle Jan 21 '13 at 22:55
I guess I ought to:-) Give me a minute:-) –  David Carlisle Jan 21 '13 at 23:18
show 3 more comments

7 Answers

up vote 20 down vote accepted

Rather than mess with the interpretation of { it is probably better to define a command that takes a comma separated list of arguments and encloses each in braces. Some variants below depending on whether you want a brace around the outer list, and whether you want a comma separator. (Beware the space after #1 is needed otherwise the case with as single argument brace group {a,b,c} does not work as TeX drops the brace.

enter image description here


\def\sets#1{\@for\tmp:=#1 \do{\{\tmp\}}}

\def\setsb#1{\{\@for\tmp:=#1 \do{\{\tmp\}}\}}

\def\setsc#1{\def\sep{\def\sep{,}}\@for\tmp:=#1 \do{\sep\{\tmp\}}}

\def\setsd#1{\{\def\sep{\def\sep{,}}\@for\tmp:=#1 \do{\sep\{\tmp\}}\}}



$\sets{a,b,c}$ $\sets{a,{b,c}}$ $\sets{{a,b,c}}$

$\setsb{a,b,c}$ $\setsb{a,{b,c}}$ $\setsb{{a,b,c}}$

$\setsc{a,b,c}$ $\setsc{a,{b,c}}$ $\setsc{{a,b,c}}$

$\setsd{a,b,c}$ $\setsd{a,{b,c}}$ $\setsd{{a,b,c}}$

share|improve this answer
add comment

Rather than changing the meaning of { and } (which is potentially dangerous) you might like to use DeclarePairedDelimeter from the mathtools package as follows:


which can then be used as $\myset{x}$ or, as below, $\myset{\myset{x},y}$



Kuratowski identified the ordered pair $\langle x,y \rangle$ 
with the set $\{\{x \},\{x,y\}\}$ whereas Wiener identified 
it with the set $\{\{x,\emptyset\},\{y\}\}$.

Kuratowski identified the ordered pair $\langle x,y \rangle$ 
with the set $\myset{\myset{x},\myset{x,y}}$ whereas Wiener identified 
it with the set $\myset{\myset{x,\emptyset},\myset{y}}$.


If you find that you need to use this command for fractions, or other content that needs \left and \right, then simply use (for example) \myset*{\frac{a}{b}}

share|improve this answer
This is a nice way to clean up my code a bit, but doesn't quite do what I wanted. Is there no way to have it set up so that I have a command like \displaybrace so that I could write \displaybrace{{{x},{x,y}}} (or something similar) and have it automatically escape the braces within its scope? –  Dennis Jan 21 '13 at 22:41
Does using \DeclarePairedDelimiter\myset{\{}{\}} have advantages over \renewcommand{\myset}[1]{\{ #1 \}}? I have used the latter; mostly because I did not know another way, but also because is allows you to treat \myset{} in a special way, maybe to use \emptyset instead of \{\}. One problem I have encountered with this is that you can not use the command across multiple lines in an \align; does your solution have the same problem? –  Raphael Jan 21 '13 at 23:47
@Raphael see section 3.6 of the mathtools documentation for a good discussion :) –  cmhughes Jan 21 '13 at 23:52
add comment

LuaTeX to the rescue. No catcode trickery, and you can understand the code when you read it :)

I have written the example in ConTeXt because I am more familiar with it, but a similar approach will also work in LaTeX.


  thirddata = thirddata or {}

  thirddata.escapebraces = function (data)
      context(data:gsub("([{}])", "\\%1"))


The power set of $\escapebraces{ {x, y} }$ is $\escapebraces{ {\emptyset, {x}, {y}, {x,y} } }$



enter image description here

share|improve this answer
add comment

Let me preface the proposed solution by providing a warning and disclaimer:

I do not recommend anyone actually use this code! If you use any macros after the category codes of } and { have been changed to 12 ("other") and if these macros take arguments that might be encased in curly braces, exceedingly bad things are almost certainly going to happen to your document. You've been warned!

OK, here goes:


{hello world}

   \catcode123=12 % change cat code of "{" to "other"
   \catcode125=12 % change cat code of "}" to "other"

{hello world}

   \catcode123=1  % restore the cat codes of "{" and "}"

{hello world}

enter image description here

share|improve this answer
Haha, so now that you've told me not to utilize this code, is there a safe way to achieve something similar? Like a temporary re-categorization of the curly braces? –  Dennis Jan 21 '13 at 22:38
Plain-TeX and LaTeX -- and every other implementation of TeX I've ever encountered! -- assign special meanings to the characters `, {, }, $, &, #, ^, _`, and %. Changing the meanings of any of these is almost certainly going to create misery, howling, and gnashing of teeth. In other words, I wouldn't do it. I'd much recommend you try a solution along the lines of the one proposed by @cmhughes. –  Mico Jan 21 '13 at 22:47
some other pair of characters should be assigned catcodes 1 and 2 during the time the braces are made other. The question is: which ones? Perhaps ^^A and ^^B. < and > or ( and ) do not seem good if the OP wants to to math. Note that for math you also need to define a mathcode and even a delimiter code. The mathcode could be by default just 123 and 125 but then you don't have the opening and closing respective math types. No forget it, what the pain about \{ and \} when we have to type hundreds of backslashes per document? –  jfbu Jan 21 '13 at 22:48
@jfbu The pain is largely about readability of source. I would like to have something that resembles the output as closely as possible. All of the backslashes in a short bit of set notation are too close together for me to easily read. Something like cmhughes's solution would be fine, but I'd prefer not having a slew of commands cluttering up my source. I'd rather something like one command that I can surround the entire set notation with and escape all of the braces that way. –  Dennis Jan 21 '13 at 22:52
@jfbu That is documented in the TeXBook: If \delcode'{ were set to some nonnegative delimiter code, you would get no error message when you wrote something like \left{. This would be bad because strange effects would happen when certain subformulas were given as arguments to macros, or when they appeared in alignments. But it has an even worse defect, because a user who gets away with \left{ is likely to try also \bigl{, which fails miserably. –  David Carlisle Jan 21 '13 at 23:37
show 7 more comments

This is more of a proof of concept than a recommendable way to do what you're looking for. I'd stay with the \DeclarePairedDelimiter road outlined by cmhughes. However, here it is:

  \tl_set:Nn \l_tmpa_tl { #1 }
  \regex_replace_all:nnN { \cB. } { \c{lbrace} \c{use:n} \cB\{ } \l_tmpa_tl
  \regex_replace_all:nnN { \cE. } { \cE\} \c{rbrace} } \l_tmpa_tl


Kuratowski identified the ordered pair $\langle x,y \rangle$ with the set
$\escapebraces{ {{x},{x,y}} }$ whereas Wiener  identified it with the set
$\escapebraces{ {{x,\emptyset},{y}} }$.


Limitations: you can't use macros with arguments in the argument of \escapebraces, nor subscripts or superscripts enclosed in braces. For these you might use \bgroup and \egroup, so

$\escapebraces{ {x_\bgroup11\egroup,x_\bgroup12\egroup} }$

would work. Don't try using \sqrt\bgroup12\egroup, please.

enter image description here

share|improve this answer
Just curious: why the \use:n { and } in the replacement text of the regular expression? –  Bruno Le Floch Jan 22 '13 at 13:45
add comment

If one wants to use braces directly also in math mode, the mathcodes and delcodes must be correctly set. This is done here:


\def\displaybrace<{\bgroup\catcode`\>=2 \delcode123="266308
    \delcode125="267309 \mathcode123="4266 \mathcode125="5267
    \catcode123=12 \catcode125=12 }




Any use of a > will close the macro. Within the \displaybrace<..stuff...> we have a substitute only for the closing group delimiter with >.

displayed braces

So if one wants to do other things than just display some collection of braces and letters, the following slight extension is needed, which just additionally makes < also serve as opening group character:


\def\displaybrace<{\bgroup\catcode`\<=1 \catcode`\>=2 
    \mathcode123="4266 \mathcode125="5267
    \catcode123=12 \catcode125=12 }



 \[\omega < \displaybrace<\left{\int_a^b e^<-x^2>\,dx\right}> <z^2 \]



Please ntake note how I used < and > inside \displaybrace to code the superscript.

More generally any code (be it in text or math mode) where one would have used traditionnally { and } must be written with < and >. And it will work perfectly fine if this constraint is obeyed (except if some macro is used which really requires that { and } are in their traditional habits, or and this is more probable, some macro which would be completely surprised to learn that < and > are now the opening and closing group characters).

Obviously using < and > this way makes writing inequalities impossible... But we could let + and - play the rôle here played by < and >. Again + and - are used for many things so one would have to find something better...

...for example ^^A and ^^B (which have character codes 1 and 2) could play the rôle here attributed to < and > and this would allow complete freedom to set-up arbitrary math formulas (perhaps your sets are defined mathematically?). But then the input would not be so readable.

Let me explicitely points out that the above code is designed to work well with arbitrary \left or \big.. like constructions.


braces as other

share|improve this answer
add comment

The following was motivated by the answer by David Carlisle. Note that \sets{{a,{b,c},{{c,d},e}}} does not work with this (accepted) answer (neither would \setsb, \setsc, nor setsd).

CAVEAT: any input mistake (non matching braces) makes the TeX run end in an error!

CAVEAT2: only accepted elements here are letters (lowercase and uppercase) and \emptyset.

Please note how {} are converted into \emptyset (and how spaces in the input are ignored, as is expected anyhow in math mode).

The macro has to be used in math mode because of its use of \emptyset.

Edit1: improvement to allow spaces in the input ... (particularly, a space just before a closing brace was a disaster before the edit).

Nota Bene : this code is a bit to play with TeX's mechanism of grouping and local scope and recursive macros. It could be made more general. In a way, it's like telling TeX to show us it understands sets!

Edit2: one last update, just to fix the problem of { } giving {\emptyset} rather than just \emptyset.


\def\printset #1{\ifx\relax#1\relax\emptyset\else
                 \screensp #1\relax\emptyset
                 {\{\setaux #1\relax,\}}\fi}

\def\screensp #1\relax{\ifx#1\@sptoken\relax\expandafter\@firstoftwo\else

\def\setaux #1#2,#3{\ifx\relax#1\relax\emptyset\else
                  {\printset {#1}}\fi\fi\fi
                  \setaux\fi\fi {#3}}







\[\printset{{{a,b},{\emptyset,U,{}, {V,W}, {}},{{}},{d,{e,{U,{V,W}},\emptyset,f}}}}\]

\[\printset{a , b , { c , { d , { u , { v , w } } }} , { e } }\]

\[\printset{    }\]

\[\printset{   {  }   }\]



share|improve this answer
@jfbu: how would you compare this to the method with catcodes, mathcodes, and delcodes? answ.: the new thing is the \emptyset business. The inconvenience is that the elements of the sets are much restricted (here only letters and the \emptyset math character). The method with catcodes allows much more freedom, with the constraints described in that anwer. interviewer: ok, thanks and see you. –  jfbu Jan 22 '13 at 21:29
add comment

Your Answer


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.