TeX - LaTeX Asked on January 14, 2021
I a looking for a command that would output $C$ if I only write c
and output $15C$ if I write c{15}
. How can that be done?
newcommand{c}{$C$}
While technically feasible, creating commands with brace-delimited optional arguments is not a good idea: this is highly non-standard in LaTeX and is likely to be confusing. The standard syntax for LaTeX is to delimit optional arguments with square brackets, which can be done this way in your case:
newcommand*{cc}[1][]{$#1C$}
The []
means that the command has an optional argument and that its default value is empty (newcommand
supports at most one optional argument, and it has to come first; if you want more power and freedom here, use NewDocumentCommand
and friends which are already available if you use the LaTeX format from 2020-10-01 or later, otherwise just require a usepackage{xparse}
). If you replaced the []
with [abc]
, the default value would be abc
.
This is a valid definition that will produce $C$
when no [
follows cc
, and $15C$
when, for instance, you input cc[15]
.
Note that I didn't use the name c
that you proposed, otherwise one would get the error LaTeX Error: Command c already defined
. Indeed, the c
command already exists in plain TeX and in LaTeX: it is used to produce a cedilla. For instance, c{e}
prints an e
with a cedilla (whatever that means; ç
and Ç
, which can be obtained with c{c}
and c{C}
, are used in French words such as « remplaçant » and « Ça », for instance).
When naming personal macros, you may choose the names you want as long as they don't clash with already defined commands. In general, one-letter command names should be avoided because they are too likely to be used by some standard macro package (plain TeX, LaTeX, amsmath
maybe...). Safe names contain a portion unique to you or to your project; such names are almost always used (at least for internal macros) when writing classes or packages. On this site, we often use names such as myCommand
or my@command
, implicitly suggesting you to replace my
with something more personal (because if you take myCommand
from an answer and another myCommand
from a different answer, they are quite likely to clash!). TeX doesn't have the notion of modules or namespaces; being careful with unique prefixes (or suffixes) is a reasonable way to cope with this lacking feature.
Correct answer by frougon on January 14, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP