Skip to content

Commit

Permalink
feat(core): Extend SU.collatedSort for complex table sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
Omikhleia authored and Didier Willis committed Sep 10, 2024
1 parent 8bed2e6 commit 104a39c
Show file tree
Hide file tree
Showing 53 changed files with 349,356 additions and 6 deletions.
28 changes: 23 additions & 5 deletions core/utilities/sorting.lua
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
--- Table sorting with language-dependent collation.
-- @module SU.sorting
--

local icu = require("justenoughicu")

local collatedSort = {
-- No ICU for language "und", fallback to 'natural' table.sort
und = function (t, _)
table.sort(t)
und = function (t, _, comparator)
if comparator then
table.sort(t, function (e1, e2)
return comparator(e1, e2, function (s1, s2)
return s1 < s2 and -1 or s1 > s2 and 1 or 0
end)
end)
else
table.sort(t)
end
end,
}

setmetatable(collatedSort, {
__call = function (self, t, options)
__call = function (self, t, options, comparator)
local lang = SILE.settings:get("document.language")
if self[lang] and type(self[lang]) == "function" then
-- Allow overriding ICU for some languages, typically "und"
return self[lang](t, options)
return self[lang](t, options, comparator)
end

if self[lang] and type(self[lang]) == "table" then
Expand All @@ -25,8 +34,17 @@ setmetatable(collatedSort, {
-- Be efficient: create the collator once before sorting.
-- I don't think we need to cache it, still.
local collator = icu.collation_create(lang, options or {})
table.sort(t, function (s1, s2)

local stringCompareClosure = function (s1, s2)
return icu.compare(collator, s1, s2)
end
table.sort(t, function (e1, e2)
-- Allow custom comparison function, notably for complex objects
-- Pass the stringCompare function so that it can be used.
if comparator then
return comparator(e1, e2, stringCompareClosure)
end
return stringCompareClosure(e1, e2) < 0
end)
icu.collation_destroy(collator)
end,
Expand Down
Loading

0 comments on commit 104a39c

Please sign in to comment.