Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Module:Archive

Permanently protected module
From Wikipedia, the free encyclopedia
Module documentation[view] [edit] [history] [purge]
WarningThis Lua module is used onapproximately 333,000 pages.
To avoid major disruption and server load, any changes should be tested in the module's/sandbox or/testcases subpages, or in your ownmodule sandbox. The tested changes can be added to this page in a single edit. Consider discussing changes on thetalk page before implementing them.
Thismodule is rated asready for general use. It has reached a mature state, is considered relatively stable and bug-free, and may be used wherever appropriate. It can be mentioned onhelp pages and other Wikipedia resources as an option for new users. To minimise server load and avoid disruptive output, improvements should be developed throughsandbox testing rather than repeated trial-and-error editing.
Page template-protectedThis module is currentlyprotected from editing.
See theprotection policy andprotection log for more details. Please discuss any changes on thetalk page; you maysubmit an edit request to ask anadministrator to make an edit if it isuncontroversial or supported byconsensus. You may alsorequest that this page be unprotected.
This module depends on the following other modules:

This module produces a banner for talk archive pages. The module detects surrounding archives automatically and creates navigational links to them, hence the name.

Usage

This module is accessed via a template,Template:Archive. See the template page for documentation.

Dependencies

This module uses a configuration module atModule:Archive/config. It also usesModule:Highest archive number,Module:Arguments,Module:Yesno, andModule:Message box.

The abovedocumentation istranscluded fromModule:Archive/doc.(edit |history)
Editors can experiment in this module'ssandbox(edit |diff) and testcases(create) pages.
Subpages of this module.

