2

related to Substring of filename in LaTeX and extract number from \jobname as counter .

I am naming my filenames as 01-text1.tex, 02-something.tex, 03-blah.tex and so on. I would like to set my section counter according to the first two letters (digits). something like

\setcounter{section}{\StrLeft{\jobname}{2}}
\addtocounter{section}{-1}

this was less than successful, probably catcodes :-(. can someone please recommend the magical invokation that works?

2 Answers 2

5

you need an expandable command if you are going to inline it into \setcounter xstring commands are mostly not expandable.

\def\getprefix#1-#2\relax{#1}
\setcounter{section}{\expandafter\getprefix\jobname\relax}

should work.

While it is true that letters in \jobname have strange catcodes that isn't actually an issue here as the digits are the usual catcode 12.

4

The usual problem: this is not expandable.

Workaround: compute the string beforehand:

\documentclass{article}
\usepackage{xstring}

\begin{document}

\StrLeft{\jobname}{2}[\temp]
\setcounter{section}{\temp}
\addtocounter{section}{-1}

\section{Title}
text

\end{document}

Simpler solution:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\setcounter{section}{ \str_range:Nnn \c_sys_jobname_str { 1 } { 2 } }
\addtocounter{section}{-1}
\ExplSyntaxOff

\begin{document}

\section{Title}
text

\end{document}

Of course there is a lower level solution, but much less fun:

\documentclass{article}

\begingroup\def\welch#1#2#3\welch{#1#2}
\setcounter{section}{\expandafter\welch\jobname..\welch}
\addtocounter{section}{-1}
\endgroup

\begin{document}

\section{Title}
text

\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .