Debian Codegraph @

texk/texlive/linked_scripts/luafindfont/luafindfont.lua

raw symbols SCIP
1 #!/usr/bin/env texlua
2 --
3 -- $Id: luafindfont.lua 1117 2025-07-04 09:32:59Z herbert $
4 -----------------------------------------------------------------------
5 -- FILE: luafindfont.lua
6 -- DESCRIPTION: search for fonts in the database
7 -- REQUIREMENTS: luatex v.0.80 or later; packages lualibs, xindex-lapp
8 -- AUTHOR: Herbert Voß (C) 2025-07-04
9 -----------------------------------------------------------------------
10 luafindfont = luafindfont or { }
11 local version = 0.16
12 luafindfont.version = version
13
14 --[[
15 Search the font database for fontnames. The database is used
16 by Lua(La)TeX and created by default with the first run of
17 Lua(La)TeX. If there is no such data file then "luafindfont"
18 will execute the command to create it.
19
20 luafindfont(1)
21
22 %% This file may be distributed and/or modified under the
23 %% conditions of the LaTeX Project Public License, either version 1.3c
24 %% of this license or (at your option) any later version.
25 %% The latest version of this license is in
26 %% http://www.latex-project.org/lppl.txt
27 %% and version 1.3c or later is part of all distributions of LaTeX
28 %% version 2005/12/01 or later.
29
30 Report bugs to [email protected]
31
32 ]]
33
34 -- equivilant with ConTeXt, e.g. times
35 -- mtxrun --script font --list --name --all --pattern=times
36
37 kpse.set_program_name("luatex")
38 local f = kpse.find_file("lualibs.lua")
39
40 require("lualibs") -- all part of LuaTeX
41
42 if #arg == 0 then
43 print("I need at least one argument or option! Will exit ...")
44 os.exit()
45 end
46
47 local args_verbose = 0
48 local args_nosymbolicnames = false
49 local args_otfinfo = 0
50 local args_info = 0
51 local args_listonly = 0
52 local args_xetex = 0
53 local args_max_string = 90
54
55 local otfinfo_arg = ""
56 local mtxrun = 0
57 local fontNo = 0
58
59 local i = 1
60 while i <= #arg do
61 if arg[i] == "-h" or arg[i] == "--help" then
62 print("Version "..version..", Copyright 2021-25 by Herbert Voß")
63 print([[Syntax: luafindfont [options] <font>
64 By default the Lua program 'luafindfont' creates a list of the
65 fonts which have in its names the given string.
66
67 parameter handling
68 -h,--help
69 -n,--nosymbolicnames
70 ,--no-symbolic-names
71 -o,--otfinfo (default 0)
72 -i,--info (default 0)
73 -I,--Info (default 0)
74 -l, --listonlynames
75 -L, --listonlyfiles
76 -x, --xetex
77 -v, --verbose
78 -V, --version
79 -m,--max_string (default 90)
80 <font> (string) ]])
81 elseif arg[i] == "-V" or arg[i] == "--version" then
82 print("version "..version)
83 os.exit()
84 elseif arg[i] == "-v" or arg[i] == "--verbose" then
85 args_verbose = 1
86 elseif (arg[i] == "-n") or (arg[i] == "--nosymbolicnames") or (arg[i] == "--no-symbolic-names") then
87 args_nosymbolicnames = true
88 elseif arg[i] == "-l" or arg[i] == "--listonlynames" then
89 args_listonly = 1
90 elseif arg[i] == "-L" or arg[i] == "--listonlyfiles" then
91 args_listonly = 2
92 elseif arg[i] == "-x" or arg[i] == "--xetex" then
93 args_xetex = 1
94 elseif arg[i] == "-o" or arg[i] == "--otfinfo" then
95 local o_arg = arg[i+1]
96 otfinfo_arg = "i"
97 fontNo = tonumber(o_arg)
98 if not fontNo then -- combination: No and Arg
99 fontNo = tonumber(string.match(o_arg,"%d+"))
100 otfinfo_arg = string.match(o_arg,"%a+")
101 if not fontNo then
102 print("Option -o needs a following fontnumber!")
103 fontNo = 0
104 end
105 end
106 i = i + 1
107 elseif arg[i] == "-i" or arg[i] == "--info" then
108 local fontNr = tonumber(arg[i+1])
109 if fontNr then
110 args_info = fontNr
111 i = i + 1
112 else
113 print("Option -i needs a following fontnumber!")
114 args_info = 0
115 end
116 elseif arg[i] == "-I" or arg[i] == "--Info" then
117 mtxrun = 1
118 local I_arg = arg[i+1]
119 fontNo = tonumber(I_arg)
120 if not fontNo then
121 print("Option -I needs a following fontnumber!")
122 fontNo = 0
123 end
124 i = i + 1
125 elseif arg[i] == "-m" or arg[i] == "--max_string" then
126 local string_len = tonumber(arg[i+1])
127 if string_len then
128 args_max_string = string_len
129 i = i + 1
130 else
131 print("Option -m needs a following fontnumber!")
132 args_max_string = 90
133 end
134 else
135 args_font = arg[i]:lower()
136 end
137 i = i + 1
138 end
139
140 local vlevel = args_verbose
141
142 function logprint(str)
143 if vlevel > 0 then print(str) end
144 end
145
146 if vlevel > 0 then
147 print("Parameter:")
148 print(" args_verbose = "..args_verbose)
149 print(" args_nosymbolicnames = "..tostring(args_nosymbolicnames))
150 print(" args_xetex = "..args_xetex)
151 print(" otfinfo_arg = "..otfinfo_arg)
152 print(" fontNo = "..fontNo)
153 print(" args_max_string = "..args_max_string)
154 end
155
156 if not args_font and args_listonly < 1 then
157 print("No fontname given, will close ...")
158 os.exit()
159 end
160
161 --local otfinfo = args_otfinfo
162 local info = args_info
163 local Info = args_Info
164 local noSymbolicNames = args_nosymbolicnames
165 local maxStrLength = args_max_string
166 local font_str = {}
167 if args_listonly < 1 then
168 font_str = args_font:gsub("%s+", ""):split("&")
169 end
170 if #font_str == 1 then font_str[2] = "" end -- a & b
171
172 local luaVersion = _VERSION
173 if vlevel > 0 then
174 print("We are using "..luaVersion)
175 if font_str[2] ~= "" then
176 print('Looking for font \"'..font_str[1]..' & '..font_str[2]..'\"')
177 else
178 print('Looking for font \"'..font_str[1]..'\"')
179 end
180 end
181
182 function getFileParts(fullpath,part)
183 local path, file, ext = string.match(fullpath, "(.-)([^/]-([^%.]+))$")
184 if part == "path" then return path
185 elseif part == "ext" then return ext
186 else return file end
187 end
188
189 -- for fileparts see also file fontloader-l-file.lua in /luaotfload
190
191 function getFileLocation()
192 local cachepaths = kpse.expand_var('$TEXMFCACHE') or ""
193 if cachepaths == "" or cachepaths == "$TEXMFCACHE" then
194 cachepaths = kpse.expand_var('$TEXMFVAR') or ""
195 end
196 logprint("cachepaths: "..cachepaths)
197 if cachepaths == "" then
198 print("umghhh ....")
199 print("No cache path found ... ")
200 return ""
201 end
202 local windows = (os.type == "windows")
203 if windows then logprint ("System: Windows")
204 else logprint ("System: macOS or Linux")
205 end
206 if windows then
207 paths = string.split(cachepaths,";")
208 else
209 paths = string.split(cachepaths,":")
210 end
211 logprint ("Paths: [1]"..paths[1])
212 if #paths > 1 then
213 logprint(" [2]"..paths[2])
214 end
215 local file = paths[1].."/luatex-cache/generic/names"
216 logprint("try path: "..file)
217 local f,err = io.open (file.."/test.tmp", "w")
218 if not f and #paths > 1 then
219 logprint("first path has no file, I'll try the second one, if exists ...")
220 file = paths[2].."/luatex-cache/generic/names"
221 logprint("try path: "..file)
222 f,err = io.open (file.."/test.tmp", "w")
223 if not f then
224 print("Error getting file location: \n",err)
225 return ""
226 else
227 f:close()
228 end
229 else
230 f:close()
231 end
232 -- print("File: "..fontListFile)
233 return file
234 end
235
236 function readBinaryOrZippedFile(file)
237 logprint("Check for file "..file..".luc.gz")
238 local f,err = io.open (file..".luc.gz", "rb")
239 if f then
240 logprint("Found a zipped binary data file ... ")
241 local chunk = gzip.decompress(f:read"*all")
242 f:close()
243 local func = load (chunk, "b")
244 str = func()
245 logprint("Loaded a chunk ... ")
246 return str
247 else
248 logprint("There is no zipped binary data file ... ")
249 end
250 logprint("Check for unzipped file "..file..".luc")
251 local f,err = io.open (file..".luc", "rb")
252 if f then
253 logprint("Found a binary data file ... ")
254 local chunk = f:read"*all"
255 f:close()
256 local func = load (chunk, "b")
257 str = func()
258 return str
259 end
260 logprint("There is no binary data file ... ")
261 logprint("Check for zipped file "..file..".lua.gz")
262 f,err = io.open (file..".lua.gz", "rb")
263 if f then
264 logprint("Found a gzipped data file ... ")
265 local str = f:read("*all")
266 local str2 = loadstring(gzip.decompress(str))
267 str = str2()
268 f:close()
269 return str
270 end
271 logprint("There is no gzipped data file ... ")
272 logprint("Check for file "..file..".lua")
273 f,err = io.open (file..".lua", "r")
274 if f then
275 logprint("Found a normal data file ... ")
276 local str = dofile(f)
277 f:close()
278 return str
279 else
280 logprint("There is no data file ... ")
281 print("Error reading file: ",err)
282 return nil
283 end
284 end
285
286 function compareEntries(f1, f2)
287 if (f1["basename"] == f2["basename"]) and
288 (f1["familyname"] == f2["familyname"]) and
289 (f1["fullpath"] == f2["fullpath"]) then
290 return true
291 else
292 return false
293 end
294 end
295
296 function centerText(text, width)
297 if text == nil then return "" end
298 local spaces = math.floor((width-string.len(text))/2)
299 local len = string.len(text)
300 return ((" "):rep(spaces)..text..(" "):rep(spaces))
301 end
302
303 local fontData = {}
304 local fontListFile = getFileLocation()
305 if fontListFile == "" then
306 print("There is no cached font file list!")
307 print('Will run at first "luaotfload-tool --update --force" ... Wait a minute, please ...')
308 local exrun = io.popen('luaotfload-tool --update --force', 'r')
309 local output = exrun:read('*all')
310 print(output)
311 exrun:close()
312 fontListFile = getFileLocation()
313 end
314
315 fontListFile = fontListFile.."/luaotfload-names"
316 fontData = readBinaryOrZippedFile(fontListFile)
317
318 if not fontData then
319 print("umghhh ....")
320 print("It does not work! I cannote find the base data file ... I'll give it up ... :-(")
321 os.exit()
322 end
323
324 if vlevel > 0 then
325 print(require 'xindex-pretty'.dump(fontData)) --["families"]["system"]["otf"]))
326 end
327
328 if args_listonly == 1 then
329 local tmp = {}
330 for _,font in ipairs(fontData.mappings) do
331 tmp[#tmp + 1] = font.fontname --.. " (" .. font.basename .. ")"
332 end
333 table.sort(tmp)
334 for _,fontname in ipairs(tmp) do
335 print(fontname)
336 end
337 os.exit()
338 elseif args_listonly == 2 then
339 local tmp = {}
340 for _,font in ipairs(fontData.mappings) do
341 tmp[#tmp + 1] = font.basename
342 end
343 table.sort(tmp)
344 for _,filename in ipairs(tmp) do
345 print(filename)
346 end
347 os.exit()
348 end
349
350
351 fontDataMap = fontData["mappings"]
352 fontFilesTable = fontData["files"]["full"]
353
354 --print(require 'xindex-pretty'.dump(fontFilesTable)) --["families"]["system"]["otf"]))
355 --print(require 'xindex-pretty'.dump(fontFilesTable["bare"]["system"]["otf"])) --["families"]["system"]["otf"]))
356
357 --[[
358 print("Dateiliste für System->OTF")
359 for i, v in ipairs(fontFilesTable) do
360 print(i,v)
361 end
362 ]]
363
364 table.sort(fontDataMap,
365 function(a,b)
366 if not a["basename"] or not b["basename"] then
367 return false
368 else
369 return string.lower(a["basename"]) < string.lower(b["basename"])
370 end
371 end)
372
373 -- strip duplicates
374 local newFontDataMap = {}
375 if #fontDataMap > 0 then
376 newFontDataMap[1] = fontDataMap[1]
377 end
378 for i = 2,#fontDataMap do
379 if not compareEntries(fontDataMap[i],newFontDataMap[#newFontDataMap]) then
380 newFontDataMap[#newFontDataMap+1] = fontDataMap[i]
381 end
382 end
383
384 fontDataMap = newFontDataMap
385 --for i, v in ipairs(fontDataMap) do
386 -- print(i, v["basename"],v["familyname"], v["fullpath"])
387 -- end
388
389 local j = 1
390 local printFont = 0
391 local fontList = {}
392 -- now calculate the longest string for all colums
393 local l_max = {1, 1, 1}
394 for i, v in ipairs(fontDataMap) do
395 if v["basename"] and v["familyname"] then
396 -- print(string.format("%2d. %30s %20s %50s",j,v["basename"],v["familyname"],v["fullpath"]))
397 if font_str[2] ~= "" then
398 if (( string.find (v["familyname"]:lower(), font_str[1], 1, true) -- symbolic name
399 or
400 string.find (v["basename"]:lower(), font_str[1], 1, true) -- file name
401 )
402 and
403 string.find (v["subfamily"]:lower(), font_str[2], 1, true) -- file name
404 )
405 or (font_str[1] == "*") then
406 printFont = 1
407 end
408 else
409 if string.find (v["familyname"]:lower(), font_str[1], 1, true)
410 or
411 string.find (v["basename"]:lower(), font_str[1], 1, true)
412 or
413 (font_str[1] == "*") then
414 printFont = 1
415 end
416 end
417 if printFont>0 then
418 print(string.format("%2d. %30s %20s %50s",j,v["basename"],v["familyname"],v["fullpath"]))
419 fontList[#fontList+1] = v
420 local fullpath = getFileParts(v["fullpath"],"path") -- strip file name
421 local basename = v["basename"]
422 -- local basename = string.fromutf8(v["basename"])
423 if string.len(basename) > l_max[1] then l_max[1] = string.len(basename) end
424 if string.len(v["familyname"]) > l_max[2] then l_max[2] = string.len(v["familyname"]) end
425 if string.len(fullpath) > l_max[3] then l_max[3] = string.len(fullpath) end
426 j = j + 1
427 printFont = 0
428 -- if j > 100 then os.exit() end
429 end
430 end
431 end
432
433 os.exit()
434
435 if #fontList == 0 then
436 print("There are no fonts with the given search name!\n")
437 os.exit()
438 end
439
440
441 -- print(l_max[1],l_max[2],l_max[3])
442 if l_max[3] > maxStrLength then l_max[3] = maxStrLength end
443
444 local minChars = 26
445 local Fontname = "Filename"
446 local Path = "Path"
447 local SymbolicName = "Symbolic"
448 local lfdNr = "No."
449
450 if (font_str ~= "*") and not noSymbolicNames then
451 if args_xetex > 0 then
452 -- print(string.format("%5s %"..l_max[1].."s %"..l_max[2].."s %"..l_max[3].."s".."%4s",lfdNr,Fontname,SymbolicName,Path,"X"))
453 io.write(string.format("%5s",lfdNr))
454 io.write(centerText(Fontname,l_max[1]))
455 io.write(centerText(SymbolicName,l_max[2]))
456 io.write(centerText(Path,l_max[3]))
457 print("X")
458 else
459 -- print(string.format("%5s %"..l_max[1].."s %"..l_max[2].."s %"..l_max[3].."s",lfdNr,Fontname,SymbolicName,Path))
460 io.write(string.format("%5s",lfdNr))
461 io.write(centerText(Fontname,l_max[1]))
462 io.write(centerText(SymbolicName,l_max[2]))
463 print(centerText(Path,l_max[3]))
464 end
465 else
466 if args_xetex > 0 then
467 -- print(string.format("%5s %"..l_max[1].."s %"..l_max[3].."s".."%4s",lfdNr,Fontname,Path,"X"))
468 io.write(string.format("%5s",lfdNr))
469 io.write(centerText(Fontname,l_max[1]))
470 io.write(centerText(SymbolicName,l_max[2]))
471 io.write(centerText(Path,l_max[3]))
472 print("X")
473 else
474 -- print(string.format("%5s %"..l_max[1].."s %"..l_max[3].."s",lfdNr,Fontname,Path))
475 io.write(string.format("%5s",lfdNr))
476 io.write(centerText(Fontname,l_max[1]))
477 io.write(centerText(SymbolicName,l_max[2]))
478 print(centerText(Path,l_max[3]))
479 end
480 end
481
482 local kpsewhich = "0" -- test if font is present for xetex
483 for i, v in ipairs(fontList) do
484 local path = getFileParts(v["fullpath"],"path")
485 if string.len(path) > l_max[3] then
486 path = string.sub (path, 1, minChars).."..."..string.sub (path, string.len(path)-maxStrLength+minChars+4)
487 end
488 if args_xetex > 0 then
489 kpsewhich = "0"
490 local exrun = io.popen("kpsewhich "..v["basename"],'r')
491 if exrun then
492 if string.len(exrun:read('*all')) > 0 then
493 kpsewhich = "1"
494 end
495 else
496 print("!!! There maybe a problem with font "..v["basename"].." kpsewhich doesn't work")
497 print(tostring(exrun))
498 kpsewhich = "0"
499 os.exit()
500 end
501 exrun:close()
502 end
503 if (font_str ~= "*") and not noSymbolicNames then
504 if args_xetex > 0 then
505 print(string.format("%4d. %"..l_max[1].."s %"..l_max[2].."s %"..l_max[3].."s".." %3s",i,v["basename"],v["familyname"],path,kpsewhich))
506 else
507 print(string.format("%4d. %"..l_max[1].."s %"..l_max[2].."s %"..l_max[3].."s",i,v["basename"],v["familyname"],path))
508 end
509 else
510 if args_xetex > 0 then
511 print(string.format("%4d. %"..l_max[1].."s %"..l_max[3].."s".." %3s",i,v["basename"],path,kpsewhich))
512 else
513 print(string.format("%4d. %"..l_max[1].."s %"..l_max[3].."s",i,v["basename"],path))
514 end
515 end
516 end
517
518 if fontNo > 0 and mtxrun == 0 then
519 print()
520 if fontNo > #fontList then
521 print("given font number is greater than the number of the fontlist!")
522 else
523 print("Running otfinfo -"..otfinfo_arg.." on font no."..fontNo)
524 local font = fontList[fontNo]["fullpath"]
525 print("otfinfo -"..otfinfo_arg.." \""..font.."\"")
526 local exrun = io.popen("otfinfo -"..otfinfo_arg.." \""..font.."\"", 'r') -- ".." font may have spaces
527 local output = exrun:read('*all')
528 print(output)
529 exrun:close()
530 end
531 end
532
533 if info > 0 then
534 if info > #fontList then
535 print("given font number is greater than the number of the fontlist!")
536 else
537 font = fontList[info]["familyname"]
538 print("\nFont: "..font)
539 local font_dir = {"local","system","texmf"}
540 local font_ext = {"ttf","otf","ttc"}
541 for j = 1,#font_dir do
542 for i = 1,#font_ext do
543 local fonttype = ""
544 local ext = font_ext[i]
545 local dir = font_dir[j]
546 if fontData["families"][dir][ext] then -- font extension exists?
547 local entry = fontData["families"][dir][ext][font]
548 if entry then
549 if entry["r"] then fonttype = fonttype.."Regular " end
550 if entry["b"] then fonttype = fonttype.."| Bold " end
551 if entry["i"] then fonttype = fonttype.."| Italic " end
552 if entry["bi"] then fonttype = fonttype.."| BoldItalic" end
553 io.write("Fonttype "..ext.."("..dir..") --> ")
554 if #fonttype > 0 then
555 print("| "..fonttype.." |")
556 else
557 print(" undefined ") --- no regular definiert
558 end
559 else
560 print()
561 end
562 end
563 end
564 end
565 end
566 end
567
568 if mtxrun > 0 then
569 print()
570 print("Running mtxrun on font no."..fontNo)
571 -- local font = fontList[fontNo]["fullpath"]
572 local font = fontList[fontNo]["basename"]
573 print("mtxrun --script fonts --list --info --file \""..font.."\"")
574 local exrun = io.popen("mtxrun --script fonts --list --info --file \""..font.."\"", 'r') -- ".." font may have spaces
575 local output = exrun:read('*all')
576 print(output)
577 exrun:close()
578 end
579
580 --print(require 'xindex-pretty'.dump(fontData["families"]["system"]["otf"])) --["families"]["system"]["otf"]))
581
582
583 --[[
584
585 ["families"]={
586 ["local"]={},
587 ["system"]={
588 ["otf"]={
589 ["adobecaslonpro"]={
590 ["b"]={
591 ["default"]=3143,
592 },
593 ["bi"]={
594 ["default"]=3146,
595 },
596 ["i"]={
597 ["default"]=3145,
598 },
599 ["r"]={
600 ["default"]=3147,
601 },
602 },
603 },
604 },
605 },
606
607 ]]
608
609 --[[
610 This is a sketch of the luaotfload db:
611
612 type dbobj = {
613 families : familytable;
614 fontnames : fontnametable;
615 files : filemap;
616 status : filestatus;
617 mappings : fontentry list;
618 meta : metadata;
619 }
620 and familytable = {
621 local : (format, familyentry) hash; // specified with include dir
622 texmf : (format, familyentry) hash;
623 system : (format, familyentry) hash;
624 }
625 and familyentry = {
626 r : sizes; // regular
627 i : sizes; // italic
628 b : sizes; // bold
629 bi : sizes; // bold italic
630 }
631 and sizes = {
632 default : int; // points into mappings or names
633 optical : (int, int) list; // design size -> index entry
634 }
635 and fontnametable = {
636 local : (format, index) hash;
637 texmf : (format, index) hash;
638 system : (format, index) hash;
639 }
640 and metadata = {
641 created : string // creation time
642 formats : string list; // { "otf", "ttf", "ttc" }
643 local : bool; (* set if local fonts were added to the db *)
644 modified : string // modification time
645 statistics : TODO; // created when built with "--stats"
646 version : float; // index version
647 }
648 and filemap = { // created by generate_filedata()
649 base : {
650 local : (string, int) hash; // basename -> idx
651 system : (string, int) hash;
652 texmf : (string, int) hash;
653 };
654 bare : {
655 local : (string, (string, int) hash) hash; // location -> (barename -> idx)
656 system : (string, (string, int) hash) hash;
657 texmf : (string, (string, int) hash) hash;
658 };
659 full : (int, string) hash; // idx -> full path
660 }
661 and fontentry = { // finalized by collect_families()
662 basename : string; // file name without path "foo.otf"
663 conflicts : { barename : int; basename : int }; // filename conflict with font at index; happens with subfonts
664 familyname : string; // sanitized name of the font family the font belongs to, usually from the names table
665 fontname : string; // sanitized name of the font
666 format : string; // "otf" | "ttf" | "afm" (* | "pfb" *)
667 fullname : string; // sanitized full name of the font including style modifiers
668 fullpath : string; // path to font in filesystem
669 index : int; // index in the mappings table
670 italicangle : float; // italic angle; non-zero with oblique faces
671 location : string; // "texmf" | "system" | "local"
672 plainname : string; // unsanitized font name
673 typographicsubfamily : string; // sanitized preferred subfamily (names table 14)
674 psname : string; // PostScript name
675 size : (false | float * float * float); // if available, size info from the size table converted from decipoints
676 subfamily : string; // sanitized subfamily (names table 2)
677 subfont : (int | bool); // integer if font is part of a TrueType collection ("ttc")
678 version : string; // font version string
679 weight : int; // usWeightClass
680 }
681 and filestatus = (string, // fullname
682 { index : int list; // pointer into mappings
683 timestamp : int; }) dict
684 ]]