Module:Chem2
- العربية
- অসমীয়া
- Basa Bali
- বাংলা
- 閩南語 / Bân-lâm-gí
- Беларуская
- भोजपुरी
- Български
- Bosanski
- Català
- Dansk
- الدارجة
- Ελληνικά
- Español
- Euskara
- فارسی
- Galego
- ગુજરાતી
- 한국어
- Bahasa Indonesia
- IsiZulu
- Íslenska
- עברית
- Kurdî
- Lietuvių
- Македонски
- മലയാളം
- मराठी
- ဘာသာမန်
- Bahasa Melayu
- Монгол
- မြန်မာဘာသာ
- 日本語
- Oʻzbekcha / ўзбекча
- ပအိုဝ်ႏဘာႏသာႏ
- Polski
- Português
- Qaraqalpaqsha
- Simple English
- کوردی
- Српски / srpski
- Sunda
- Suomi
- Tagalog
- ไทย
- Türkçe
- Tiếng Việt
- 粵語
- 中文
- Bajau Sama
- Kumoring
Appearance
From Wikipedia, the free encyclopedia
This module is rated as ready 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 on help pages and other Wikipedia resources as an option for new users. To minimise server load and avoid disruptive output, improvements should be developed through sandbox testing rather than repeated trial-and-error editing.
Page template-protected This module is currently protected from editing.
See the protection policy and protection log for more details. Please discuss any changes on the talk page; you may submit an edit request to ask an administrator to make an edit if it is uncontroversial or supported by consensus. You may also request that this page be unprotected.
See the protection policy and protection log for more details. Please discuss any changes on the talk page; you may submit an edit request to ask an administrator to make an edit if it is uncontroversial or supported by consensus. You may also request that this page be unprotected.
Warning This Lua module is used on approximately 8,900 pages and changes may be widely noticed. Test changes in the module's /sandbox or /testcases subpages, or in your own module sandbox. Consider discussing changes on the talk page before implementing them.
This module depends on the following other modules:
This module implements {{chem2 }}. Please see its documentation for details.
The above documentation is transcluded from Module:Chem2/doc. (edit | history)
Editors can experiment in this module's sandbox (edit | diff) and testcases (create) pages.
Subpages of this module.
Editors can experiment in this module's sandbox (edit | diff) and testcases (create) pages.
Subpages of this module.
localgetArgs=require('Module:Arguments').getArgs localp={}-- module's table -- Elements with wiki links localam={ H="Hydrogen", He="Helium", Li="Lithium", Be="Beryllium", B="Boron", C="Carbon", N="Nitrogen", O="Oxygen", F="Fluorine", Ne="Neon", Na="Sodium", Mg="Magnesium", Al="Aluminium", Si="Silicon", P="Phosphorus", S="Sulfur", Cl="Chlorine", Ar="Argon", K="Potassium", Ca="Calcium", Sc="Scandium", Ti="Titanium", V="Vanadium", Cr="Chromium", Mn="Manganese", Fe="Iron", Co="Cobalt", Ni="Nickel", Cu="Copper", Zn="Zinc", Ga="Gallium", Ge="Germanium", As="Arsenic", Se="Selenium", Br="Bromine", Kr="Krypton", Rb="Rubidium", Sr="Strontium", Y="Yttrium", Zr="Zirconium", Nb="Niobium", Mo="Molybdenum", Tc="Technetium", Ru="Ruthenium", Rh="Rhodium", Pd="Palladium", Ag="Silver", Cd="Cadmium", In="Indium", Sn="Tin", Sb="Antimony", Te="Tellurium", I="Iodine", Xe="Xenon", Cs="Caesium", Ba="Barium", La="Lanthanum", Ce="Cerium", Pr="Praseodymium", Nd="Neodymium", Pm="Promethium", Sm="Samarium", Eu="Europium", Gd="Gadolinium", Tb="Terbium", Dy="Dysprosium", Ho="Holmium", Er="Erbium", Tm="Thulium", Yb="Ytterbium", Lu="Lutetium", Hf="Hafnium", Ta="Tantalum", W="Tungsten", Re="Rhenium", Os="Osmium", Ir="Iridium", Pt="Platinum", Au="Gold", Hg="Mercury (element)", Tl="Thallium", Pb="Lead", Bi="Bismuth", Po="Polonium", At="Astatine", Rn="Radon", Fr="Francium", Ra="Radium", Ac="Actinium", Th="Thorium", Pa="Protactinium", U="Uranium", Np="Neptunium", Pu="Plutonium", Am="Americium", Cm="Curium", Bk="Berkelium", Cf="Californium", Es="Einsteinium", Fm="Fermium", Md="Mendelevium", No="Nobelium", Lr="Lawrencium", Rf="Rutherfordium", Db="Dubnium", Sg="Seaborgium", Bh="Bohrium", Hs="Hassium", Mt="Meitnerium", Ds="Darmstadtium", Rg="Roentgenium", Cn="Copernicium", Nh="Nihonium", Fl="Flerovium", Mc="Moscovium", Lv="Livermorium", Ts="Tennessine", Og="Oganesson", -- Groups etc with element-like names Bn='Benzyl group', Bu='Butyl group', Bz='Benzoyl group', Cp='Cyclopentadienyl', D='Deuterium', Et='Ethyl group', Ln='Lanthanide', Me='Methyl group', Nu='Nucleophile', Ph='Phenyl group', Pn='Pentyl group', R='Substituent', T='Tritium', Tf='Trifluoromethylsulfonyl group', X='Halogen', } -- Groups which are redirected from their normal target if wikilinked; never -- autolinked. localgroups={ CH3='Methyl group', CO3='Carbonate', COOH='Carboxyl group', ClO='Hypochlorite', ClO2='Chlorite', ClO3='Chlorate', ClO4='Perchlorate', H2O='Water of crystallization', H3O='Hydronium', NH2='Amine group', NH4='Ammonium', NO3='Nitrate', PO3='Phosphite', PO4='Phosphate', SH='Thiol group', SO3='Sulfite', SO4='Sulfate', SeH='Selenol group' } localT_ELEM=0-- token types localT_NUM=1-- number localT_OPEN=2-- open '(' localT_CLOSE=3-- close ')' localT_PM_CHARGE=4-- + or − localT_WATER=6-- .xH2O x number localT_CRYSTAL=9-- .x localT_CHARGE=8-- charge (x+), (x-) localT_SUF_CHARGE=10-- suffix and charge e.g. 2+ from H2+ localT_SUF_CHARGE2=12-- suffix and (charge) e.g. 2(2+) from He2(2+) localT_SPECIAL=14-- starting with \ e.g. \d for double bond (=) localT_SPECIAL2=16-- starting with \y{x} e.g. \i{12} for isotope with mass number 12 localT_ARROW_R=17-- match: -> localT_ARROW_EQ=18-- match: <-> localT_UNDERSCORE=19-- _{ ... } localT_CARET=20-- ^{ ... } localT_LINKOPEN=21-- Opening of link, always like "[[target|" even if the source wasn't localT_NOCHANGE=30-- Anything else like ☃ functionsu(up,down) ifup==""then return('<sub class="template-chem2-sub">%s</sub>'):format(down) end ifdown==""then return('<sup class="template-chem2-sup">%s</sup>'):format(up) end return('<span class="template-chem2-su"><span>%s</span><span>%s</span></span>'):format(up,down) end functionDotIt() return'·' end functionitem(f)-- (iterator) returns one token (type, value) at a time from the formula 'f' locali=1 returnfunction() localt,x=nil,nil if(i==1)andf:match('^[0-9]',i)then x=f:match('^[%d.]+',i);t=T_NOCHANGE;i=i+x:len();-- matching coefficient (need a space first) elseifi<=f:len()then x=f:match('^%s+[%d.]+',i);t=T_NOCHANGE;-- matching coefficient (need a space first) ifnotxthenx=f:match('^%s[+]',i);t=T_NOCHANGE;end-- matching + (H2O + H2O) ifnotxthenx=f:match('^%&%#[%w%d]+%;',i);t=T_NOCHANGE;end-- &#...; ifnotxthenx=f:match('^%<%-%>',i);t=T_ARROW_EQ;end-- matching <-> ifnotxthenx=f:match('^%-%>',i);t=T_ARROW_R;end-- matching -> ifnotxthenx=f:match('^%u%l*',i);t=T_ELEM;end-- matching symbols like Aaaaa ifnotxthenx=f:match('^%d+[+-]',i);t=T_SUF_CHARGE;end-- matching x+, x- ifnotxthenx=f:match('^%d+%(%d*[+-]%)',i);t=T_SUF_CHARGE2;end-- matching x(y+/-), x(+/-) ifnotxthenx=f:match('^%(%d*[+-]%)',i);t=T_CHARGE;end-- matching (x+) (xx+), (x-) (xx-) ifnotxthenx=f:match('^[%d.]+',i);t=T_NUM;end-- matching number ifnotxand(f:match('^%[%[%[[^[]',i)orf:match('^%[[^[]',i))then i=i+1;returnT_OPEN,'['end-- escape [[[X or [X (relevant to auto-linking) ifnotxandf:sub(i,i+1)=='[['then x=f:match('^%[%[([^]|]*)',i)-- link target locallen=x:len()+3 x='[['..(groups[x]oram[x]orx)..'|'-- override link target for common groups iff:sub(len+i,len+i)==']'then -- We're going to read the link twice, once as target and once as -- chemical markup, e.g. [[CH3]] => "[[CH3|", "CH3]]" i=i+2 else i=i+len end returnT_LINKOPEN,x end ifnotxthenx=f:match('^[(|{|%[]',i);t=T_OPEN;end-- matching ({[ ifnotxthenx=f:match('^[)|}|%]]',i);t=T_CLOSE;end-- matching )}] ifnotxthenx=f:match('^[+-]',i);t=T_PM_CHARGE;end-- matching + or - ifnotxthenx=f:match('^%*[%d.]*H2O',i);t=T_WATER;end-- Crystal water ifnotxthenx=f:match('^%*[%d.]*',i);t=T_CRYSTAL;end-- Crystal ifnotxthenx=f:match('^[\\].{%d+}',i);t=T_SPECIAL2;end-- \y{x} ifnotxthenx=f:match('^[\\].',i);t=T_SPECIAL;end-- \x ifnotxthenx=f:match('^_{[^}]*}',i);t=T_UNDERSCORE;end-- _{...} ifnotxthenx=f:match('^^{[^}]*}',i);t=T_CARET;end-- ^{...} ifnotxthenx=f:match('^.',i);t=T_NOCHANGE;end--the rest - one by one ifxtheni=i+x:len();elsei=i+999;error("Invalid character in formula! : "..f)end end returnt,x end end functionp._chem(args) localf=args[1]or'' f=mw.text.decode(f,true)-- handle entity input (like −): decode right away f=string.gsub(f,"–","-")-- replace – with - (hyphen not ndash) f=string.gsub(f,"−","-")-- replace – with - (hyphen not minus sign) localformula='' localt,x locallink=args['link']or"" localauto=args['auto']or"" localseen={} local_debug=false ifnot(link=='')thenformula=formula.."[["..link.."|";end-- wikilink start [[link| fort,xinitem(f)do if_debugthen formula=("%s\n* %d %s"):format(formula,t,x) elseift==T_ELEMthen if(auto=='')or(notam[x])orseen[x]thenformula=formula..x elseformula=("%s[[%s|%s]]"):format(formula,am[x],x);seen[x]=true end elseift==T_COEFFICIENTthenformula=formula..x elseift==T_NUMthenformula=formula..su("",x); elseift==T_LINKOPENthenformula=formula..x;-- [[Link| elseift==T_OPENthenformula=formula..x;-- ([{ elseift==T_CLOSEthenformula=formula..x;-- )]} elseift==T_PM_CHARGEthenformula=formula..su(x:gsub("-","−"),""); elseift==T_SUF_CHARGEthen formula=formula..su(x:match("[+-]"):gsub("-","−"),x:match("%d+"),""); elseift==T_SUF_CHARGE2then formula=formula..su(x:match("%(%d*[+-]"):gsub("-","−"):sub(2,-1),x:match("%d+")) elseift==T_CHARGEthen formula=formula.."<sup>" ifx:match("%d+")thenformula=formula..x:match("%d+");end formula=formula..x:match("[%+-]"):gsub("-","−").."</sup>"; -- Cannot concatenat a nil value from x:match("%d+"); elseift==T_CRYSTALthenformula=formula..DotIt()..string.gsub(x,"*",'',1); elseift==T_SPECIALthen parameter=x:sub(2,2)-- x fra \x ifparameter=="s"thenformula=formula.."−"-- single bond elseifparameter=="d"thenformula=formula.."="-- double bond elseifparameter=="t"thenformula=formula.."≡"-- tripple bond elseifparameter=="q"thenformula=formula.."≣"-- Quadruple bond elseifparameter=="h"thenformula=formula.."η"-- η, hapticity elseifparameter=="*"thenformula=formula.."*"-- *, normal * elseifparameter=="-"thenformula=formula.."-"-- - elseifparameter=="\\"thenformula=formula.."\\"-- \ elseifparameter=="\'"thenformula=formula.."'"-- html-code for ' end elseift==T_SPECIAL2then-- \y{x} parameter=x:sub(2,2)-- y fra \y{x} ifparameter=="h"then--[[Hapticity]] if(auto=='')thenformula=formula.."η<sup>"..x:match('%d+').."</sup>-" else formula=formula.."[[Hapticity|η<sup>"..x:match('%d+').."</sup>]]-" end elseifparameter=="m"thenformula=formula.."μ<sub>"..x:match('%d+').."</sub>-"-- mu ([[bridging ligand]]) end elseift==T_WATERthen ifx:match("^%*[%d.]")then formula=formula..DotIt()..x:match("%f[%.%d]%d*%.?%d*%f[^%.%d%]]").."H<sub>2</sub>O"; else formula=formula..DotIt().."H<sub>2</sub>O"; end elseift==T_UNDERSCOREthenformula=formula..su("",x:gsub("-","−"):sub(3,-2))-- x contains _{string} elseift==T_CARETthenformula=formula..su(x:gsub("-","−"):sub(3,-2),"")-- x contains ^{string} elseift==T_ARROW_Rthenformula=formula.." → " elseift==T_ARROW_EQthenformula=formula.." ⇌ " elseift==T_NOCHANGEthenformula=formula..x;-- The rest - everything which isn't captured by the regular expresions. elseerror('unreachable - ???')end-- in fact, unreachable end ifnot(link==nilorlink=='')thenformula=formula.."]]";end-- wikilink closing ]] formula=mw.getCurrentFrame():preprocess('<templatestyles src="Module:Chem2/styles.css"/>').. '<span class="chemf nowrap">'..formula..'</span>' ifargs[2]orargs[3]orargs[4]then formula=formula..require('Module:If preview')._warning{ '{{chem2}} was called with multiple positional arguments. It should have just one, e.g. {{chem2|H2O}}.' } end returnformula end functionp.chem(frame) localargs=getArgs(frame) returnp._chem(args) end -- PRIVATE function to generate documentation. functionp._autodoc(frame) localTableTools=require('Module:TableTools')-- we don't want to load this on articles for no reason localresult={ '===Elements and element-style symbols===\nThese may be automatically linked or used as if they were redirects.\n', '{| class="wikitable"\n! Symbol !! Link target\n' } forsymbol,targetinTableTools.sortedPairs(am)do result[#result+1]=('|-\n| %s || [[%s]]\n'):format(symbol,target) end result[#result+1]='|}\n===Groups===\nThese must be linked manually; they work as if they were redirects.\n' result[#result+1]='{| class="wikitable"\n! Symbol !! Link target\n' forsymbol,targetinTableTools.sortedPairs(groups)do result[#result+1]=('|-\n| %s || [[%s]]\n'):format(symbol,target) end result[#result+1]='|}' returntable.concat(result) end returnp