# [Tex/LaTex] How to code an auto-increment counter in LaTeX

programming

When typesetting letters is common practice to have a reference such as:

   XXX-yl-0001


Where the last number is incremented for each successive letter. Normally, I hand-code the number. When having hundreds of letters one tends to now and then make mistakes and duplicate or miss references.

Can someone propose a method to automate this with TeX? Important is to only increment once for each run, i.e., you don't want the counter to increment if you re-run the file. Please note I am out of inspiration for a MWE.

My suggestion, is probably one needs two files. The first one to totalize and a local per jobname to keep the specific letter reference.

Here is a ConTeXt based solution. It uses datasets, which is the ConTeXt mechanism for multi-pass data. The basic idea is to store the MD5sum of the file and the count of the letter in the auxiliary file. At each run compare the stored value of MD5sum with the current value. If the md5sum has changed, increment the number and store it in the auxiliary file. Of course, if you delete the auxiliary file, the number is reset to zero. (For simplicity, I assume that the file suffix is always .tex)

\definedataset[letterdata]

\startluacode
local datasets = job.datasets
local filename = environment.inputfilename .. '.tex' -- temp hack
local checksum = file.checksum(filename)

local set = "letterdata"

datasets.setdata{
name = set,
data = { checksum = checksum }
}

local oldsum  = datasets.getdata(set, 1, "checksum", "")
local number  = datasets.getdata(set, 2, "number", 0)

if oldsum ~= checksum then
number = tonumber(number) + 1
end

datasets.setdata{
name = set,
data = { number = number }
}

context.setvalue("letternumber", number)
\stopluacode

\starttext

Value: \letternumber

\stoptext


This will increment the number whenever you change the file and recompile. Recompiling the same file will not increment the number.