[Tex/LaTex] Using \newcommand with arguments inside of \newcommand

macros

I'm using the following commands inside my main TeX file right after the ToC.

\mainmatter
\pagestyle{fancy}
\renewcommand{\chaptermark}[1]{\markboth{\chaptername\ \thechapter.\ #1}{}}
\lhead[\thepage]{\leftmark}\chead[]{}\rhead[\myentitle]{\thepage}
\lfoot{}\cfoot{}\rfoot{}

I want to put it all into a new command \MainMatter. How can I do this? I have just tried to do so, however, I get the following error.

Illegal parameter number in definition of `\MainMatter`}.

How can this be done?

Best Answer

\newcommand definitions with arguments within another \renewcommand or \newcommand require a ##1, ##2 etc. for argument replacement, even if the outer command has no arguments at all.

In lack of a MWE, I just 'invented' one, defining the unknown command \myentitle.

\documentclass{book}

\usepackage{fancyhdr}%
\usepackage{blindtext}

\newcommand{\myentitle}{Some unknown text}
\newcommand{\MainMatter}{%
\mainmatter%
\pagestyle{fancy}%
\renewcommand{\chaptermark}[1]{\markboth{\chaptername\ \thechapter.\ ##1}{}}
\lhead[\thepage]{\leftmark}\chead[]{}\rhead[\myentitle]{\thepage}
\lfoot{}\cfoot{}\rfoot{}
}%

\begin{document}

\MainMatter

\chapter{The very first chapter}
\blindtext[10]

\end{document}

enter image description here

Related Question