Module:Theosophist authors

From Teopedia

Documentation for this module may be created at Module:Theosophist authors/doc

local p = {}
local FS, RS, AS = mw.ustring.char(0x2063), mw.ustring.char(0x2064), mw.ustring.char(0x2062)

local function split(s, sep)
    local out, start = {}, 1
    while true do
        local a, b = string.find(s, sep, start, true)
        if not a then table.insert(out, string.sub(s, start)); return out end
        table.insert(out, string.sub(s, start, a - 1)); start = b + 1
    end
end

local function trim(s) return mw.text.trim(s or '') end

-- Legacy records sometimes separate linked coauthors with commas rather than
-- the property's semicolon separator. Never split commas inside a page name.
local function authors(value)
    local out = {}
    for _, part in ipairs(split(value, AS)) do
        if part:find('[[', 1, true) then
            local start = 1
            while true do
                local a, b = part:find('%[%[[^]]+%]%]', start)
                local rest = part:sub(start, a and a - 1 or #part)
                rest = trim(rest:gsub('^[%s,;]+', ''):gsub('[%s,;]+$', ''))
                if rest ~= '' and rest ~= 'and' then table.insert(out, rest) end
                if not a then break end
                table.insert(out, part:sub(a, b))
                start = b + 1
            end
        else
            table.insert(out, part)
        end
    end
    return out
end

local function fetch(frame)
    local rows, offset = {}, 0
    for batch = 1, 100 do
        local query = '{{#ask:[[Theosophist item ID::+]]'
            .. '|?Theosophist item author=a|+sep=' .. AS
            .. '|?Theosophist item ID=id|?Theosophist item title=t'
            .. '|?Theosophist item volume=v|?Theosophist item number=n|?Theosophist item page=pg'
            .. '|?Theosophist item month=m|?Theosophist item year=y'
            .. '|?Theosophist item links to text=links|+sep=; '
            .. '|?Theosophist item author signed=as'
            .. '|mainlabel=-|link=none|headers=hide|named args=yes'
            .. '|format=template|template=Theosophist authors raw row'
            .. '|sort=Theosophist item ID|order=asc|searchlabel=|limit=500|offset=' .. offset .. '}}'
        local text = frame:preprocess(query):gsub('%[%[SMW::off%]%]', ''):gsub('%[%[SMW::on%]%]', '')
        local count = 0
        for _, record in ipairs(split(text, RS)) do
            local f = split(record, FS)
            if #f == 10 and trim(f[2]) ~= '' then
                table.insert(rows, {a=trim(f[1]), id=f[2], t=f[3], v=f[4], n=f[5], pg=f[6],
                                    m=f[7], y=f[8], links=f[9], as=trim(f[10])})
                count = count + 1
            end
        end
        if count == 0 then return rows end
        offset = offset + count
    end
    error('Theosophist author index exceeds the pagination safety limit.')
end

-- keyfn (необязательна) возвращает строку, по которой группировать запись;
-- по умолчанию группируем по полю author.
local function group(rows, keyfn)
    local map, order = {}, {}
    for _, r in ipairs(rows) do
        local seen = {}
        for _, raw in ipairs(authors(keyfn and keyfn(r) or r.a)) do
            raw = trim(raw)
            local target = raw:match('^%[%[([^]|]+)|[^]]+%]%]$') or raw:match('^%[%[([^]]+)%]%]$')
            local name = trim(target or raw)
            if name ~= '' and not seen[name] then
                seen[name] = true
                if not map[name] then
                    map[name] = {target=target, label=raw, items={}}
                    table.insert(order, name)
                end
                table.insert(map[name].items, r)
            end
        end
    end
    table.sort(order, function(a,b) return mw.ustring.lower(a) < mw.ustring.lower(b) end)
    return map, order
end

-- Запись оглавления ссылается на выпуск, а не на отдельную строку:
-- якоря nN создаёт {{Theosophist number}} на странице оглавления тома.
local function location(r)
    local details = 'vol. ' .. r.v .. ', no. ' .. r.n .. ', ' .. r.m .. ' ' .. r.y .. ', pp. ' .. r.pg
    if not r.pg:find('-', 1, true) then details = details:gsub(', pp%. ', ', p. ') end
    return '[[Theosophist/Vol' .. r.v .. '#n' .. r.n .. '|' .. details .. ']]'
end

local function entry(r)
    local links = trim(r.links) ~= '' and ('; ' .. r.links) or ''
    return '<li><i>' .. r.t .. '</i> <span style="color:grey; font-size:85%;">('
        .. location(r) .. ')' .. links .. '</span></li>'
end

-- Три состояния авторства записи оглавления:
--   author -- установленное имя: ссылка на карточку словаря, или же простой
--     текст, если карточки ещё нет;
--   author signed -- печатная подпись, буквально как напечатана (под
--     заголовком или в конце материала);
--   author signed = UNSIGNED -- материал напечатан без всякой подписи. Помета
--     в квадратных скобках -- не печатный текст, а утверждение редакции, как
--     и описательные заголовки в квадратных скобках.
local UNSIGNED = '[unsigned]'

local function has_card(value)
    return value:find('[[', 1, true) ~= nil
end

-- Строка, по которой материал опознаётся, когда карточки автора нет:
-- печатная подпись, а если её нет -- простой текст поля author.
local function signature(r)
    local as = trim(r.as)
    if as ~= '' and as ~= UNSIGNED then return as end
    local a = trim(r.a)
    if a ~= '' and not has_card(a) then return a end
    return ''
end

local function select_rows(frame, kind)
    local out = {}
    for _, r in ipairs(fetch(frame)) do
        if kind == 'carded' and has_card(trim(r.a)) then
            table.insert(out, r)
        elseif kind == 'signature' and not has_card(trim(r.a)) and signature(r) ~= '' then
            table.insert(out, r)
        elseif kind == 'unsigned' and trim(r.as) == UNSIGNED then
            table.insert(out, r)
        end
    end
    return out
end

function p.list(frame)
    local map, order = group(select_rows(frame, 'carded'))
    local out = {}
    for _, name in ipairs(order) do
        local author = map[name]
        local label = author.label
        if author.target then
            label = frame:expandTemplate{title='CTD show name', args={[1]=author.target, mode='full LF'}}
            label = '[[' .. author.target .. '|' .. label .. ']]'
        end
        table.insert(out, '<h3>' .. label .. '</h3>\n<ol>')
        table.sort(author.items, function(a,b)
            if a.t == b.t then return a.id < b.id end
            return mw.ustring.lower(a.t) < mw.ustring.lower(b.t)
        end)
        for _, r in ipairs(author.items) do
            table.insert(out, entry(r))
        end
        table.insert(out, '</ol>')
    end
    return table.concat(out, '\n')
end

-- Подписи, псевдонимы, инициалы и описательные обозначения, за которыми не
-- стоит лица с карточкой словаря: подпись есть, но она ничего не
-- устанавливает. Группируются так же, как авторы с карточками.
function p.unidentified(frame)
    local map, order = group(select_rows(frame, 'signature'), signature)
    local out = {}
    for _, name in ipairs(order) do
        local author = map[name]
        table.insert(out, '<h3>' .. author.label .. '</h3>\n<ol>')
        table.sort(author.items, function(a, b)
            if a.t == b.t then return a.id < b.id end
            return mw.ustring.lower(a.t) < mw.ustring.lower(b.t)
        end)
        for _, r in ipairs(author.items) do
            table.insert(out, entry(r))
        end
        table.insert(out, '</ol>')
    end
    return table.concat(out, '\n')
end

-- Материал, напечатанный без всякой подписи (author signed = UNSIGNED),
-- независимо от того, установлен ли автор из других источников.
-- Группируется по томам, внутри тома -- по ID, то есть по выпускам и страницам.
function p.unsigned(frame)
    local rows = select_rows(frame, 'unsigned')
    table.sort(rows, function(a, b) return a.id < b.id end)
    local out, current = {}, nil
    for _, r in ipairs(rows) do
        if r.v ~= current then
            if current then table.insert(out, '</ol>') end
            current = r.v
            table.insert(out, '<h3>Volume ' .. r.v .. '</h3>\n<ol>')
        end
        table.insert(out, entry(r))
    end
    if current then table.insert(out, '</ol>') end
    return table.concat(out, '\n')
end

function p.debug(frame)
    local rows = fetch(frame)
    local carded, signed, unsigned, blank = 0, 0, 0, 0
    for _, r in ipairs(rows) do
        if has_card(trim(r.a)) then carded = carded + 1 end
        if not has_card(trim(r.a)) and signature(r) ~= '' then signed = signed + 1 end
        if trim(r.as) == UNSIGNED then unsigned = unsigned + 1 end
        if trim(r.a) == '' and trim(r.as) == '' then blank = blank + 1 end
    end
    return 'Total contents entries: ' .. #rows .. '; with a dictionary entry: ' .. carded
        .. '; signature without an entry: ' .. signed .. '; marked unsigned: ' .. unsigned
        .. '; neither author nor signature recorded: ' .. blank
end

return p