Plugins and Language Packs for Family Historian

Find duplicate persons by name and facts.fh_lua

--[[
@Title: Find duplicate persons by name and facts
@Type: standard
@Author: Torleif Haugødegård
@Contributors:
@Version: 1.0
@LastUpdated: 16 November 2026
@Licence: This plugin is copyright (c) 2026 Torleif Haugødegård and is licensed under the MIT License which is hereby incorporated by reference (see https://pluginstore.family-historian.co.uk/fh-plugin-licence)
@Description: Searches for possible duplicate individuals. Choose all surnames or one surname; compare given names (any in common, first given name, at least two, or ignore); optionally require a given name in common for the father or mother; and compare fact dates (ignore, exact dates, exact years, or years within a chosen interval of 1 to 20), with or without minor facts. The interface is available in Norwegian and UK English. Results are shown in the Result Set window.
]]

require("iuplua")
iup.SetGlobal("CUSTOMQUITMESSAGE", "YES")
-- FH passes strings as UTF-8 when this file is UTF-8 (with BOM). IUP must be
-- told so, otherwise æ, ø and å are shown incorrectly in the dialogs.
if fhGetContextInfo("CI_STRING_ENCODING") == "UTF-8" then
  iup.SetGlobal("UTF8MODE", "YES")
end

----------------------------------------------------------------------
-- Texts (Norwegian "no" and UK English "en")
----------------------------------------------------------------------
local TXT = {
  en = {
    title      = "Find duplicate persons by name and facts",
    lblSurnMode= "Surname search method:",
    s1         = "1) All surnames",
    s2         = "2) One selected surname",
    lblSurname = "Surname (used with method 2):",
    lblName    = "Given name comparison method:",
    n1         = "1) At least one given name is the same",
    n2         = "2) First given name is the same",
    n3         = "3) At least two given names are the same",
    n4         = "4) Do not compare given names",
    lblParent  = "Require a given name in common for father or mother?",
    yes        = "Yes",
    no         = "No",
    lblFact    = "Fact comparison method:",
    f1         = "1) Ignore facts",
    f2         = "2) Dates exactly the same",
    f3         = "3) Years exactly the same",
    f4         = "4) Years within an interval",
    lblInterval= "Interval: +/- years (1 to 20), used with method 4:",
    lblMinor   = "Also consider minor facts (occupation, residence, etc.)?",
    ok         = "Search",
    cancel     = "Cancel",
    badInterval= "The interval must be a whole number from 1 to 20.",
    noSurnames = "No individuals with a surname were found.",
    none       = "No possible duplicates were found.",
    tooMany    = "The search stopped after %d pairs. Narrow the search (for example choose one surname or a stricter method) to see all matches.",
    colNo      = "Pair",
    colId      = "ID",
    colGiven   = "Name (surname first)",
    colSur     = "Surname",
    colBirth   = "Birth",
    colId1     = "ID 1",
    colId2     = "ID 2",
    colP1      = "Given names 1",
    colS1      = "Surname 1",
    colP2      = "Given names 2",
    colS2      = "Surname 2",
    colB1      = "Birth 1",
    colB2      = "Birth 2",
    colNames   = "Matching given names",
    colFacts   = "Matching facts",
    resTitle   = "Possible duplicate individuals",
    sumHeading = "Search summary",
    sumSurnames= "Surnames",
    sumAllSurn = "all surnames",
    sumOneSurn = "one surname: %s",
    sumNames   = "Given names",
    sumParents = "Parent given name in common",
    sumFacts   = "Facts",
    sumInterval= "+/- %d years",
    sumMinor   = "Minor facts considered",
    sumFound   = "Possible duplicate pairs found",
    parents    = "parents",
    ignored    = "(ignored)",
    factNames  = { BIRT="Birth", CHR="Christening", BAPM="Baptism", MARR="Marriage",
                   DEAT="Death", BURI="Burial", CREM="Cremation" },
  },
  no = {
    title      = "Finn duplikate personer etter navn og fakta",
    lblSurnMode= "Søkemetode for etternavn:",
    s1         = "1) Alle etternavn",
    s2         = "2) Ett valgt etternavn",
    lblSurname = "Etternavn (brukes med metode 2):",
    lblName    = "Metode for sammenligning av fornavn:",
    n1         = "1) Minst ett fornavn er likt",
    n2         = "2) Første fornavn er likt",
    n3         = "3) Minst to fornavn er like",
    n4         = "4) Ikke vurdere fornavn",
    lblParent  = "Kreve at et fornavn til far eller mor er likt?",
    yes        = "Ja",
    no         = "Nei",
    lblFact    = "Metode for sammenligning av fakta:",
    f1         = "1) Ignorere fakta",
    f2         = "2) Datoer eksakt like",
    f3         = "3) År eksakt like",
    f4         = "4) År innenfor et intervall",
    lblInterval= "Intervall: +/- år (1 til 20), brukes med metode 4:",
    lblMinor   = "Vurdere mindre vesentlige fakta (yrke, bosted osv.)?",
    ok         = "Søk",
    cancel     = "Avbryt",
    badInterval= "Intervallet må være et heltall fra 1 til 20.",
    noSurnames = "Fant ingen personer med etternavn.",
    none       = "Fant ingen mulige duplikater.",
    tooMany    = "Søket stoppet etter %d par. Avgrens søket (for eksempel velg ett etternavn eller en strengere metode) for å se alle treff.",
    colNo      = "Par",
    colId      = "ID",
    colGiven   = "Navn (etternavn først)",
    colSur     = "Etternavn",
    colBirth   = "Født",
    colId1     = "ID 1",
    colId2     = "ID 2",
    colP1      = "Fornavn 1",
    colS1      = "Etternavn 1",
    colP2      = "Fornavn 2",
    colS2      = "Etternavn 2",
    colB1      = "Født 1",
    colB2      = "Født 2",
    colNames   = "Like fornavn",
    colFacts   = "Like fakta",
    resTitle   = "Mulige duplikate personer",
    sumHeading = "Sammendrag av søket",
    sumSurnames= "Etternavn",
    sumAllSurn = "alle etternavn",
    sumOneSurn = "ett etternavn: %s",
    sumNames   = "Fornavn",
    sumParents = "Fornavn til forelder likt",
    sumFacts   = "Fakta",
    sumInterval= "+/- %d år",
    sumMinor   = "Mindre vesentlige fakta vurdert",
    sumFound   = "Mulige duplikatpar funnet",
    parents    = "foreldre",
    ignored    = "(ignorert)",
    factNames  = { BIRT="Fødsel", CHR="Dåp (CHR)", BAPM="Dåp (BAPM)", MARR="Vielse",
                   DEAT="Død", BURI="Begravelse", CREM="Kremasjon" },
  },
}
local S = TXT.en

local PARENT_HWND = fhGetContextInfo("CI_PARENT_HWND")
local IS_UTF8 = (fhGetContextInfo("CI_STRING_ENCODING") == "UTF-8")
local MAXPAIRS = 50000

-- "Major" facts: normally occur once per person, so a different date
-- counts as a conflict. All other dated facts are "minor": they can only
-- add matches, never conflicts (people have many residences, censuses, etc.)
local MAJOR = { BIRT = true, CHR = true, BAPM = true, MARR = true,
                DEAT = true, BURI = true, CREM = true }

-- Items below an individual that are not facts
local SKIP = { NAME = true, SEX = true, FAMC = true, FAMS = true,
               NOTE = true, SOUR = true, OBJE = true, _FLGS = true,
               _UID = true, CHAN = true, RIN = true, REFN = true,
               ALIA = true, ASSO = true }

----------------------------------------------------------------------
-- Text helpers
----------------------------------------------------------------------
local UPPER_LOWER = {
  { "\195\134", "\195\166" }, -- Æ -> æ
  { "\195\152", "\195\184" }, -- Ø -> ø
  { "\195\133", "\195\165" }, -- Å -> å
  { "\195\132", "\195\164" }, -- Ä -> ä
  { "\195\150", "\195\182" }, -- Ö -> ö
  { "\195\156", "\195\188" }, -- Ü -> ü
  { "\195\137", "\195\169" }, -- É -> é
}

local function fold(s)
  s = s or ""
  if IS_UTF8 then
    for _, p in ipairs(UPPER_LOWER) do
      s = string.gsub(s, p[1], p[2])
    end
  end
  -- ASCII only: string.lower can change UTF-8 bytes in some locales
  s = string.gsub(s, "[A-Z]", function(c) return string.char(string.byte(c) + 32) end)
  return s
end

local function trim(s)
  s = string.gsub(s or "", "^%s+", "")
  s = string.gsub(s, "%s+$", "")
  return s
end

-- Sort key giving Norwegian alphabetical order (a-z, then æ, ø, å; "aa" = å).
-- Input must already be folded to lower case.
local function sortKey(k)
  k = string.gsub(k, "aa", "{3") -- "aa" sorts as å
  if IS_UTF8 then
    k = string.gsub(k, "\195\166", "{1") -- æ
    k = string.gsub(k, "\195\164", "{1") -- ä sorts as æ
    k = string.gsub(k, "\195\184", "{2") -- ø
    k = string.gsub(k, "\195\182", "{2") -- ö sorts as ø
    k = string.gsub(k, "\195\165", "{3") -- å
    k = string.gsub(k, "\195\188", "y")  -- ü sorts as y
    k = string.gsub(k, "\195[\168\169]", "e") -- è é
    k = string.gsub(k, "[\128-\255]", "|") -- anything else: after the letters
  end
  return k
end

-- Plain byte-by-byte comparison. Lua's "<" on strings uses the Windows
-- locale (strcoll), which puts UTF-8 letters such as Ø and Å before A.
local function bytesLess(a, b)
  local la, lb = #a, #b
  local m = math.min(la, lb)
  for i = 1, m do
    local x, y = string.byte(a, i), string.byte(b, i)
    if x ~= y then return x < y end
  end
  return la < lb
end

local function getText(ptr, ref)
  local ok, v = pcall(fhGetItemText, ptr, ref)
  if ok and v then return v end
  return ""
end

local function splitNames(s)
  local list, set, orig = {}, {}, {}
  s = string.gsub(s or "", "[%.,%(%)\"']", " ")
  for w in string.gmatch(s, "%S+") do
    local key = fold(w)
    if not set[key] then
      set[key] = true
      orig[key] = w
      list[#list + 1] = key
    end
  end
  return { list = list, set = set, orig = orig }
end

-- Names in a that also occur in b, in a's original spelling
local function commonNames(a, b)
  local out = {}
  for _, w in ipairs(a.list) do
    if b.set[w] then out[#out + 1] = a.orig[w] end
  end
  return out
end

----------------------------------------------------------------------
-- Dialogs
----------------------------------------------------------------------
local function askLanguage()
  local lst = iup.list{ "Norsk", "English (UK)";
                        dropdown = "YES", value = 2, expand = "HORIZONTAL" }
  local btnOK = iup.button{ title = "OK", size = "60x" }
  local btnCancel = iup.button{ title = "Cancel / Avbryt", size = "90x" }
  local result = nil

  local dlg = iup.dialog{
    iup.vbox{
      iup.label{ title = "Language / Språk:" }, lst,
      iup.hbox{ iup.fill{}, btnOK, btnCancel; gap = 10, margin = "0x10" };
      margin = "10x10", gap = 5,
    };
    title = "Find duplicate persons by name and facts",
    size = "240x",
    defaultenter = btnOK,
    defaultesc = btnCancel,
  }
  iup.SetAttribute(dlg, "NATIVEPARENT", PARENT_HWND)

  function btnOK:action()
    if tonumber(lst.value) == 1 then result = "no" else result = "en" end
    return iup.CLOSE
  end
  function btnCancel:action() return iup.CLOSE end

  fhUpdateDisplay()
  iup.Popup(dlg)
  iup.Destroy(dlg)
  return result
end

local function askOptions(surnameLabels)
  local lstSurnMode = iup.list{ S.s1, S.s2;
                                dropdown = "YES", value = 1, expand = "HORIZONTAL" }

  local items = {}
  for i, lab in ipairs(surnameLabels) do items[i] = lab end
  items.dropdown = "YES"
  items.value = 1
  items.visible_items = 20   -- rows shown when the dropdown opens (default is 5)
  items.visiblelines = 20
  items.expand = "HORIZONTAL"
  local lstSurname = iup.list(items)
  lstSurname.active = "NO"

  local lstName = iup.list{ S.n1, S.n2, S.n3, S.n4;
                            dropdown = "YES", value = 2, expand = "HORIZONTAL" }
  local lstParent = iup.list{ S.no, S.yes;
                              dropdown = "YES", value = 1, expand = "HORIZONTAL" }

  local lstFact = iup.list{ S.f1, S.f2, S.f3, S.f4;
                            dropdown = "YES", value = 3, expand = "HORIZONTAL" }
  local txtInterval = iup.text{ value = "2", size = "40x" }
  txtInterval.active = "NO"
  local lstMinor = iup.list{ S.no, S.yes;
                             dropdown = "YES", value = 1, expand = "HORIZONTAL" }

  local btnOK = iup.button{ title = S.ok, size = "60x" }
  local btnCancel = iup.button{ title = S.cancel, size = "60x" }
  local result = nil

  local function updateEnabled()
    lstSurname.active = (tonumber(lstSurnMode.value) == 2) and "YES" or "NO"
    local fm = tonumber(lstFact.value)
    txtInterval.active = (fm == 4) and "YES" or "NO"
    lstMinor.active = (fm ~= 1) and "YES" or "NO"
  end

  function lstSurnMode:action(text, item, state)
    if state == 1 then updateEnabled() end
  end
  function lstFact:action(text, item, state)
    if state == 1 then updateEnabled() end
  end
  updateEnabled()

  local dlg = iup.dialog{
    iup.vbox{
      iup.label{ title = S.lblSurnMode }, lstSurnMode,
      iup.label{ title = S.lblSurname }, lstSurname,
      iup.label{ title = S.lblName }, lstName,
      iup.label{ title = S.lblParent }, lstParent,
      iup.label{ title = S.lblFact }, lstFact,
      iup.label{ title = S.lblInterval }, txtInterval,
      iup.label{ title = S.lblMinor }, lstMinor,
      iup.hbox{ iup.fill{}, btnOK, btnCancel; gap = 10, margin = "0x10" };
      margin = "10x10", gap = 4,
    };
    title = S.title,
    size = "320x",
    defaultenter = btnOK,
    defaultesc = btnCancel,
  }
  iup.SetAttribute(dlg, "NATIVEPARENT", PARENT_HWND)

  function btnOK:action()
    local factMode = tonumber(lstFact.value)
    local interval = nil
    if factMode == 4 then
      interval = tonumber(trim(txtInterval.value))
      if interval == nil or interval ~= math.floor(interval)
         or interval < 1 or interval > 20 then
        fhMessageBox(S.badInterval, "MB_OK", "MB_ICONEXCLAMATION", dlg.HWND)
        return iup.DEFAULT
      end
    end
    result = {
      surnameMode  = tonumber(lstSurnMode.value),
      surnameIndex = tonumber(lstSurname.value),
      nameMode     = tonumber(lstName.value),
      parentReq    = (tonumber(lstParent.value) == 2),
      factMode     = factMode,
      interval     = interval,
      minor        = (factMode ~= 1) and (tonumber(lstMinor.value) == 2),
    }
    return iup.CLOSE
  end
  function btnCancel:action() return iup.CLOSE end

  fhUpdateDisplay()
  iup.Popup(dlg)
  iup.Destroy(dlg)
  return result
end

----------------------------------------------------------------------
-- Main
----------------------------------------------------------------------
local lang = askLanguage()
if lang == nil then return end
S = TXT[lang]

-- 1. Group all individuals by surname
local groups, order = {}, {}
do
  local ptr = fhNewItemPtr()
  ptr:MoveToFirstRecord("INDI")
  while ptr:IsNotNull() do
    local raw = trim(getText(ptr, "~.NAME:SURNAME"))
    if raw ~= "" then
      local key = fold(raw)
      local g = groups[key]
      if g == nil then
        g = { display = raw, list = {} }
        groups[key] = g
        order[#order + 1] = key
      end
      g.list[#g.list + 1] = ptr:Clone()
    end
    ptr:MoveNext()
  end
end

if #order == 0 then
  fhMessageBox(S.noSurnames, "MB_OK", "MB_ICONINFORMATION")
  return
end

local sortKeyOf = {}
for _, key in ipairs(order) do sortKeyOf[key] = sortKey(key) end
table.sort(order, function(x, y) return bytesLess(sortKeyOf[x], sortKeyOf[y]) end)
local labels = {}
for i, key in ipairs(order) do
  labels[i] = groups[key].display .. " (" .. #groups[key].list .. ")"
end

local opt = askOptions(labels)
if opt == nil then return end

-- Surname keys to search
local searchKeys = {}
if opt.surnameMode == 2 then
  searchKeys[1] = order[opt.surnameIndex]
else
  searchKeys = order
end

-- 2. Person data
-- Builds one entry for a fact: its date (if any), value and place.
-- Returns nil for a fact that carries no information at all.
local function makeEntry(factPtr)
  local entry = { date = "", year = nil, value = "", place = "" }
  local longDate = getText(factPtr, "~.DATE:LONG")
  if longDate ~= "" then
    entry.date = fold(longDate)
    entry.year = tonumber(getText(factPtr, "~.DATE:YEAR"))
    if entry.year == nil then
      entry.year = tonumber(string.match(longDate, "%d%d%d%d"))
    end
  end
  local okv, v = pcall(fhGetValueAsText, factPtr)
  if okv and type(v) == "string" then
    v = fold(trim(v))
    if v ~= "y" then entry.value = v end   -- "Y" is just an "occurred" flag
  end
  entry.place = fold(trim(getText(factPtr, "~.PLAC")))
  if entry.date == "" and entry.value == "" and entry.place == "" then
    return nil
  end
  return entry
end

local function addEntry(facts, tag, entry)
  if entry == nil then return end
  local list = facts[tag]
  if list == nil then
    list = {}
    facts[tag] = list
  end
  list[#list + 1] = entry
end

-- Facts of the individual, including facts without a date, and the
-- marriages (MARR) held in the families the individual is a spouse in.
local function readFacts(indiPtr)
  local facts = {}
  local child = fhNewItemPtr()
  child:MoveToFirstChildItem(indiPtr)
  while child:IsNotNull() do
    local tag = fhGetTag(child)
    if tag == "FAMS" then
      local fam = fhGetValueAsLink(child)
      if fam ~= nil and fam:IsNotNull() then
        local m = fhNewItemPtr()
        m:MoveToFirstChildItem(fam)
        while m:IsNotNull() do
          if fhGetTag(m) == "MARR" then
            addEntry(facts, "MARR", makeEntry(m))
          end
          m:MoveNext()
        end
      end
    elseif not SKIP[tag] and (MAJOR[tag] or opt.minor) then
      addEntry(facts, tag, makeEntry(child))
    end
    child:MoveNext()
  end
  return facts
end

local function buildPerson(ptr)
  local p = {
    ptr    = ptr,
    given  = splitNames(getText(ptr, "~.NAME:GIVEN_ALL")),
    sex    = getText(ptr, "~.SEX"),
    birth  = getText(ptr, "~.BIRT.DATE"),
  }
  if opt.parentReq then
    p.father = splitNames(getText(ptr, "~.FAMC>HUSB>NAME:GIVEN_ALL"))
    p.mother = splitNames(getText(ptr, "~.FAMC>WIFE>NAME:GIVEN_ALL"))
  end
  if opt.factMode ~= 1 then
    p.facts = readFacts(ptr)
  end
  return p
end

-- 3. Comparison rules
local function givenNamesMatch(a, b)
  local common = commonNames(a.given, b.given)
  if opt.nameMode == 1 then
    return #common >= 1, common
  elseif opt.nameMode == 2 then
    local fa, fb = a.given.list[1], b.given.list[1]
    if fa ~= nil and fa == fb then return true, { a.given.orig[fa] } end
    return false, {}
  elseif opt.nameMode == 3 then
    return #common >= 2, common
  end
  return true, {}
end

local function parentsMatch(a, b)
  if #commonNames(a.father, b.father) > 0 then return true end
  if #commonNames(a.mother, b.mother) > 0 then return true end
  return false
end

local function datesMatch(x, y)
  if opt.factMode == 2 then
    return x.date == y.date
  elseif opt.factMode == 3 then
    return x.year ~= nil and x.year == y.year
  end
  return x.year ~= nil and y.year ~= nil
         and math.abs(x.year - y.year) <= opt.interval
end

-- Two facts of the same type match when both have a date and the dates
-- satisfy the chosen method. If one or both have no date, they match when
-- the fact value or the place is the same.
local function entriesMatch(x, y)
  if x.date ~= "" and y.date ~= "" then
    return datesMatch(x, y)
  end
  if x.value ~= "" and x.value == y.value then return true end
  if x.place ~= "" and x.place == y.place then return true end
  return false
end

-- Accepted when at least one fact type matches and no major fact conflicts.
-- A conflict is a major fact (birth, christening, baptism, death, burial,
-- cremation, marriage) where both persons have dated facts of that type but
-- none of them match.
local function factsMatch(a, b)
  local matched, conflict = {}, false
  for tag, listA in pairs(a.facts) do
    local listB = b.facts[tag]
    if listB ~= nil then
      local hit, bothDated = false, false
      for _, x in ipairs(listA) do
        for _, y in ipairs(listB) do
          if entriesMatch(x, y) then hit = true end
          if x.date ~= "" and y.date ~= "" then bothDated = true end
        end
      end
      if hit then
        matched[#matched + 1] = tag
      elseif MAJOR[tag] and bothDated then
        conflict = true
      end
    end
  end
  table.sort(matched)
  return (not conflict) and #matched > 0, matched
end

-- 4. Search
local colP1, colP2, colB1, colB2, colNames, colFacts = {}, {}, {}, {}, {}, {}
local n = 0
local truncated = false

for _, key in ipairs(searchKeys) do
  if truncated then break end
  local g = groups[key]
  local people = {}
  for i, ptr in ipairs(g.list) do
    people[i] = buildPerson(ptr)
  end
  table.sort(people, function(x, y)
    local kx = sortKey(table.concat(x.given.list, " "))
    local ky = sortKey(table.concat(y.given.list, " "))
    return bytesLess(kx, ky)
  end)

  for i = 1, #people - 1 do
    if truncated then break end
    local a = people[i]
    for j = i + 1, #people do
      local b = people[j]
      local ok = true

      if a.sex ~= "" and b.sex ~= "" and a.sex ~= b.sex then ok = false end

      local commonGiven = {}
      if ok then ok, commonGiven = givenNamesMatch(a, b) end

      if ok and opt.parentReq then ok = parentsMatch(a, b) end

      local matchedFacts = {}
      if ok and opt.factMode ~= 1 then
        ok, matchedFacts = factsMatch(a, b)
      end

      if ok then
        n = n + 1
        colP1[n] = a.ptr:Clone()
        colP2[n] = b.ptr:Clone()
        colB1[n] = a.birth
        colB2[n] = b.birth

        local nameText = table.concat(commonGiven, ", ")
        if opt.nameMode == 4 then nameText = S.ignored end
        if opt.parentReq then
          if nameText ~= "" then
            nameText = nameText .. " + " .. S.parents
          else
            nameText = S.parents
          end
        end
        colNames[n] = nameText

        local labelsF = {}
        for _, tag in ipairs(matchedFacts) do
          labelsF[#labelsF + 1] = S.factNames[tag] or tag
        end
        if opt.factMode == 1 then
          colFacts[n] = S.ignored
        else
          colFacts[n] = table.concat(labelsF, ", ")
        end

        if n >= MAXPAIRS then
          truncated = true
          break
        end
      end
    end
  end
end

-- 5. Output

-- Summary of the chosen search options, as {label, value} pairs
local function buildSummary()
  local surn
  if opt.surnameMode == 2 then
    surn = string.format(S.sumOneSurn, groups[order[opt.surnameIndex]].display)
  else
    surn = S.sumAllSurn
  end
  local nameMethods = { S.n1, S.n2, S.n3, S.n4 }
  local factMethods = { S.f1, S.f2, S.f3, S.f4 }
  local facts = factMethods[opt.factMode]
  if opt.factMode == 4 then
    facts = facts .. " (" .. string.format(S.sumInterval, opt.interval) .. ")"
  end
  local pairsList = {
    { S.sumSurnames, surn },
    { S.sumNames, nameMethods[opt.nameMode] },
    { S.sumParents, opt.parentReq and S.yes or S.no },
    { S.sumFacts, facts },
  }
  if opt.factMode ~= 1 then
    pairsList[#pairsList + 1] = { S.sumMinor, opt.minor and S.yes or S.no }
  end
  pairsList[#pairsList + 1] = { S.sumFound, tostring(n) }
  return pairsList
end
local summary = buildSummary()
local summaryLines = {}
for _, p in ipairs(summary) do
  summaryLines[#summaryLines + 1] = p[1] .. ": " .. p[2]
end
local summaryText = S.sumHeading .. ":\n\n" .. table.concat(summaryLines, "\n")

if n == 0 then
  fhMessageBox(S.none .. "\n\n" .. summaryText, "MB_OK", "MB_ICONINFORMATION")
  return
end

if truncated then
  fhMessageBox(string.format(S.tooMany, MAXPAIRS), "MB_OK", "MB_ICONEXCLAMATION")
end

-- "Surname, Given names" so that the column reads and sorts by surname.
local function nameText(ptr)
  return trim(getText(ptr, "~.NAME:SURNAME_FIRST"))
end

-- Each pair is written as two rows in the same columns: person 1 on the
-- first row and person 2 directly below. The pair number is repeated on both
-- rows; the matching given names and facts are shown on the first row only.
-- Pairs are listed by surname (alphabetical), then by given names.
local cNo, cId, cName, cBirth, cNames, cFacts, cPtr =
  {}, {}, {}, {}, {}, {}, {}
for i = 1, n do
  for k = 1, 2 do
    local r = 2 * (i - 1) + k
    local ptr, birth
    if k == 1 then ptr, birth = colP1[i], colB1[i]
    else ptr, birth = colP2[i], colB2[i] end
    cNo[r]    = i
    cId[r]    = fhGetRecordId(ptr)
    cName[r]  = nameText(ptr)
    cBirth[r] = birth
    cNames[r] = (k == 1) and colNames[i] or ""
    cFacts[r] = (k == 1) and colFacts[i] or ""
    cPtr[r]   = ptr
  end
end
local rows = 2 * n

-- Widths are in quarter-characters (24 = about 5-6 characters).
-- The name column is followed by a hidden "buddy" item column, so that
-- double-clicking a name still opens that individual.
fhOutputResultSetColumn(S.colNo, "integer", cNo, rows, 24, "align_right", 0)
fhOutputResultSetColumn(S.colId, "integer", cId, rows, 36, "align_right", 0)
fhOutputResultSetColumn(S.colGiven, "text", cName, rows, 140, "align_left")
fhOutputResultSetColumn("", "item", cPtr, rows, 0, "align_left", 0, true, "default", "buddy")
fhOutputResultSetColumn(S.colBirth, "text", cBirth, rows, 80, "align_left")
fhOutputResultSetColumn(S.colNames, "text", cNames, rows, 60, "align_left")
fhOutputResultSetColumn(S.colFacts, "text", cFacts, rows, 80, "align_left")
-- Summary: label and value columns to the right, on the first rows only.
-- If there are fewer rows than summary lines, the last rows are merged.
local cSumLabel, cSumValue = {}, {}
for r = 1, rows do
  cSumLabel[r], cSumValue[r] = "", ""
end
for i, p in ipairs(summary) do
  local r = math.min(i, rows)
  if i > rows then
    cSumLabel[r] = cSumLabel[r] .. "; " .. p[1]
    cSumValue[r] = cSumValue[r] .. "; " .. p[2]
  else
    cSumLabel[r], cSumValue[r] = p[1], p[2]
  end
end
fhOutputResultSetColumn(S.sumHeading, "text", cSumLabel, rows, 130, "align_left")
fhOutputResultSetColumn("", "text", cSumValue, rows, 160, "align_left")

fhOutputResultSetTitles(S.resTitle .. " (" .. n .. ")",
  S.resTitle .. " (" .. n .. ")", table.concat(summaryLines, "  |  "))

Source: Find-duplicate-persons-by-name-and-facts.fh_lua