[Tex/LaTex] Section or chapter in header

header-footer

I am writing a document and I have made it, so that on every even page, the header shows the current chapter, and on every odd page it shows the current section. But how can I show either the current chapter or the current section in the header, depending on the fact that the current page already belongs to a section or not?

\documentclass[a4paper, 12pt, twoside]{scrreprt}                            
\usepackage{geometry}                           
\usepackage[utf8]{inputenc}             
\usepackage[ngerman]{babel}              
\usepackage[T1]{fontenc}        
\usepackage{blindtext}  
\usepackage[headsepline]{scrlayer-scrpage}
\pagestyle{scrheadings}
\clearpairofpagestyles                          
\rohead{\chaptername :\ \rightmark}     
\lehead{\chaptername :\ \leftmark}      
\automark[section]{chapter}                                         
\ofoot[\pagemark]{\pagemark}

\begin{document}
\chapter{1}
    \blindtext
    \chapter{2}
    \section{2.1}
    \blindtext
    \chapter{3}
    \blindtext
    \section{3.1}
    \blindtext
\end{document}

Best Answer

You can use the additive star version \automark*:

\documentclass[a4paper, 12pt, twoside]{scrreprt}                            
\usepackage{geometry}                           
\usepackage[utf8]{inputenc}             
\usepackage[ngerman]{babel}              
\usepackage[T1]{fontenc}        
\usepackage{blindtext}  
\usepackage[headsepline]{scrlayer-scrpage}
\automark[chapter]{chapter}
\automark*[section]{}% Add odd side marks without removing previous marks
\renewcommand*{\chaptermarkformat}{\chapapp~\thechapter:\enskip}% Put "chapter" oder "appendix" in front of the chapter number in running head
\clearpairofpagestyles
\ohead{\headmark}                         
\ofoot*{\pagemark}

\begin{document}
\chapter{Erstes Kapitel}
    \Blindtext\Blindtext
\chapter{Zweites Kapitel}
\section{Erster Abschnitt des zweiten Kapitels}
    \Blindtext\Blindtext
\chapter{Drittes Kapitel}
    \Blindtext\Blindtext
\section{Erster Abschnitt des dritten Kapitels}
    \Blindtext\Blindtext
\end{document}

The first \automark[chapter]{chapter} activates automatic running heads and defines a \chaptermark to set left and right mark and resets \sectionmark etc. The second \automark*[section]{} does only define \sectionmark to set the right mark (odd syntax: left argument → right mark; right argument → left mark). So you have chapter on the left and right pages until you have a \section that changes the running head of right pages to be the section.

Related Question