如何建立固定計數器?

如何建立固定計數器?

如何建立一個一旦設定就固定的計數器?

這個想法是在應該編號的文本中插入某種註釋,但隨著原始程式碼中實際實現的日期而增加。

它們不應該依賴原始程式碼中的順序,並且即使其中一些被刪除,它們也應該保留其值。

這裡不是 MWE,而是一個實現應該是什麼樣子的想法:

\documentclass{article}
\begin{document}
  \mynote{Some note I've added first}, 
  \mynote{A fourth note}, 
  \mynote{A second note}, 
  \mynote{A fifth note}, 
  \mynote{A third note}.    
\end{document}

這應該給出如下輸出:

註1:我首先添加的一些註釋
註4:第四個注意事項,
筆記2:第二個注意事項,
註5:第五個音符,
註3:第三個註釋。

如果我刪除帶有第二個註釋的行,它應該給出:

註1:我首先添加了一些註釋,
註4:第四個注意事項,
註5:第五個音符,
註3:第三個註釋。

答案1

這是一個概念證明,但以這種方式使用輔助文件是非常危險的,因為錯誤可能會破壞先前的副本,並且筆記的順序也會丟失。因此,備份.notes檔案的例程必須在 LaTeX 作業結束時執行。

\documentclass{article}

\makeatletter
\newwrite\jjdbout
\newcounter{jjdbnotes}
\def\countnotes#1#2{\stepcounter{jjdbnotes}}
\def\savenote#1#2{%
  \expandafter\gdef\csname #1\endcsname{#2}%
  \addnote{#1}{#2}%
}
\makeatletter
\def\addnote#1#2{%
  \toks@=\expandafter{\jjdbnotes}%
  \xdef\jjdbnotes{\the\toks@^^J%
    \noexpand\jjdbnote{#1}{#2}}%
}
\makeatother
\let\jjdbnote\countnotes
\InputIfFileExists{\jobname.notes}{}{}
\let\jjdbnote\savenote
\gdef\jjdbnotes{} % initialize
\InputIfFileExists{\jobname.notes}{}{}

\newcommand{\mynote}[1]{%
  \par
  \ifcsname\pdfmdfivesum{#1}\endcsname
    \textbf{Note \csname\pdfmdfivesum{#1}\endcsname: }#1%
  \else
    \stepcounter{jjdbnotes}%
    \expandafter\addnote{\pdfmdfivesum{#1}}{\thejjdbnotes}%
    \textbf{Note \thejjdbnotes: }#1%
  \fi
}
\AtEndDocument{
  \immediate\openout\jjdbout=\jobname.notes
  \immediate\write\jjdbout{\unexpanded\expandafter{\jjdbnotes}}
}

\begin{document}
  \mynote{Some note I've added first},
  \mynote{A fourth note},
  \mynote{A second note},
  \mynote{A fifth note},
  \mynote{A third note}.

\end{document}

文件.notes被讀取兩次;第一個用於計算條目數,第二個用於為行指定含義。

每個註釋都儲存為其 MD5 校驗和,該校驗和應與文字唯一關聯。當然,如果註釋文字發生更改,順序將再次遺失。

因此,每個校驗和都會分配註釋編號。如果在運行期間我們發現一個新註釋,它將被添加到巨集中,其內容將在作業結束時\jjdbnotes寫出到文件中。.notes請注意,TeX 無法將行追加到現有檔案中。

顯示的輸出是透過按照規定的順序逐行取消註釋而獲得的。

在此輸入影像描述

更好的方法是將筆記儲存在單獨的文件中,notes.tex格式為

\makeatletter
\newcommand{\savenote}[2]{\@namedef{jjdb@note#2}{#1}}
\newcommand{\mynote}[1]{\@nameuse{jjdb@note#1}}
\makeatother

\savenote{Some note I've added first}{1}
\savenote{A second note}{2}
\savenote{A third note}{3}
\savenote{A fourth note}{4}
\savenote{A fifth note}{5}

\input{notes}並在序言中執行。然後在文件中你可以使用

\mynote{1},
\mynote{4},
\mynote{2},
\mynote{5},
\mynote{3}.

透過這種方式,您只需按順序添加註釋即可。

答案2

我認為你想要的正是 LaTeX 中的交叉引用對你沒有幫助的情況:對它們進行硬編碼就足夠了。如果您想格式化(粗體等),您可以使用description環境,或建立自己的命令,例如:

\newcommand{\mynote}[1]{\par\noindent\bfseries Note#1}

並使用

\mynote{1} some text
\mynote{3} some other text

編輯:根據其他使用者的建議,新增 '\write command in\mynote` 以獲得類似以下內容:

\documentclass{article}
\begin{document}
\newwrite\notenumber
\immediate\openout\notenumber=note.dat
\newcommand{\mynote}[1]{%
           \immediate\write\notenumber{#1}\par\noindent\bfseries Note~#1:}
\mynote{3} the note number 3
\mynote{1} the note number 1
\end{document}

然後,您可以在文字編輯器中對它們進行排序,或者在 LaTeX 中使用以下答案對它們進行排序:這個問題

相關內容