Debian Codegraph @

texmf-dist/tex/lualatex/luaoptions/luaoptions.lua

raw
1 -- luacheck: ignore ly warn info log self luatexbase internalversion font fonts tex token kpse status
2 local err, warn, info, log = luatexbase.provides_module({
3 name = "luaoptions",
4 version = '0.9', --LUAOPTIONS_VERSION
5 date = "2026/05/20", --LUAOPTIONS_DATE
6 description = "Module luaoptions.",
7 author = "The lualatex-tools Project",
8 copyright = "2015-2026 - the lualatex-tools Project",
9 license = "MIT",
10 })
11
12 --[[
13 This module provides functionality to handle package options and make them
14 configurable in a fine-grained fashion as
15 - package options
16 - local options (for individual instances of commands/environments)
17 - changed “from here on” within a document.
18
19 -- ]]
20
21 local lib = require(kpse.find_file("luaoptions-lib.lua") or "luaoptions-lib.lua")
22 local optlib = {} -- namespace for the returned table
23 local Opts = {options = {}} -- Options class
24 Opts.__index = function (self, k) return self.options[k] or rawget(Opts, k) end
25 setmetatable(Opts, Opts)
26 local clients = {}
27
28 function Opts:new(declarations)
29 --[[
30 Declare an options object along with default and accepted values.
31 To *some* extent also provide type checking.
32 - declarations: a definition table stored in the calling module (see below)
33 Each entry in the 'declarations' table represents one package option, with each
34 value being an array (table with integer indexes instead of keys). For
35 details please refer to the manual.
36 --]]
37 local o = setmetatable(
38 {
39 declarations = declarations,
40 options = {}
41 },
42 self
43 )
44 for k, v in pairs(declarations) do
45 o.options[k] = v[1] or ''
46 end
47 return o
48 end
49
50 function Opts:check_local_options(opts, ignore_declarations)
51 --[[
52 Parse the given options (options passed to a command/environment),
53 sanitize them against the global package options and return a table
54 with the local options that should then supersede the global options.
55 If ignore_declaration is given any non-false value the sanitization
56 step is skipped (i.e. local options are only parsed and duplicates
57 rejected).
58 --]]
59 local options = {}
60 local next_opt = opts:gmatch('([^,]+)') -- iterator over options
61 for opt in next_opt do
62 local k, v = opt:match('([^=]+)=?(.*)')
63 if k then
64 if v and v:sub(1, 1) == '{' then -- handle keys with {multiple, values}
65 while select(2, v:gsub('{', '')) ~= select(2, v:gsub('}', '')) do v = v..','..next_opt() end
66 v = v:sub(2, -2) -- remove { }
67 end
68 if not ignore_declarations then
69 k, v = self:sanitize_option(k:gsub('^%s', ''), v:gsub('^%s', ''))
70 end
71 if k then
72 if options[k] then err('Option %s is set two times for the same score.', k)
73 else options[k] = v
74 end
75 end
76 end
77 end
78 return options
79 end
80
81 function Opts:has_option(name)
82 --[[
83 Returns true if the given option is declared
84 --]]
85 return self.declarations[name] ~= nil
86 end
87
88 function Opts:is_neg(k)
89 --[[
90 Type check for a 'negative' option. This is an existing option
91 name prefixed with 'no' (e.g. 'noalign')
92 --]]
93 local _, i = k:find('^no')
94 return i and lib.contains_key(self.declarations, k:sub(i + 1))
95 end
96
97 function Opts:sanitize_option(k, v)
98 --[[
99 Check and (if necessary) adjust the value of a given option.
100 Reject undefined options
101 Check 'negative' options
102 Handle boolean options (empty strings or 'false'), set them to real booleans
103 --]]
104 local declarations = self.declarations
105 if k == '' or k == 'noarg' then return end
106 if not lib.contains_key(declarations, k) then err('Unknown option: '..k) end
107 -- aliases
108 if declarations[k] and declarations[k][2] == optlib.is_alias then
109 if declarations[k][1] == v then return
110 else k = declarations[k] end
111 end
112 -- boolean
113 if v == 'false' then v = false end
114 -- negation (for example, noindent is the negation of indent)
115 if self:is_neg(k) then
116 if v ~= nil and v ~= 'default' then
117 k = k:gsub('^no(.*)', '%1')
118 v = not v
119 else return
120 end
121 end
122 return k, v
123 end
124
125 function Opts:set_option(k, v)
126 --[[
127 Set an option for the given prefix to be in effect from this point on.
128 Raises an error if the option is not declared or does not meet the
129 declared expectations. (TODO: The latter has to be integrated by extracting
130 optlib.validate_option from optlib.validate_options and call it in
131 sanitize_option).
132 --]]
133 k, v = self:sanitize_option(k, v)
134 if k then
135 self.options[k] = v
136 self:validate_option(k)
137 end
138 end
139
140 function Opts:use_option(key)
141 --[[
142 Call an option and write its value to the TeX space.
143 This is a shorthand for accessing options from the TeX side
144 (rather than having to write tex.print(XX_opts.some_options))
145 --]]
146 local option = self.options[key]
147 if option then
148 tex.print(option:explode('\n'))
149 else
150 err(string.format("Trying to access non-existent option %s", key))
151 end
152 end
153
154 function Opts:validate_option(key, options_obj)
155 --[[
156 Validate an (already sanitized) option against its expected values.
157 With options_obj a local options table can be provided,
158 otherwise the global options stored in OPTIONS are checked.
159 --]]
160 local package_opts = self.declarations
161 local options = options_obj or self.options
162 local unexpected
163 if options[key] == 'default' then
164 -- Replace 'default' with an actual value
165 options[key] = package_opts[key][1]
166 unexpected = options[key] == nil
167 end
168 if not lib.contains(package_opts[key], options[key]) and package_opts[key][2] then
169 -- option value is not in the array of accepted values
170 if type(package_opts[key][2]) == 'function' then package_opts[key][2](key, options[key])
171 else unexpected = true
172 end
173 end
174 if unexpected then
175 err([[
176 Unexpected value "%s" for option %s:
177 authorized values are "%s"
178 ]],
179 options[key], key, table.concat(package_opts[key], ', ')
180 )
181 end
182 end
183
184 function Opts:validate_options(options_obj)
185 --[[
186 Validate the given set of options against the option declaration
187 table for the given prefix.
188 With options_obj a local options table can be provided,
189 otherwise the global options stored in OPTIONS are checked.
190 --]]
191 for k, _ in lib.orderedpairs(self.declarations) do
192 self:validate_option(k, options_obj)
193 end
194 end
195
196
197 function optlib.is_alias()
198 --[[
199 This function doesn't do anything, but if an option is defined
200 as an alias, its second parameter will be this function, so the
201 test declarations[k][2] == optlib.is_alias in Opts:sanitize_options
202 will return true.
203 --]]
204 end
205
206
207 function optlib.is_dim(k, v)
208 --[[
209 Type checking for options that accept a LaTeX dimension.
210 This can be
211 - a number (integer or float)
212 - a number with unit
213 - a (multiplied) TeX length
214 (see error message in code for examples)
215 --]]
216 if v == '' or v == false or tonumber(v) then return true end
217 local n, sl, u = v:match('^%d*%.?%d*'), v:match('\\'), v:match('%a+')
218 -- a value of number - backslash - length is a dimension
219 -- invalid input will be prevented in by the LaTeX parser already
220 if n and sl and u then return true end
221 if n and lib.contains(lib.TEX_UNITS, u) then return true end
222 err([[
223 Unexpected value "%s" for dimension %s:
224 should be either a number (for example "12"),
225 a number with unit, without space ("12pt"),
226 or a (multiplied) TeX length (".8\linewidth")
227 ]],
228 v, k
229 )
230 end
231
232
233 function optlib.is_neg(k, _)
234 --[[
235 Type check for a 'negative' option. At this stage,
236 we only check that it begins with 'no'.
237 --]]
238 return k:find('^no')
239 end
240
241
242 function optlib.is_num(_, v)
243 --[[
244 Type check for number options
245 --]]
246 return v == '' or tonumber(v)
247 end
248
249
250 function optlib.is_str(_, v)
251 --[[
252 Type check for string options
253 --]]
254 return type(v) == 'string'
255 end
256
257
258 function optlib.merge_options(base_opt, super_opt)
259 --[[
260 Merge two tables.
261 Create a new table as a copy of base_opt, then merge with
262 super_opt. Entries in super_opt supersede (i.e. overwrite)
263 colliding entries in base_opt.
264 --]]
265 local result = {}
266 for k, v in pairs(base_opt) do result[k] = v end
267 for k, v in pairs(super_opt) do result[k] = v end
268 return result
269 end
270
271 function optlib.register(client_name, declarations)
272 --[[
273 Register a client as package options.
274 - Create a new Opts object,
275 - initialize it,
276 - store it in a global variable <client_name>_opts,
277 - write the code to handle the package options.
278 --]]
279 local o = Opts:new(declarations)
280 local exopt = ''
281 for k, v in pairs(declarations) do
282 tex.sprint(string.format([[
283 \DeclareOptionX{%s}{\setluaoption{%s}{%s}{#1}}%%
284 ]],
285 k, client_name, k
286 ))
287 exopt = exopt..k..'='..(v[1] or '')..','
288 end
289 clients[client_name] = o
290 tex.sprint([[\ExecuteOptionsX{]]..exopt..[[}%%]], [[\ProcessOptionsX]])
291 end
292
293 function optlib.client(name)
294 --[[
295 Return the FormattersTable instance registered with the given client name.
296 Return 'nil' if no client is found.
297 --]]
298 return clients[name]
299 end
300
301 function optlib.get_option(client_name, k)
302 --[[
303 Get an option's value from a registered client.
304 Raises an error if the client hasn't been registered.
305 --]]
306 local client = optlib.client(client_name)
307 return client.options[k]
308 end
309
310 function optlib.set_option(client_name, k, v)
311 --[[
312 Set an option.
313 Look up a registered client and set an option.
314 Produces an error if the client hasn't been registered.
315 --]]
316 local client = optlib.client(client_name)
317 client:set_option(k, v)
318 end
319
320 function optlib.use_option(client_name, k)
321 --[[
322 Look up an option and write it to LaTex.
323 --]]
324 local client = optlib.client(client_name)
325 client:use_option(k)
326 end
327
328 optlib.Opts = Opts
329 return optlib