# How can I escape plain text in section titles?

How one may with section titled "zażółć gęślą jaźń" or "\newline is a new line in LaTeX" may easily escape them? It is ceratin that nothing there should be treated as LaTeX formatting.

There is a nice solution for normal text, described in How can I escape plain text?

Unfortunately it fails for \section{}:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage{fvextra}
\DefineVerbatimEnvironment{escape}
{Verbatim}
{fontfamily=\rmdefault,breaklines,breaksymbolleft={}}

\begin{document}

\tableofcontents
\newpage
\section{\begin{escape}\newline\end{escape}}
\begin{escape}
red fox
sauté
zażółć gęślą jaźń
\newline is a new line in LaTeX
Samp_Dist_Corr
whatever whatever whatever whatever whatever whatever whatever whatever whatever whatever whatever
\end{escape}

\end{document}


fails with

! Argument of \FV@BeginScanning has an extra }.
<inserted text>
\par
l.14 \section{\begin{escape}\newline\end{escape}}


Using \section{\escape{\newline}} is not changing neither outcome nor error message.

To avoid XY problem: I am using pdflatex to generate pdf files from plaintext.

Define also an inline version of escape and use cprotect.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{cprotect}
\usepackage{fvextra}
\DefineVerbatimEnvironment{escape}
{Verbatim}
{fontfamily=\rmdefault,breaklines,breaksymbolleft={}}
\CustomVerbatimCommand\escapeinline{Verb}{fontfamily=\rmdefault,breaklines,breaksymbolleft={}}

\begin{document}

\tableofcontents

\cprotect\section{\escapeinline|\newline|}

This is inline: \escapeinline|??{xx|

\begin{escape}
red fox
sauté
zażółć gęślą jaźń
\newline is a new line in LaTeX
Samp_Dist_Corr
whatever whatever whatever whatever whatever whatever whatever whatever whatever whatever whatever
\end{escape}

\end{document}


verbatim like commands and environments usually do not work inside arguments of other commands. ltxdoc.cls, e.g., defines \cmd and \cs to solve this. They do not escape sequences of text but are used to print commands. A very simple suggestion would be to use TeX primitive \string, but you have to protect it inside \section:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage{fvextra}
\DefineVerbatimEnvironment{escape}
{Verbatim}
{fontfamily=\rmdefault,breaklines,breaksymbolleft={}}

% from ltxdoc.cls:
\DeclareRobustCommand\cs[1]{\texttt{\char\\#1}}
\makeatletter
\def\cmd#1{\cs{\expandafter\cmd@to@cs\string#1}}
\def\cmd@to@cs#1#2{\char\number#2\relax}
\makeatother

\begin{document}

\tableofcontents
\newpage
\section{\texttt{\protect\string\newline} \cmd\newline\space and \cs{newline}}
\begin{escape}
red fox
sauté
zażółć gęślą jaźń
\newline is a new line in LaTeX
Samp_Dist_Corr
whatever whatever whatever whatever whatever whatever whatever whatever whatever whatever whatever
\end{escape}

\end{document}