I have a problem with redefining a comamnd within a new environment.
Not working MWE:
\documentclass{book}
\makeatletter
\newcommand{\mysection}{\@ifstar{\mysection@star}{\mysection@nostar}}
\newcommand{\mysection@star}[1]{\begingroup\sloppy\raggedright\section*{#1}\endgroup}
\newcommand{\mysection@nostar}[1]{\begingroup\sloppy\raggedright\section{#1}\endgroup}
\newcommand{\mysubsection}{\@ifstar{\mysubsection@star}{\mysubsection@nostar}}
\newcommand{\mysubsection@star}[1]{\begingroup\sloppy\raggedright\subsection*{#1}\endgroup}
\newcommand{\mysubsection@nostar}[1]{\begingroup\sloppy\raggedright\subsection{#1}\endgroup}
\makeatother
\newenvironment{MySubAppendix}{%
\makeatletter%
\renewcommand{\mysection}{\@ifstar{\mysubsection@star}{\mysubsection@nostar}}%
\makeatother%
}{}
\begin{document}
\begin{MySubAppendix}
\mysection{Sub After Block Example}
\end{MySubAppendix}
\end{document}
This leads, with pdflatex, to:
This is pdfTeX, Version 3.14159265-2.6-1.40.19 (MiKTeX 2.9.6840 64-bit)
entering extended mode
(refman.tex
LaTeX2e <2018-04-01> patch level 5
("C:\Program Files\MiKTeX 2.9\tex\latex\base\book.cls"
Document Class: book 2014/09/29 v1.4h Standard LaTeX document class
("C:\Program Files\MiKTeX 2.9\tex\latex\base\bk10.clo")) (refman.aux)
! You can't use `\spacefactor' in vertical mode.
\@->\spacefactor
\@m {}
l.19 \mysection
{Sub After Block Example}
Working MWE:
\documentclass{book}
\makeatletter
\newcommand{\mysection}{\@ifstar{\mysection@star}{\mysection@nostar}}
\newcommand{\mysection@star}[1]{\begingroup\sloppy\raggedright\section*{#1}\endgroup}
\newcommand{\mysection@nostar}[1]{\begingroup\sloppy\raggedright\section{#1}\endgroup}
\newcommand{\mysubsection}{\@ifstar{\mysubsection@star}{\mysubsection@nostar}}
\newcommand{\mysubsection@star}[1]{\begingroup\sloppy\raggedright\subsection*{#1}\endgroup}
\newcommand{\mysubsection@nostar}[1]{\begingroup\sloppy\raggedright\subsection{#1}\endgroup}
\makeatother
\newenvironment{MySubAppendix}{%
}{}
\begin{document}
\begin{MySubAppendix}
\makeatletter%
\renewcommand{\mysection}{\@ifstar{\mysubsection@star}{\mysubsection@nostar}}%
\makeatother%
\mysection{Sub After Block Example}
\end{MySubAppendix}
\end{document}
At first glance the working version would be an alternative, but when having this multiple times it is a bit of a problem writing each times the part:
\makeatletter%
\renewcommand{\mysection}{\@ifstar{\mysubsection@star}{\mysubsection@nostar}}%
\makeatother%
Any ideas?
\makeatletter/\makeatotherin the expansion code of a macro. I once asked a similar question. (Similar but not quite a duplicate.) – campa May 23 '19 at 10:13\newcommandor\newenvironmentare involved is the same. – egreg May 23 '19 at 11:01@was part of the argument, while here it is explicitly present in the replacement text: that's why I deemed the questions similar but not exact duplicates. But of course the underlying problem is the same. – campa May 23 '19 at 11:15