1

How can I count the number of leading spaces and not all spaces as with the use of \str_count_spaces ?

Concretly I would like to read a content line by line and for each line of input I would use the indentation to build the corresponding output.

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
    \seq_new:N \l__pmbc_words_seq
    \tl_new:N \l__pmbc_one_temp_tl

    \NewExpandableDocumentCommand{\nbleadingsp}{m} {
        \projetmbc_nbleadingsp:n { #1 }
    }

    \cs_new:Nn \projetmbc_nbleadingsp:n {
        % ...
    }
\ExplSyntaxOff


\begin{document}

\nbleadingsp{ 1space}

\nbleadingsp{  two spaces}

\nbleadingsp{  2 * 2    spaces}

\end{document}
2
  • TeX ignores consecutive spaces, so unless you force them in some other way, typing \nbleadingsp{ a} or \nbleadingsp{ a} or \nbleadingsp{ a} will all have one single space token. – Phelype Oleinik Aug 13 '20 at 16:33
  • 1
    You can do it only if you don't allow \nbleadingsp to be in the argument of another command. Or globally changing the category code of the space, which would break so many things… – egreg Aug 13 '20 at 16:43
3

As Phelype Oleinik and egreg has said, it's possible only by reading the argument verbatim, which forbides the use in another command.

In the following code, the argument is taken verbatim by use of the v specifier of xparse.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand { \nbleadingsp } { v } 
  { \__pmbc_nbleadingsp:n { #1 } }

\cs_new_protected:Npn \__pmbc_nbleadingsp:n #1
  {
    \int_zero:N \l_tmpa_int
    \str_map_inline:nn { #1 }
      {
        \str_if_eq:nnTF { ##1 } { ~ } 
          { \int_incr:N \l_tmpa_int }
          { \str_map_break: }
      }
    \int_use:N \l_tmpa_int
  }
\ExplSyntaxOff


\begin{document}

\nbleadingsp{ 1space}

\nbleadingsp{  two spaces}

\nbleadingsp{  2 * 2    spaces}

\nbleadingsp{    four    spaces }

\end{document}
1
  • Thanks a lot. That is a very good starting point. I will use two compilations and infos stored in an extra files if I have to work with LaTeX macros in the content. 😆 – projetmbc Aug 13 '20 at 17:08

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.