Tăng sai bộ đếm?

Sep 08 2020

Bối cảnh

Tôi muốn thêm các nhận xét đánh dấu được đánh số tự động trong văn bản.

Cố gắng

Sau câu trả lời này, tôi đã viết như sau

\documentclass{article}
\usepackage{color}
\usepackage{soul}

\newcounter{mycounter}
\newcommand\showmycounter{\stepcounter{mycounter}\themycounter}

\definecolor{aquamarine}{rgb}{0.5, 1.0, 0.83}
\newcommand{\my}[1]{\sethlcolor{aquamarine} 
   \protect\hl{Comment \showmycounter: #1} \sethlcolor{yellow}}

\begin{document}
some text 
\my{my first comment}\\
some more text
\my{my second comment}

\end{document}

mà không may vì một số lý do kỳ lạ làm tăng bộ đếm trong các bước năm.

Câu hỏi

Bạn có thể vui lòng cho tôi biết làm thế nào để tăng đơn vị trên bộ đếm này?

PS: Tôi là một người mới lập trình latex. Cho tôi xin lỗi trước nếu câu hỏi này là ngu ngốc.

Trả lời

3 Skillmon Sep 08 2020 at 20:26

Cung cấp nhận xét của tôi như một câu trả lời: Bạn không nên đặt \stepcounterbên trong đối số của \hl. Thay vào đó, hãy tăng bộ đếm trước nó và chỉ đặt \themycounterbên trong \hl:

\documentclass{article}
\usepackage{color}
\usepackage{soul}

\newcounter{mycounter}

\definecolor{aquamarine}{rgb}{0.5, 1.0, 0.83}
\DeclareRobustCommand{\my}[1]
  {%
    \sethlcolor{aquamarine}\stepcounter{mycounter}%
    \protect\hl{Comment \themycounter: #1} \sethlcolor{yellow}%
  }

\begin{document}
some text 
\my{my first comment}\\
some more text
\my{my second comment}

\end{document}

4 egreg Sep 08 2020 at 20:53

Việc xử lý \hlyêu cầu nhiều lần vượt qua đối số của nó để thực hiện các phép đo. Bạn phát hiện ra rằng có năm lần vượt qua và mỗi lần vượt qua sẽ làm tăng bộ đếm. Lưu ý rằng \stepcounterhoạt động trên toàn cầu.

Bạn có thể tránh phải lao vào mớ soulcông việc khác.

\documentclass{article}
\usepackage{color}
\usepackage{soul}

\definecolor{aquamarine}{rgb}{0.5, 1.0, 0.83}

\newif\ifstep
\newcommand{\stepcounteronce}[1]{%
  \ifstep
    \global\stepfalse
    \stepcounter{#1}%
  \fi
}

\newcounter{mycounter}
\newcommand\showmycounter{\stepcounteronce{mycounter}\themycounter}
\newcommand{\my}[1]{{% an additional group to do \sethlcolor locally
  \global\steptrue
  \sethlcolor{aquamarine}%
  \hl{Comment \showmycounter: #1}%
}}

\begin{document}

some text 
\my{my first comment}

some more text
\my{my second comment}

This is again \hl{yellow}

\end{document}

Bằng cách thêm vào, \global\steptruebạn bắt đầu máy móc chỉ cho phép \stepcounteroncelàm \stepcounterlần đầu tiên.

Lưu ý nhóm bổ sung, cho phép tránh khai báo lại một cách rõ ràng \sethlcolor.