新しいコマンドを使用するとページ番号がリセットされます

新しいコマンドを使用するとページ番号がリセットされます

何かをn回繰り返すことができるコマンドをプリアンブルで定義しました

\def\myrepeat#1#2{\count0=#1 \loop \ifnum\count0>0 \advance\count0 by -1 #2\repeat}

つまり、\myrepeat{3}{foo} は foofoofoo と入力するのと同じです。

本文で \myrepeat コマンドを使用するたびに、ページ番号が 0 にリセットされます。なぜこのようなことが起こるのでしょうか。また、これを修正する簡単な方法はありますか。

問題を説明する例を以下に示します。

\documentclass[]{article}

\def\irepeat#1#2{\count0=#1 \loop \ifnum\count0>0 \advance\count0 by -1 #2\repeat}

\begin{document}
The page number here is 1.
\newpage
\irepeat{3}{foo}
The page number here is 0.
\newpage
And 1 again.
\end{document}

ありがとう。

答え1

カウンターは\count0現在のページ番号を保存するので、一時的な保存場所として使用するのはお勧めできません。コードをグループで囲むことで可能になりますが、何かを印刷する場合はお勧めしません。段落を印刷すると予期しないタイミングでページ ビルダーが起動し、ページに間違った番号が付けられる可能性があるためです。

LaTeX は、一時記憶用に と の 2 つのカウンターを提供します。\@tempcnta\@tempcntb使用することもできます。\count@これは と同じです\count255

トークン リストの繰り返しコピーを印刷するより良い方法があります。最も簡単な方法は、LaTeX3 の機能を使用することです。

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\irepeat}{ m m }
{
 \prg_replicate:nn { #1 } { #2 }
}
\ExplSyntaxOff

\begin{document}

\irepeat{3}{foo}

\end{document}

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

\numexpr標準的なLaTeX技術を使えば、

\documentclass{article}

\makeatletter
\newcommand{\irepeat}[2]{%
  \ifnum#1>\z@
    #2%
    \expandafter\@firstofone
  \else
    \expandafter\@gobble
  \fi
  {\expandafter\irepeat\expandafter{\number\numexpr#1-1\relax}{#2}}%
}
\makeatother

\begin{document}

\irepeat{3}{foo}

\end{document}

ループ付き

\documentclass{article}

\makeatletter
\newcommand\irepeat[2]{%
  \@tempcnta=#1\relax % or \@tempcntb or \count@
  \loop\ifnum\@tempcnta>\z@
    \advance\@tempcnta by \m@ne
    #2%
  \repeat
}
\makeatother

\begin{document}

\irepeat{3}{foo}

\end{document}

関連情報