Module:Chem2
local getArgs = require('Module:Arguments').getArgs
 local p = {} -- module's table
 
 -- Elements with wiki links
 local am = {
 	H = &quot;Hydrogen&quot;,
 	He = &quot;Helium&quot;,
 	Li = &quot;Lithium&quot;,
 	Be = &quot;Beryllium&quot;,
 	B = &quot;Boron&quot;,
 	C = &quot;Carbon&quot;,
 	N = &quot;Nitrogen&quot;,
 	O = &quot;Oxygen&quot;,
 	F = &quot;Fluorine&quot;,
 	Ne = &quot;Neon&quot;,
 	Na = &quot;Sodium&quot;,
 	Mg = &quot;Magnesium&quot;,
 	Al = &quot;Aluminium&quot;,
 	Si = &quot;Silicon&quot;,
 	P = &quot;Phosphorus&quot;,
 	S = &quot;Sulfur&quot;,
 	Cl = &quot;Chlorine&quot;,
 	Ar = &quot;Argon&quot;,
 	K = &quot;Potassium&quot;,
 	Ca = &quot;Calcium&quot;,
 	Sc = &quot;Scandium&quot;,
 	Ti = &quot;Titanium&quot;,
 	V = &quot;Vanadium&quot;,
 	Cr = &quot;Chromium&quot;,
 	Mn = &quot;Manganese&quot;,
 	Fe = &quot;Iron&quot;,
 	Co = &quot;Cobalt&quot;,
 	Ni = &quot;Nickel&quot;,
 	Cu = &quot;Copper&quot;,
 	Zn = &quot;Zinc&quot;,
 	Ga = &quot;Gallium&quot;,
 	Ge = &quot;Germanium&quot;,
 	As = &quot;Arsenic&quot;,
 	Se = &quot;Selenium&quot;,
 	Br = &quot;Bromine&quot;,
 	Kr = &quot;Krypton&quot;,
 	Rb = &quot;Rubidium&quot;,
 	Sr = &quot;Strontium&quot;,
 	Y = &quot;Yttrium&quot;,
 	Zr = &quot;Zirconium&quot;,
 	Nb = &quot;Niobium&quot;,
 	Mo = &quot;Molybdenum&quot;,
 	Tc = &quot;Technetium&quot;,
 	Ru = &quot;Ruthenium&quot;,
 	Rh = &quot;Rhodium&quot;,
 	Pd = &quot;Palladium&quot;,
 	Ag = &quot;Silver&quot;,
 	Cd = &quot;Cadmium&quot;,
 	In = &quot;Indium&quot;,
 	Sn = &quot;Tin&quot;,
 	Sb = &quot;Antimony&quot;,
 	Te = &quot;Tellurium&quot;,
 	I = &quot;Iodine&quot;,
 	Xe = &quot;Xenon&quot;,
 	Cs = &quot;Caesium&quot;,
 	Ba = &quot;Barium&quot;,
 	La = &quot;Lanthanum&quot;,
 	Ce = &quot;Cerium&quot;,
 	Pr = &quot;Praseodymium&quot;,
 	Nd = &quot;Neodymium&quot;,
 	Pm = &quot;Promethium&quot;,
 	Sm = &quot;Samarium&quot;,
 	Eu = &quot;Europium&quot;,
 	Gd = &quot;Gadolinium&quot;,
 	Tb = &quot;Terbium&quot;,
 	Dy = &quot;Dysprosium&quot;,
 	Ho = &quot;Holmium&quot;,
 	Er = &quot;Erbium&quot;,
 	Tm = &quot;Thulium&quot;,
 	Yb = &quot;Ytterbium&quot;,
 	Lu = &quot;Lutetium&quot;,
 	Hf = &quot;Hafnium&quot;,
 	Ta = &quot;Tantalum&quot;,
 	W = &quot;Tungsten&quot;,
 	Re = &quot;Rhenium&quot;,
 	Os = &quot;Osmium&quot;,
 	Ir = &quot;Iridium&quot;,
 	Pt = &quot;Platinum&quot;,
 	Au = &quot;Gold&quot;,
 	Hg = &quot;Mercury (element)&quot;,
 	Tl = &quot;Thallium&quot;,
 	Pb = &quot;Lead&quot;,
 	Bi = &quot;Bismuth&quot;,
 	Po = &quot;Polonium&quot;,
 	At = &quot;Astatine&quot;,
 	Rn = &quot;Radon&quot;,
 	Fr = &quot;Francium&quot;,
 	Ra = &quot;Radium&quot;,
 	Ac = &quot;Actinium&quot;,
 	Th = &quot;Thorium&quot;,
 	Pa = &quot;Protactinium&quot;,
 	U = &quot;Uranium&quot;,
 	Np = &quot;Neptunium&quot;,
 	Pu = &quot;Plutonium&quot;,
 	Am = &quot;Americium&quot;,
 	Cm = &quot;Curium&quot;,
 	Bk = &quot;Berkelium&quot;,
 	Cf = &quot;Californium&quot;,
 	Es = &quot;Einsteinium&quot;,
 	Fm = &quot;Fermium&quot;,
 	Md = &quot;Mendelevium&quot;,
 	No = &quot;Nobelium&quot;,
 	Lr = &quot;Lawrencium&quot;,
 	Rf = &quot;Rutherfordium&quot;,
 	Db = &quot;Dubnium&quot;,
 	Sg = &quot;Seaborgium&quot;,
 	Bh = &quot;Bohrium&quot;,
 	Hs = &quot;Hassium&quot;,
 	Mt = &quot;Meitnerium&quot;,
 	Ds = &quot;Darmstadtium&quot;,
 	Rg = &quot;Roentgenium&quot;,
 	Cp = &quot;Copernicium&quot;,
 	Nh = &quot;Nihonium&quot;,
 	Fl = &quot;Flerovium&quot;,
 	Mc = &quot;Moscovium&quot;,
 	Lv = &quot;Livermorium&quot;,
 	Ts = &quot;Tennessine&quot;,
 	Og = &quot;Oganesson&quot;,
 	
 	-- Groups etc with element-like names
 	Bn = 'Benzyl group',
 	Bz = 'Benzoyl group',
 	D = 'Deuterium',
 	Et = 'Ethyl group',
 	Ln = 'Lanthanide',
 	Nu = 'Nucleophile',
 	Ph = 'Phenyl group',
 	R = 'Substituent',
 	T = 'Tritium',
 	Tf = 'Trifluoromethylsulfonyl group',
 	X = 'Halogen',
 }
 
 -- Groups which are redirected from their normal target if wikilinked; never
 -- autolinked.
 local groups = {
 	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'
 }
 
 local T_ELEM = 0         -- token types
 local T_NUM = 1          -- number
 local T_OPEN = 2         -- open '('
 local T_CLOSE = 3        -- close ')'
 local T_PM_CHARGE = 4    -- + or −
 local T_WATER = 6        -- .xH2O x number
 local T_CRYSTAL = 9      -- .x
 local T_CHARGE = 8       -- charge (x+), (x-)
 local T_SUF_CHARGE = 10  -- suffix and charge e.g. 2+ from H2+
 local T_SUF_CHARGE2 = 12 -- suffix and (charge) e.g. 2(2+) from He2(2+)
 local T_SPECIAL = 14     -- starting with \ e.g. \d for double bond (=)
 local T_SPECIAL2 = 16    -- starting with \y{x} e.g. \i{12} for isotope with mass number 12
 local T_ARROW_R = 17     -- match: -&gt;
 local T_ARROW_EQ = 18    -- match: &lt;-&gt;
 local T_UNDERSCORE = 19  -- _{ ... }
 local T_CARET = 20       -- ^{ ... }
 local T_LINKOPEN = 21    -- Opening of link, always like &quot;[[target|&quot; even if the source wasn't
 local T_NOCHANGE = 30    -- Anything else like ☃
 
 function su(up, down)
 	if up == &quot;&quot; then
 		return ('&lt;sub class=&quot;template-chem2-sub&quot;&gt;%s&lt;/sub&gt;'):format(down)
 	end
 	if down == &quot;&quot; then
 		return ('&lt;sup class=&quot;template-chem2-sup&quot;&gt;%s&lt;/sup&gt;'):format(up)
 	end
     return ('&lt;span class=&quot;template-chem2-su&quot;&gt;&lt;span&gt;%s&lt;/span&gt;&lt;span&gt;%s&lt;/span&gt;&lt;/span&gt;'):format(up, down)
 end
 
 function DotIt()
     return '&amp;middot;'
 end
 
 function item(f) -- (iterator) returns one token (type, value) at a time from the formula 'f'
     local i = 1
 
     return function ()
         local t, x = nil, nil
 
         if (i == 1) and f:match('^[0-9]', i) then 
             x = f:match('^[%d.]+', i); t = T_NOCHANGE; i = i + x:len();   -- matching coefficient (need a space first)
 
         elseif i &lt;= f:len() then
             x = f:match('^%s+[%d.]+', i); t = T_NOCHANGE;  -- matching coefficient (need a space first)
             if not x then x = f:match('^%s[+]', i); t = T_NOCHANGE; end       -- matching + (H2O + H2O)
             if not x then x = f:match('^%&amp;%#[%w%d]+%;', i); t = T_NOCHANGE; end       -- &amp;#...;
             if not x then x = f:match('^%&lt;%-%&gt;', i); t = T_ARROW_EQ; end       -- matching &lt;-&gt;
             if not x then x = f:match('^%-%&gt;', i); t = T_ARROW_R; end       -- matching -&gt;
             if not x then x = f:match('^%u%l*', i); t = T_ELEM; end        -- matching symbols like Aaaaa
             if not x then x = f:match('^%d+[+-]', i); t = T_SUF_CHARGE; end        -- matching x+, x-
             if not x then x = f:match('^%d+%(%d*[+-]%)', i); t = T_SUF_CHARGE2; end        -- matching x(y+/-), x(+/-)
             if not x then x = f:match('^%(%d*[+-]%)', i); t = T_CHARGE; end        -- matching (x+) (xx+), (x-) (xx-)
             if not x then x = f:match('^[%d.]+', i); t = T_NUM; end        -- matching number
             if not x and (f:match('^%[%[%[[^[]', i) or f:match('^%[[^[]', i)) then
             	i = i + 1; return T_OPEN, '&amp;#91;' end -- escape [[[X or [X (relevant to auto-linking)
             if not x and f:sub(i, i + 1) == '[[' then
             	x = f:match('^%[%[([^]|]*)', i) -- link target
             	local len = x:len() + 3
             	x = '[[' .. (groups[x] or am[x] or x) .. '|'  -- override link target for common groups
 
             	if f: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]] =&gt; &quot;[[CH3|&quot;, &quot;CH3]]&quot;
             		i = i + 2
             	else
             		i = i + len
             	end
             	return T_LINKOPEN, x
             end
             if not x then x = f:match('^[(|{|%[]', i); t = T_OPEN; end     -- matching ({[
             if not x then x = f:match('^[)|}|%]]', i); t = T_CLOSE; end    -- matching )}]
             if not x then x = f:match('^[+-]', i); t = T_PM_CHARGE; end    -- matching + or -
             if not x then x = f:match('^%*[%d.]*H2O', i); t = T_WATER; end -- Crystal water
             if not x then x = f:match('^%*[%d.]*', i); t = T_CRYSTAL; end  -- Crystal
             if not x then x = f:match('^[\\].{%d+}', i); t = T_SPECIAL2; end -- \y{x}
             if not x then x = f:match('^[\\].', i); t = T_SPECIAL; end -- \x
             if not x then x = f:match('^_{[^}]*}', i); t = T_UNDERSCORE; end -- _{...}
             if not x then x = f:match('^\^{[^}]*}', i); t = T_CARET; end   -- ^{...}
             if not x then x = f:match('^.', i); t = T_NOCHANGE; end  --the rest - one by one
             if x then i = i + x:len(); else i = i + 999; error(&quot;Invalid character in formula! : &quot;..f) end
         end
         return t, x
     end
 end
 
 function p._chem(args)
     local f = args[1] or ''
 
     f = string.gsub(f, &quot;–&quot;, &quot;-&quot;)  -- replace – with - (hyphen not ndash)
     f = string.gsub(f, &quot;−&quot;, &quot;-&quot;)  -- replace – with - (hyphen not minus sign)
 
     local formula = ''
     local t, x
 
     local link = args['link'] or &quot;&quot;
     local auto = args['auto'] or &quot;&quot;
     local seen = {}
     local _debug = false
 
     if not (link == '') then formula = formula .. &quot;[[&quot; .. link .. &quot;|&quot;; end   -- wikilink start [[link|
  
     for t, x in item(f) do 
     	if _debug then
     		formula = (&quot;%s\n* %d %s&quot;):format(formula, t, x)
         elseif t == T_ELEM then
             if (auto == '') or (not am[x]) or seen[x] then formula = formula .. x
             else formula = (&quot;%s[[%s|%s]]&quot;):format(formula, am[x], x); seen[x] = true
             end
         elseif t == T_COEFFICIENT then formula = formula .. x
         elseif t == T_NUM   then formula = formula .. su(&quot;&quot;, x);
         elseif t == T_LINKOPEN  then formula = formula .. x;      -- [[Link|
         elseif t == T_OPEN  then formula = formula .. x;          -- ([{
         elseif t == T_CLOSE then formula = formula .. x;          -- )]}
         elseif t == T_PM_CHARGE    then formula = formula .. su(x:gsub(&quot;-&quot;, &quot;−&quot;), &quot;&quot;);
         elseif t == T_SUF_CHARGE then 
             formula = formula .. su(x:match(&quot;[+-]&quot;):gsub(&quot;-&quot;, &quot;−&quot;), x:match(&quot;%d+&quot;), &quot;&quot;);
         elseif t == T_SUF_CHARGE2 then 
             formula = formula .. su(x:match(&quot;%(%d*[+-]&quot;):gsub(&quot;-&quot;, &quot;−&quot;):sub(2, -1), x:match(&quot;%d+&quot;))
         elseif t == T_CHARGE then
         	formula = formula .. &quot;&lt;sup&gt;&quot;
         	if x:match(&quot;%d+&quot;) then formula = formula .. x:match(&quot;%d+&quot;); end
         	formula = formula .. x:match(&quot;[%+-]&quot;):gsub(&quot;-&quot;, &quot;−&quot;) .. &quot;&lt;/sup&gt;&quot;;
         	-- Cannot concatenat a nil value from x:match(&quot;%d+&quot;);
         elseif t == T_CRYSTAL then formula = formula .. DotIt() .. string.gsub( x, &quot;*&quot;, '', 1 );
         elseif t == T_SPECIAL then
             parameter = x:sub(2, 2) -- x fra \x  
             if     parameter == &quot;s&quot; then formula = formula .. &quot;−&quot;   -- single bond
             elseif parameter == &quot;d&quot; then formula = formula .. &quot;=&quot;   -- double bond
             elseif parameter == &quot;t&quot; then formula = formula .. &quot;≡&quot;   -- tripple bond
             elseif parameter == &quot;q&quot; then formula = formula .. &quot;≣&quot;   -- Quadruple bond
             elseif parameter == &quot;h&quot; then formula = formula .. &quot;η&quot;   -- η, hapticity
             elseif parameter == &quot;*&quot; then formula = formula .. &quot;*&quot;   -- *, normal *
             elseif parameter == &quot;-&quot; then formula = formula .. &quot;-&quot;   -- -
             elseif parameter == &quot;\\&quot; then formula = formula .. &quot;\\&quot;   -- \
             elseif parameter == &quot;\'&quot; then formula = formula .. &quot;&amp;#39;&quot;   -- html-code for '
             end
         elseif t == T_SPECIAL2 then  -- \y{x}
             parameter = x:sub(2, 2) -- y fra \y{x} 
             if parameter  == &quot;h&quot; then --[[Hapticity]]
                 if (auto == '') then formula = formula .. &quot;η&lt;sup&gt;&quot; .. x:match('%d+') .. &quot;&lt;/sup&gt;-&quot;
                 else
                     formula = formula .. &quot;[[Hapticity|η&lt;sup&gt;&quot; .. x:match('%d+') .. &quot;&lt;/sup&gt;]]-&quot;
                 end
             elseif parameter == &quot;m&quot; then formula = formula .. &quot;μ&lt;sub&gt;&quot; .. x:match('%d+') .. &quot;&lt;/sub&gt;-&quot; -- mu ([[bridging ligand]])
             end
         elseif t == T_WATER then 
             if x:match(&quot;^%*[%d.]&quot;) then 
                 formula = formula .. DotIt() .. x:match(&quot;%f[%.%d]%d*%.?%d*%f[^%.%d%]]&quot;) .. &quot;H&lt;sub&gt;2&lt;/sub&gt;O&quot;;
             else
                 formula = formula .. DotIt() .. &quot;H&lt;sub&gt;2&lt;/sub&gt;O&quot;;
             end  
         elseif t == T_UNDERSCORE  then formula = formula .. su(&quot;&quot;, x:sub(3,-2)) -- x contains _{string}
         elseif t == T_CARET then formula = formula .. su(x:sub(3,-2), &quot;&quot;) -- x contains ^{string}
         elseif t == T_ARROW_R then formula = formula .. &quot; → &quot;
         elseif t == T_ARROW_EQ then formula = formula .. &quot; ⇌ &quot;
         elseif t == T_NOCHANGE  then formula = formula .. x;  -- The rest - everything which isn't captured by the regular expresions.
      
         else error('unreachable - ???') end -- in fact, unreachable
     end
 
     if not (link == nil or link == '') then formula = formula .. &quot;]]&quot;; end   -- wikilink closing ]]
     formula = mw.getCurrentFrame():preprocess('&lt;templatestyles src=&quot;Module:Chem2/styles.css&quot;/&gt;') ..
         '&lt;span class=&quot;chemf nowrap&quot;&gt;' .. formula .. '&lt;/span&gt;'
     if args[2] or args[3] or args[4] then
         formula = formula .. require('Module:If preview')._warning{
 '&amp;#123;&amp;#123;chem2&amp;#125;&amp;#125; was called with multiple positional arguments. It should have just one, e.g. &amp;#123;&amp;#123;chem2&amp;#124;H2O&amp;#125;&amp;#125;.'
         }
     end
     return formula
 end
 
 function p.chem(frame)
     local args = getArgs(frame)
     return p._chem(args)
 end
 
 -- PRIVATE function to generate documentation.
 function p._autodoc(frame)
 	local TableTools = require('Module:TableTools') -- we don't want to load this on articles for no reason
 	local result = {
 		'===Elements and element-style symbols===\nThese may be automatically linked or used as if they were redirects.\n',
 		'{| class=&quot;wikitable&quot;\n! Symbol !! Link target\n'
 	}
 	for symbol, target in TableTools.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=&quot;wikitable&quot;\n! Symbol !! Link target\n'
 	for symbol, target in TableTools.sortedPairs(groups) do
 		result[#result + 1] = ('|-\n| %s || [[%s]]\n'):format(symbol, target)
 	end
 	result[#result + 1] = '|}'
 	return table.concat(result)
 end