Creating my first command
Expanding on the comments of Gonzalo Medina and egreg, I would recommend create the macro \code
as such:
\newcommand{\code}[2][ForestGreen]{\textcolor{#1}{\textit{#2}}}
Then \code{text}
and \code[red]{text}
produce:
Explanation:
[2]
so as to accept two parameters:#1
and#2
.- To provide a default color, we make the first one (
#1
) optional via defining a default of[ForestGreen]
.
Notes:
- no need to load both
color
andxcolor
packages -- just loadxcolor
.
Code:
\documentclass{article}
\usepackage[svgnames]{xcolor}
\newcommand{\code}[2][ForestGreen]{\textcolor{#1}{\textit{#2}}}
\begin{document}
\code{text}
\code[red]{text}
\end{document}
Well, most has already been commented while I was composing an answer. I recommend that you have a look at the xparse
package -- using it considerably simplyfies command definitions as soon as optional parameters and conditional branches are involved. You can find the documentation on CTAN, an example is included in the code given below.
\documentclass{article}
\usepackage{lipsum}
\usepackage{xparse}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\newcommand{\format}[1]{%
\textcolor{ForestGreen}{\textit{#1}}}
%format multiple paragraphs
\newcommand{\parformat}[1]{%
{\color{ForestGreen} \itshape #1}}
%xparse version; [m]andatory text parameter,
%[O]ptional color parameter with a given default
\NewDocumentCommand{\xformat}{O{MidnightBlue} m}{%
\textcolor{#1}{\textit{#2}}}
%xparse version for long mandatory argument
\NewDocumentCommand{\xparformat}{O{MidnightBlue} +m}{%
{\color{#1} \itshape #2}}
\begin{document}
\noindent
\format{Formatted text}\\
\xformat{some more text}\\
\xformat[red]{yet more text}\\
\parformat{\lipsum[3]\par\lipsum[4]}
\xparformat[cyan]{\lipsum[3]\par\lipsum[4]}
\end{document}