[Tex/LaTex] How to define a command in the preamble with an optional argument for use in macros

macrostitles

I'm trying to write tags to include document info which can be declared in the preamble then included in a title page using \@institution or \@module, similar to how LaTeX already includes \title{} to get \@title.

I need a command which has an optional "module number" and can be declared by \module[PH588]{Mathematical Techniques} in the preamble, to form tags like \@mod@no and \@mod@title (or similar) to be used in the title page as

{\Large \mod@no: \@mod@title \par}

and produce "PH588: Mathematical Techniques" in a large font.

I am new to this whole macro business and am only fully comfortable with basics like \newcommand. For other information I've used

\newcommand{\department}[1]{\renewcommand\@dept{#1}}
    \newcommand{\@dept}{}

to define each title element.

My attempts thus far (which have been fruitless) are along the lines of:

1)

\def\module[#1]#2{\gdef\@module[#1]{#2}}
    \def\@module{}

2)

\def\module{\@ifnextchar[{\@module@wno}{\@module@wono}}
    \newcommand{\@module}{}
        \def\@module[#1]#2{#1: #2}
        \def\@module#1{#1}

3)

\newcommand{\module}[2][no module number]{\@ifnextchar[{\renewcommand\@module@no[2]{#1}}{\renewcommand\@module}}
    \def\@module@no[#1]#2{#1}
    \def\@module#1{#1}
    \newcommand\@module@no[#1]#2{#1: #2}
    \newcommand\@module#1{#1}

These are all between \makeatletter and \makeatother.

As you can see I have very little idea what I'm doing, so if you could provide a simple explanation of how each part of your code does what it's doing and why that would really help me out!

Thanks in advance!

Best Answer

Something with the hard way using \@ifnextchar and the easy way with xparse

\documentclass{article}

\usepackage{xcolor}
\usepackage{xparse}

\makeatletter

\providecommand{\@module@no}{}
\providecommand{\@module@title}{}


\newcommand{\module}{%
  \@ifnextchar[{\module@@opt}{\module@@noopt}
}

\newcommand{\module@@opt}[2][no module number]{%
\renewcommand{\@module@no}{#1}%
\renewcommand{\@module@title}{#2}%
}

\newcommand{\module@@noopt}[1]{%
  \module@@opt{#1}%
}


%\@onlypreamble{\module}


\NewDocumentCommand{\Module}{o+m}{%
  \IfValueTF{#1}{%
    \renewcommand{\@module@no}{#1}%
  }{%
    \renewcommand{\@module@no}{no module number}%
  }%
  \renewcommand{\@module@title}{#2}%
}


\newcommand{\printmoduleinfo}{%
{\large \textbf{\@module@no} \textsc{\@module@title}}%
}



\makeatother




\begin{document}

\module[The Fellowship of the Ring]{The Lord Of the Rings}


\printmoduleinfo

\module{The Lord Of the Rings}

\printmoduleinfo

\fbox{\textcolor{blue}{And now again with the xparse stuff}}

\Module[The two Towers]{The Lord Of the Rings}

\printmoduleinfo

\Module{The Lord Of the Rings}

\printmoduleinfo


\end{document}

enter image description here

Related Question