Module:Auto compact TOC

require('strict')local p = {}local horizontal = require('Module:List').horizontallocal start = [[__NOTOC__<div id="toc" class="toc plainlinks" role="navigation" aria-labelledby="mw-toc-heading"><div class="toctitle"><h2 id="mw-toc-heading">Contents</h2></div>]]local close = [[</div>]]local function make_TOC_item(anchor, link_text)link_text = link_text or anchorreturn ("[[#%s|%s]]"):format(anchor, link_text)endlocal Array_mt = { __index = table }local function Array()return setmetatable({}, Array_mt)endfunction p.make_TOC(frame)local content = mw.title.getCurrentTitle():getContent()if not content thenerror "The current page has no content"endlocal letters = Array()-- Find uppermost headers containing a single ASCII letter.for letter in content:gmatch "%f[^\n]==%s*(%a)%s*==%f[^=]" doletter = letter:upper()letters:insert(make_TOC_item(letter))endlocal yesno = require('Module:Yesno')local rest = Array()local other_headers = require('Module:TableTools').listToSet{"See also", "References", "Notes", "Further reading", "External links",}for header in content:gmatch "%f[^\n]==%s*(..-)%s*==%f[^=]" doif other_headers[header] thenrest:insert(make_TOC_item(header))endendreturn start .. horizontal(letters) .. horizontal(rest) .. closeendreturn p