\docsvlist とネストされた関数: 不要な大きなスペース

\docsvlist とネストされた関数: 不要な大きなスペース

カンマで区切られたリストを反復処理して、いくつかの単語を翻訳したいと思います。パッケージ\docsvlistを使用してこれを行う方法は既に見つけました。ただし、印刷されたカンマの後に「通常の」スペースのみがあるはずなのに、最初の単語の前と単語の間に大きなスペースが印刷されています。この問題は、翻訳に使用されるコマンドetoolboxのネストから生じていると思います。\ifstrequal

以下は、ネストの影響を示すために、すべての可能な翻訳を呼び出す例と最初の翻訳のみを呼び出す例を含む MWE です。

これらの追加スペースを回避するにはどうすればよいでしょうか?

ムウェ

\documentclass{article}

\usepackage{etoolbox}

\begin{document}
    
    \newcommand\TranslateAnimal[1]{
        \ifstrequal{#1}{Cat}{Chat}{
            \ifstrequal{#1}{Dog}{Chien}{
                \ifstrequal{#1}{Mouse}{Souris}{
                    \ifstrequal{#1}{Bird}{Oiseau}{
                        \ifstrequal{#1}{Horse}{Cheval}{
                            #1 % If there is no known translation
        }}}}}
    }

    \newcommand{\TranslateAnimalList}[2][,]{
        \def\nextitem{\def\nextitem{#1}}% Separator
        \renewcommand*{\do}[1]{\nextitem\TranslateAnimal{##1}} % How to process each item
        \docsvlist{#2}% Process list
    }

    There are additional large spaces before the first word and after words: \TranslateAnimalList{Cat,Bird,Dog,Horse,Mouse,Seal,Donkey}
    
    Compare with: \TranslateAnimalList{Cat,Cat,Cat,Cat,Cat,Cat,Cat} where there is only a large space before the first word

\end{document}

答え1

違いを確認して行末のパーセント記号 (%) は何に使用されますか? (マクロが余分なスペースを作成するのはなぜですか?)

\documentclass{article}

\usepackage{etoolbox}

\newcommand\TranslateAnimal[1]{%
  \ifstrequal{#1}{Cat}{Chat}{%
    \ifstrequal{#1}{Dog}{Chien}{%
      \ifstrequal{#1}{Mouse}{Souris}{%
        \ifstrequal{#1}{Bird}{Oiseau}{%
          \ifstrequal{#1}{Horse}{Cheval}{%
            #1% If there is no known translation
  }}}}}%
}

\newcommand{\TranslateAnimalList}[2][, ]{%
  \def\nextitem{\def\nextitem{#1}}% Separator
  \renewcommand*{\do}[1]{\nextitem\TranslateAnimal{##1}}% How to process each item
  \docsvlist{#2}% Process list
}

\begin{document}
    
The list is \TranslateAnimalList{Cat,Bird,Dog,Horse,Mouse,Seal,Donkey}.

Compare with \TranslateAnimalList{Cat,Cat,Cat,Cat,Cat,Cat,Cat}.

\end{document}

おそらく、 を使用した異なる実装を評価できるでしょうexpl3

\documentclass{article}
%\usepackage{xparse} % not needed with LaTeX 2020-10-01 or later

\ExplSyntaxOn
\NewExpandableDocumentCommand{\TranslateAnimal}{m}
 {
  \str_case:nnF { #1 }
   {
    {Cat}{Chat}
    {Dog}{Chien}
    {Mouse}{Souris}
    {Bird}{Oiseau}
    {Horse}{Cheval}
   }
   { #1 } % no known translation
 }

\NewDocumentCommand{\TranslateAnimalList}{O{,~}m}
 {
  \seq_clear:N \l_tmpa_seq
  \clist_map_inline:nn { #2 }
   {
    \seq_put_right:Nn \l_tmpa_seq { \TranslateAnimal { ##1 } }
   }
  \seq_use:Nn \l_tmpa_seq { #1 }
 }
\ExplSyntaxOff

\begin{document}
    
The list is \TranslateAnimalList{Cat,Bird,Dog,Horse,Mouse,Seal,Donkey}.

Compare with \TranslateAnimalList{Cat,Cat,Cat,Cat,Cat,Cat,Cat}.

\end{document}

ここに画像の説明を入力してください

関連情報