1

I found a macro, counting the number of occurrences of a substring, as an answer to a different question. This does exactly what I want, at least, when just printing its output to the document. I want to use the output, and pass it on to a different command -- specifically, to the \bookmark[level=] value. I cannot figure out how to get it to expand, or how to capture its output. I am sure this is very trivial, and maybe I am simply missing the vocabulary to search for this -- but I would appreciate any help.

The code in question:

\ExplSyntaxOn
% \CountSubStr{<substring>}{<string>}
\NewDocumentCommand{\CountSubStr}{ m m }{
  \seq_set_split:Nnn \l_tmpa_seq { #1 } { #2 }
  \int_eval:n {(\seq_count:N \l_tmpa_seq) - 1 }
}
\ExplSyntaxOff
2
  • Can you provide a complete example? What package is the \bookmark from? May 13, 2023 at 19:10
  • tl;dr: "I am sure this is very trivial" → No, it's impossible. Unless you modify the thing to store the result somewhere (as in the answer below that stores it into a counter) that "is expandable" (\thesubstringcount).
    – user202729
    May 14, 2023 at 2:28

1 Answer 1

1

Not sure how you want \bookmark to work with \CountSubStr but this should work:

\documentclass{article}

\usepackage{bookmark}

\newcounter{substringcount}

\ExplSyntaxOn

% \CountSubStr{<substring>}{<string>}
\NewDocumentCommand{\CountSubStr}{ m m }
{
    \seq_set_split:Nnn \l_tmpa_seq { #1 } { #2 }
    \setcounter{substringcount}{ \int_eval:n {(\seq_count:N \l_tmpa_seq) - 1 } }
}
\ExplSyntaxOff

\bookmark[level=\thesubstringcount]{Last page}

\begin{document}
    Hello
    \CountSubStr{ab}{abcdeab}
\end{document}
9
  • Using \NewExpandableDocumentCommand doesn't magically turn unexpandable functions into expandable. And \seq_set_split:Nnn is unexpandable, because it must do assignments. Neither \setcounter is expandable, by the way.
    – egreg
    May 13, 2023 at 21:02
  • @egreg: It does not have to be since I assign the result to a counter and then use the counter when I need the result of the function… May 13, 2023 at 21:11
  • I was mainly objecting to the usage of \NewExpandableDocumentCommand, which is wrong in that context.
    – egreg
    May 13, 2023 at 21:23
  • as the content of your function is not expandable, you can simply use \NewDocumentCommand, it doesn't change anything. And why do you expect the bookmark to use the correct value if the bookmark is before the command?? May 13, 2023 at 21:23
  • @egreg: It was from a previous attempt with a different solution. I did not think it did any harm leaving it in. Apparently I was wrong. I have now removed the wrong part. May 13, 2023 at 21:25

You must log in to answer this question.

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