3

!! Attention !!

Because this topic developed some amount of complexity, I tried to restructure the topic considering the newly gathered information. Please see this post to find the latest detail: Override macro with \renewcommand{} multiple times from different files - toc addcontentsline


I would like to add a line to my toc, depending on the comparison of two strings.

Inital setup

In the root-file I defined two commands

\newcommand{\Field}{Dummyfield}
\newcommand{\OldField}{}

The root-file gets a lot of chapter-files to read from. Every chapter redefines the \Field{}-command. What I want to do is to compare the strings in Field{} and \OldField{} and if they are not equal, I want to add a line to the toc, saying whatever \Field{} holds.

My files are: (Root-file)

% Dokument-Grundeinstellungen
\documentclass[11pt, a4paper, titlepage, parskip=half]{scrbook}
%   \usepackage{tocbasic}
\usepackage[a4paper,lmargin=2cm,rmargin=2cm,tmargin=2.5cm,bmargin=2.5cm]{geometry}  % Format und Seitenraender
\usepackage[onehalfspacing]{setspace}                                                   % Zeilenabstand
%------------------------------------------------------------

% Schriftart
%\usepackage[scaled=.92]{helvet}                    % Helvetica (skaliert) als serifenlose Schriftart (Standard fuer serifenlose Schrift)  -- besser geeigent zum Lesen am BILDSCHIRM
    % \renewcommand{\familydefault}{\sfdefault}     % (Eingestellte) serifenlose Schrift als Standardschrftart (fuer Fliesstext)
\usepackage{lmodern}                                % Besser lesbare Standardschriftart (Serifenschrift) -- besser geeigent zum Lesen auf PAPIER
    \renewcommand{\familydefault}{\rmdefault}       % (Eingestellte) Serifenschriftart als Standardschrift (fuer Fliesstext)
    \setkomafont{sectioning}{\rmfamily\bfseries}    % Ueberschriften in Serifenschrift (fett)
    %\setkomafont{sectioning}{\rmfamily}            % Ueberschriften in Serifenschrift (plain)
\usepackage{color}                                  % Textfarbe aendern - Fuer Dokument, Paragraph oder diskrete Texteile mit '\textcolor{Farbe}{Text}'



%------------------------------------------------------------

% Kopf- und Fusszeile
\usepackage[markcase=noupper, headsepline=false]{scrlayer-scrpage}  % no uppercasing
        \setkomafont{pageheadfoot}{\sffamily}
        \setlength{\headheight}{2cm}
        \setlength{\footheight}{2cm}
        \newcommand{\Field}{Dummyfield}
        \newcommand{\OldField}{}
    \ihead{Name: Jon Doe\\ Ausbildungsbereich: \Field}
    \ohead{\includegraphics[height=1.8cm]{./Bilder/Logo.jpg}}
    %\cfoot{\pagemark}

%------------------------------------------------------------

% Ausgabe von Umlauten (vor 'inputenc' einbinden!)
\usepackage[T1]{fontenc}        % Schoene Ausgabe von Umlauten
%------------------------------------------------------------

% Deutsche Eingabe
\usepackage[utf8]{inputenc}     % Umlaute direkt eingeben   UTF-8 zur besseren Zusammenarbeit mit vers. Betriebssystemen
\usepackage[ngerman]{babel}     % deutsche Eingabe (Zur Eingabe von Umlauten wird 'inputenc' benötigt)
%------------------------------------------------------------

% Mathematik-Bibliotheken
\usepackage{amsmath}    % Schoene Formelumgebung - align{, \[ \], ... - NICHT eqnarray, displaymath 
\usepackage{amssymb}    % mathematische Schriftarten, Zeichensaetze und Symbole - laedt automatisch das Paket 'asmfonts'
\usepackage{mathptmx}   % Funktion aktuell Unklar. Vmt: Verbindung von drei Schriftarten fuer serifen, serifenlosund typewriter Fonts: Times/Helvetica/Courier (Helvetica akaliert - siehe Schriftart)
    \usepackage{courier} % Schritart Courier als Typewriter-Font einstellen
\usepackage[exponent-product = \cdot, decimalsymbol=comma, per=frac ]{siunitx}  % SI-Einheiten verwenden Bsp: \SI{100}{\degreeCelsius}
\usepackage{advdate}                                    % Datumberechnungen anstellen
    \newcommand{\Datum}{00/00/0000}     % Leeres Datum vorbelegen
\usepackage{ifthen}
%------------------------------------------------------------

% Weitere Zeichensaetze
\usepackage{textcomp}   % Erweiterter Zeichensatz
\usepackage{enumitem}   % spez. Nummerierungen z.B. a) b) c)
\usepackage[autostyle=true, german=quotes]{csquotes}
%------------------------------------------------------------

% Bilder, Grafiken und Dokumente einbinden
\usepackage{graphicx}   % Bilder und Grafiken einbinden '\includegraphics[Optionen]{Herkunft/Speicherort}'
\usepackage{wrapfig}    % umfliessende Grafiken '\begin{wrapfigure}{Position{Breite} ..'
\usepackage{here}       % Figures (Bilder) genau an dieser Stelle einbinden / Einbinden erzwingen - Option [H] - !!ACHTUNG!! Als Option fuer Gleitumgebungen gedacht, widerspricht aber dem Sinn einer Gleitumgebung !
\usepackage{pdfpages}   % PDF-Dokumente einbinden
\usepackage{adjustbox}  % Objektgroessen anpassen/skalieren
\usepackage{tabularx}
\usepackage{array}
\newcolumntype{P}[1]{>{\centering\arraybackslash}p{#1}}
\usepackage{colortbl}
\usepackage{multirow}
\usepackage{pgf}
    \usepackage{pgfplots}
        \pgfplotsset{compat=1.16}
    \usepackage{pgffor}     
\usepackage{tikz}
\usepackage[absolute, overlay]{textpos}
    \setlength{\TPHorizModule}{1mm}
    \setlength{\TPVertModule}{1mm}
%------------------------------------------------------------

% Referenzen/Links lauffaehig machen
\usepackage[pdftex]{hyperref}       % Unmittelbares Erzeugen von PDF-Ausgabe / Verknuefpungen/Links herstellen UND Ermoeglichung von urls: \url{}
\usepackage{cleveref}               % Erweiterte Refernzenbefehle -- IMMER NACH hyperref lade
    \crefname{enumi}{Punkt}{Punkte} % Aendert den angezeigten Namen des Labels 'enumi' in 'Punkt' bzw. 'Punkte' (Plural)
    \crefname{figure}{Abbildung}{Abbildungen}
    \crefname{eqation}{Gleichung}{Gleichungen}
    \Crefname{equation}{Gleichung}{Gleichungen}
    \crefname{subsection}{Unterabschnitt}{Unterabschnitte}
    %\Crefname{subsection}{Unterabschnitt}{Unterabschnitte}
\usepackage[version=4]{mhchem}      % Noeatig um cref-Namen neu zu besetzen
\renewcommand{\listfigurename}{Abbildungen}


% Dauer-Kommando 
\newcommand{\dauer}[1]{\SI{#1}{\hour}}
% Kalendarwochen-Kommando
\newcommand{\KW}{00}
% Tabellenfarbe definier
\definecolor{tabcol}{rgb}{0.75, 0.75, 0.75}


\begin{document}
 %------------------------------------------------------------

\tableofcontents                % Inhaltverzeichnis erzeugen
\newpage
%-----------------------------------------------------------
    %\cleardoublepage
    %\cleardoublepage   
    \include{./2018/2018}
            \foreach \i in {00, 01, 02, ..., 99}{%
    \edef\FileName{./2018/Wochen/KW\i}%
    \IfFileExists{\FileName}{%
        \include{\FileName}%
    }
}
\end{document}

And one of the content-files (part of):

% ----------------------------------------EINSTELLUNGEN--------------------------------------------------
% ---------------------------- ANFANGSTAG  UND KW SETZEN ----------------------------------------
                                    \renewcommand{\Datum}{00/00/0000}                           % Datumsvariable neu setzen {TT/MM/JJJJ}
                                    \renewcommand{\KW}{36}                                                  % KW neu setzen; z.B. {36} fuer KW 136
% --------------------------------------------------------------------------------------------------------------
\SetDate[\Datum]%---------------------------------------------------------------------------------------      % \today per advdate aendern
% --------------------------------------------------------------------------------------------------------------
% ------------------------------------ BEREICH SETZEN ---------------------------------------------------
\renewcommand{\OldField}{\Field}% ------------------- Vorherigen bereich speichern ------
                            \renewcommand{\Field}{Testfield I}                              % Neuen Bereich setzen                  
% --------------------------------------------------------------------------------------------------------------
% --------------------------------------------------------------------------------------------------------------
\section*{KW \KW{} \hspace{12pt}\today{} - \AdvanceDate[4]\today}%---------------
\ifthenelse{ \not\equal{\OldField}{\Field}  }{%
    \addtocounter{section}{1}
    \addcontentsline{toc}{section}{\Field}}{
}
%  -------------------------------------------------------------------------------------------------------------
\SetDate[\Datum] %-- Datum zurücksetzen auf Wochenanfang-----------------------------
%--------------------------------------------------------------------------------------------------------------
%
%

I hope anyone can help me with this. Regards

After Werner's idea

Considering @Werner's answer, I changed my code. But I think there is still some kind of problem with my understanding of the mechanics. Below my new try for a content-file:

\let\OldField\Field% ------------------- Vorherigen Bereich speichern ----------------------
% ------------------------------------ BEREICH SETZEN ---------------------------------------------------
                            \renewcommand{\Field}{Service Desk}                                 % <--- Neuen Bereich setzen                 
% --------------------------------------------------------------------------------------------------------------
% --------------------------------------------------------------------------------------------------------------
\section*{KW \KW{} \hspace{12pt}\today{} - \AdvanceDate[4]\today}%----------------
\ifnum\pdfstrcmp{\Field}{\OldField}=0
\else
    \addtocounter{section}{1}
    \addcontentsline{toc}{section}{\Field}%------------------------------------------------------
\fi

But it still adds a new toc-entry for every file I include, no matter if the Fileds differ or not.


Values of \Field and \OldField at different points in the code

I let the .log-file show me all the values of \Field and \OldFiled at different points in my code and over the (currently) two files the root-file can read from.

\show\OldField %respectively \show\Field
\let\OldField\Field% ------------------- Vorherigen Bereich speichern ----------------------
%\show\OldField %respectively \show\Field
% ------------------------------------ BEREICH SETZEN ---------------------------------------------------
                            \renewcommand{\Field}{Service Desk}                                 % <--- Neuen Bereich setzen                 
% --------------------------------------------------------------------------------------------------------------
%\show\OldField %respectively \show\Field
% --------------------------------------------------------------------------------------------------------------
\section*{KW \KW{} \hspace{12pt}\today{} - \AdvanceDate[4]\today}%----------------
\ifnum\pdfstrcmp{\Field}{\OldField}=0
\else
    \addtocounter{section}{1}
    \addcontentsline{toc}{section}{\Field}%------------------------------------------------------
\fi

These are the values Values at the three points

So for me it seems like the values of \OldField is always taken from the initial newcommand{\OldField}{Dummyfield} in the root-file. And that's pretty bad. Now it makes perfect sense, that the strcmp never 0 and therefore running the else-statement. The question however is, Why does \OldField (always) show its initial value from the commands definition? And ever more important: Is there a fix?

1

Copying \Field into \OldField using

\renewcommand{\OldField}{\Field}

doesn't achieve what you want since the content of \Field is not expanded upon (re)definition of \OldField. Instead, \OldField is defined to be the same as \Field, which you change in a subsequent definition. As such, \OldField will always be the same as \Field and you'll never pick up a change.

Instead, you can copy the entire definition of \Field into \OldField using

\let\OldField\Field

and then perform conditioning using \ifx or a pdf string comparison:

enter image description here

\documentclass{article}

\begin{document}

% \Field and \OldField are the same
\newcommand{\OldField}{One}
\newcommand{\Field}{One}

\ifx\Field\OldField
  \verb|\Field| = \verb|\OldField| = \Field
\else
  \verb|\Field| = \Field; \verb|\OldField| = \OldField
\fi

\ifnum\pdfstrcmp{\Field}{\OldField}=0
  \verb|\Field| = \verb|\OldField| = \Field
\else
  \verb|\Field| = \Field; \verb|\OldField| = \OldField
\fi

\bigskip

% \Field and \OldField are different
\let\OldField\Field % Copy \Field into \OldField
\renewcommand{\Field}{Two}

\ifx\Field\OldField
  \verb|\Field| = \verb|\OldField| = \Field
\else
  \verb|\Field| = \Field; \verb|\OldField| = \OldField
\fi

\ifnum\pdfstrcmp{\Field}{\OldField}=0
  \verb|\Field| = \verb|\OldField| = \Field
\else
  \verb|\Field| = \Field; \verb|\OldField| = \OldField
\fi

\end{document}

\ifx<cmdA><cmdB> checks whether the definition of <cmdA> matches that of <cmdB>, while \pdfstrcmp{<strA>}{<strB>} checks whether the (expanded) text <strA> matches <strB>, returning 0 if that's the case. This allows one to check it with \ifnum<pdfstrmp>=0.

| improve this answer | |
  • Wow, thank you for this very elaborated example. I tried to implement it. Please see my edited post above. Appreciate your help :) – Michael Schmid Oct 9 '18 at 9:00
  • @MichaelSchmid: Did you compile twice? Entries in the ToC need (at least) 2 compilations to settle. – Werner Oct 9 '18 at 14:11
  • Yes, compiled like a thousend times in a row for I know this behavior. – Michael Schmid Oct 9 '18 at 14:25
  • @MichaelSchmid: What does \show\Field and \show\OldField look like just before your test? Based on what you're saying, they should always be different. Is that the case? Can you provide a minimal example that I can use to replicate your current (problematic) behaviour? – Werner Oct 9 '18 at 15:43
  • BEFORE I redefine the \Field in \renewcommand{\Field}{Testfield I} (but after \let\OldField\Field) they show this: \Field=\long macro: ->DummyField. l.10 \show\Field (which is my default) \OldField=\long macro: ->Dummyfield. l.10 \show\OldField AFTER I redefine \Field the .log shows: \Field=\long macro: ->Testfield I. l.13 \show\Field \OldField=\long macro: ->Dummyfield. l.13 \show\OldField – Michael Schmid Oct 10 '18 at 6:57
1

Your \OldField macro will always expand to \Field, so the test will return true.

You need

\expandafter\renewcommand\expandafter\OldField\expandafter{\Field}

so \OldField will expand to the current contents of \Field, that you redefine later on.

A simpler method, once you get the hang of it, is

\let\OldField\Field
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.