---------------------------------------------------------------------------------                       Automatic archive navigator---- This module produces a talk archive banner, together with an automatically--- generated list of navigation links to other archives of the talk page in-- question. It implements {{Archive}}.-------------------------------------------------------------------------------localyesno=require('Module:Yesno')--------------------------------------------------------------------------------- Helper functions-------------------------------------------------------------------------------localfunctionmakeWikilink(page,display)ifdisplaythenreturnstring.format('[[%s|%s]]',page,display)elsereturnstring.format('[[%s]]',page)endendlocalfunctionescapePattern(s)-- Escape punctuation in a string so it can be used in a Lua pattern.s=s:gsub('%p','%%%0')returnsendlocalfunctionmakeTable(width)localarchiveTable=mw.html.create('table')archiveTable:css({['max-width']=width,['margin']='0 auto 0.5em',['text-align']='center'})-- Set width so that the table doesn't spill out on narrower skins-- or when zooming in. It has to be defined multiple times because-- "stretch" is experimental.:cssText('width:100%;width:-moz-available;width:-webkit-fill-available;width:stretch')returnarchiveTableend-- Check to see if the page is likely an annual archive. No talk pages exist-- before 2001. Some pages have the next year created in advance.localfunctionisYearlyArchive(num)localcurrentYear=tonumber(os.date("%Y"))returnnumandnum>=2001andnum<=currentYear+1-- possible yearsendlocalfunctiondetectArchiveFormat(title,args)-- Check if next/previous are set. Some archives swap between annual and-- sequential archives at some point and will need to accept whatever an-- editor says the next/previous link should be for these kind of weird-- or unsual orders.ifargsand(args.prevorargs.next)thenreturnnil,nil,nilend-- Check if "/Archive 2" exists to prevent false positives on noticeboardslocalarchiveBase=title.baseTextlocalarchive2Title=mw.title.new(archiveBase.."/Archive 2")ifarchive2Titleandarchive2Title.existsthenreturnnil,nil,nil-- Exit early for sequential archivesend-- How is the year formatted?localpatterns={{pattern="^(.-)/Archive (%d+)$",prefix=nil},-- "Talk:Base page/Archive YYYY"-- "nil" triggers the default. There is some kind of quirk with how-- the module give spaces that Template:Yearly archive list cannot-- read with either a space or the HTML space entity{pattern="^(.-)/Archive(%d+)$",prefix="/Archive"},-- "Talk:Base page/ArchiveYYYY"{pattern="^(.-)/Archive/(%d+)$",prefix="/Archive/"},-- "Talk:Base page/Archive/YYYY"{pattern="^(.-)/Archives/(%d+)$",prefix="/Archives/"},-- "Talk:Base page/Archives/YYYY"{pattern="^(.-)/(%d+)$",prefix="/"}-- "Talk:Base page/YYYY"}for_,pinipairs(patterns)dolocalbasePage,archiveNum=title.prefixedText:match(p.pattern)archiveNum=tonumber(archiveNum)ifbasePageandisYearlyArchive(archiveNum)thenreturnbasePage,true,p.prefixendendreturnnil,nil,nilend--------------------------------------------------------------------------------- Navigator class-------------------------------------------------------------------------------localNavigator={}Navigator.__index=NavigatorfunctionNavigator.new(args,cfg,currentTitle)localobj=setmetatable({},Navigator)-- Set inputsobj.args=argsobj.cfg=cfgobj.currentTitle=currentTitle-- Archive prefix-- Decode HTML entities so users can enter things like "Archive&#32;" from-- wikitext.obj.archivePrefix=obj.args.prefixorobj:message('archive-prefix')obj.archivePrefix=mw.text.decode(obj.archivePrefix)-- Current archive numberdolocalpattern=string.format('^%s([1-9][0-9]*)$',escapePattern(obj.archivePrefix))obj.currentArchiveNum=obj.currentTitle.subpageText:match(pattern)obj.currentArchiveNum=tonumber(obj.currentArchiveNum)end-- Highest archive numberobj.highestArchiveNum=require('Module:Highest archive number')._main(obj.currentTitle.nsText..':'..obj.currentTitle.baseText..'/'..obj.archivePrefix,obj.currentArchiveNum)returnobjendfunctionNavigator:message(key,...)localmsg=self.cfg[key]ifselect('#',...)>0thenreturnmw.message.newRawMessage(msg,...):plain()elsereturnmsgendendfunctionNavigator:getNamespacePreposition()-- Most talk archives are about a subject. Some will be "with" an editor-- or "on" a noticeboard.-- Function to get the namespace preposition-- Namespace number where transcludedlocalnamespaceNumber=mw.title.getCurrentTitle().namespace-- Preposition from table to make it easy for wikis to translate or ignorelocalnamespacePrepositionTable=self.cfg['namespace-prepositions']-- Default preposition if not exception from abovereturnnamespacePrepositionTable[namespaceNumber]orself.cfg["preposition-default"]endfunctionNavigator:makeBlurb()localargs=self.argslocalcurrent=self.currentTitlelocalret-- Skip if user provides their own blurb.ifargs.textthenret=args.textelse-- Set parent talk page.localparentTalkPage=current.basePageTitlelocaltalkPageTitlelocalpageUnderDiscussion-- If the parent talk page exists (and it's not the root talk page)-- we should link to it in both the "main talk page" and-- "discussions about" parts of the blurb.ifargs.prefixor(parentTalkPage.existsandparentTalkPage.isRedirect==falseandcurrent.baseText~=current.rootText)thentalkPageTitle=parentTalkPage.fullTextpageUnderDiscussion=talkPageTitle-- If it doesn't, set "main talk page" to the root talk page-- and "discussions about" to the root subject.elsetalkPageTitle=current.nsText..':'..parentTalkPage.rootText-- Set page under discussion.pageUnderDiscussion=current.subjectNsText..':'..current.rootText-- Prepend colon for non-mainspace pages.ifcurrent.subjectNsText~=''thenpageUnderDiscussion=':'..pageUnderDiscussionendend-- Check current namespace for blurb.localnamespace='main'ifcurrent.isTalkPage==truethennamespace='talk'end-- What kind of blurb to use in the message box?localfunctiongetBlurbKey(args)ifargs.type=='index'then-- For manually-indexed archives onlyreturn'blurb-index',args.typeelseifargs.type=='annual'then-- Grab the year of the current archive.return'blurb-annual',mw.getCurrentFrame():expandTemplate{title='Title year',args={page=current.fullText}}elseifargs.periodthenreturn'blurb-period',args.periodelsereturn'blurb-noperiod',''endend-- Generate a blurb from Module:Archive/configlocalblurbKey,argValue=getBlurbKey(args)localnamespacePreposition=self:getNamespacePreposition()ret=self:message(blurbKey,talkPageTitle,pageUnderDiscussion,argValue,namespace,namespacePreposition)endreturnretendfunctionNavigator:makeMessageBox()localargs=self.argslocalimageifargs.imagethenimage=args.imageelselocalicon=args.iconorself:message('default-icon')image=string.format('[[File:%s|%s|alt=|link=]]',icon,self:message('image-size'))end-- Hardcode tmbox style on the template's page.-- PS: Needs to be changed if the template is renamed!localmainTemplatePage=''ifself.currentTitle.fullText=='Template:Archive'thenmainTemplatePage='talk'endlocalmbox=require('Module:Message box').main('mbox',{demospace=args.demospaceormainTemplatePage,image=image,imageright=args.imageright,style=args.styleor'',textstyle=args.textstyleor'text-align:center',text=self:makeBlurb(),})returnmboxendfunctionNavigator:getArchiveNums()-- Returns an array of the archive numbers to format.localnoLinks=tonumber(self.args.links)orself:message('default-link-count')noLinks=math.floor(noLinks)-- If |noredlinks is "yes", true or absent, don't allow red links. If it is-- 'no' or false, allow red links.localallowRedLinks=yesno(self.args.noredlinks)==falselocalcurrent=self.currentArchiveNumlocalhighest=self.highestArchiveNumifnotcurrentornothighestornoLinks<1thenreturn{}elseifnoLinks==1thenreturn{current}endlocalfunctiongetNum(i,current)-- Gets an archive number given i, the position in the array away from-- the current archive, and the current archive number. The first two-- offsets are consecutive; the third offset is rounded up to the-- nearest 5; and the fourth and subsequent offsets are rounded up to-- the nearest 10. The offsets are calculated in such a way that archive-- numbers will not be duplicated.if-2<=iandi<=2thenreturncurrent+ielseif-3<=iandi<=3thenreturncurrent+2-(current+2)%5+(i/3)*5elseif4<=ithenreturncurrent+7-(current+7)%10+(i-3)*10elsereturncurrent+2-(current+2)%10+(i+3)*10endendlocalnums={}-- Archive nums lower than the current page.fori=-1,-math.floor((noLinks-1)/2),-1dolocalnum=getNum(i,current)ifnum<=1thentable.insert(nums,1,1)breakelsetable.insert(nums,1,num)endend-- Current page.ifnums[#nums]<currentthentable.insert(nums,current)end-- Higher archive nums.fori=1,math.ceil((noLinks-1)/2)dolocalnum=getNum(i,current)ifnum<=highestthentable.insert(nums,num)elseifallowRedLinksand(i<=2ori<=3andnum==nums[#nums]+1)then-- Only insert one red link, and only if it is consecutive.table.insert(nums,highest+1)breakelseifnums[#nums]<highestthen-- Insert the highest archive number if it isn't already there.table.insert(nums,highest)breakelsebreakendendreturnnumsendfunctionNavigator:makeArchiveLinksWikitable()localargs=self.argslocallang=mw.language.getContentLanguage()localnums=self:getArchiveNums()localnoLinks=#nums-- Skip number processing if |prev and |next are defined.ifargs.prevorargs.nextthenlocalarchives={}ifargs.prevthenarchives[#archives+1]=mw.title.new(args.prev)endarchives[#archives+1]=self.currentTitleifargs.nextthenarchives[#archives+1]=mw.title.new(args.next)endlocaltable=makeTable('30em')for_,titleinipairs(archives)doiftostring(title)==self.currentTitle.prefixedTextthentable:tag("td"):wikitext(string.format('<span style="font-size:115%%;">%s</span>',makeWikilink(title.fullText,title.subpageText)))elsetable:tag("td"):wikitext(makeWikilink(title.fullText,title.subpageText))endendreturntostring(table)endifnoLinks<1thenreturn''end-- Make the table of links.locallinks={}localisCompact=noLinks>7localcurrentIndexfori,numinipairs(nums)dolocalsubpage=self.archivePrefix..tostring(num)localdisplayifisCompactthendisplay=tostring(num)elsedisplay=self:message('archive-link-display',num)endlocallink=makeWikilink('../'..subpage,display)ifnum==self.currentArchiveNumthenlink=string.format('<span style="font-size:115%%;">%s</span>',link)currentIndex=iendtable.insert(links,link)end-- Add the arrows.-- We must do the forwards arrow first as we are adding elements to the-- links table. If we did the backwards arrow first the index for the-- current archive would be wrong.currentIndex=currentIndexormath.ceil(#links/2)fori=currentIndex+1,#linksdoifnums[i]-nums[i-1]>1thentable.insert(links,i,lang:getArrow('forwards'))breakendendfori=currentIndex-1,1,-1doifnums[i+1]-nums[i]>1thentable.insert(links,i+1,lang:getArrow('backwards'))breakendend-- Output the wikitable.localwidthifnoLinks<=3thenwidth=string.format('%dem',noLinks*10)elseifnoLinks<=7thenwidth=string.format('%dem',(noLinks+3)*5)elsewidth='37em'endlocaltable=makeTable(width)for_,sinipairs(links)dotable:tag("td"):wikitext(s)endreturntostring(table)endfunctionNavigator:__tostring()localargs=self.argslocalboxComponents-- Is |omit filled? If not, make the whole box.ifargs.omit==nilthen-- Check for annual archiveslocalcurrentTitle=self.currentTitlelocalyearlyBase,isYearly,yearlyPattern=detectArchiveFormat(currentTitle,args)ifisYearlythen-- Use a yearly archive formatlocallinksYearlyListSeparator="&#32;"-- Space separatorlocallinksYearlyList=mw.getCurrentFrame():expandTemplate{title='Yearly archive list',args={root=yearlyBase,sep=linksYearlyListSeparator,prefix=yearlyPattern}}boxComponents=self:makeMessageBox()..'\n'..'<div style="font-size:115%; width:100%; word-spacing:1em; text-align:center;">'..linksYearlyList..'</div>'else-- Default numbered archive formatboxComponents=self:makeMessageBox()..'\n'..self:makeArchiveLinksWikitable()end-- We're omitting the banner, so we should only make the links table.elseifargs.omit=='banner'thenboxComponents=self:makeArchiveLinksWikitable()-- We're omitting the archives, so we should only make the banner.elseifargs.omit=='archives'thenboxComponents=self:makeMessageBox()end-- Allow for demo pages to be edited freely.ifnotargs.demospacethenboxComponents=boxComponents..' __NONEWSECTIONLINK__ __NOEDITSECTION__ __ARCHIVEDTALK__'endreturnboxComponentsend--------------------------------------------------------------------------------- Exports-------------------------------------------------------------------------------localp={}functionp._exportClasses()return{Navigator=Navigator}endfunctionp._aan(args,cfg,currentTitle)cfg=cfgormw.loadData('Module:Archive/config')currentTitle=currentTitleormw.title.getCurrentTitle()localaan=Navigator.new(args,cfg,currentTitle)returntostring(aan)endfunctionp.aan(frame)localargs=require('Module:Arguments').getArgs(frame,{wrappers='Template:Archive',})returnp._aan(args)endreturnp
Retrieved from "https://en.wikipedia.org/w/index.php?title=Module:Archive&oldid=1288579244"
Category:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp