Module:Languages

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Lua

CodeDiscussionEditHistoryLinksLink count Subpages:DocumentationTestsResultsSandboxLive code All modules

Supported languages (mappings in "MediaWiki:Lang/code" for {{int:lang}}, and their current native names)

  • (⧼lang/apc⧽) شامي
  • (⧼lang/mui⧽) Baso Palembang
  • (ace) Acèh
  • (agq) Aghem
  • (sma) åarjelsaemien
  • (af) Afrikaans
  • (zgh-latn) tamaziɣt tanawayt
  • (⧼lang/nan-hant⧽) 閩南語(傳統漢字)
  • (ang) Ænglisc
  • (ak) Akan
  • (gsw) Alemannisch
  • (als) Alemannisch
  • (smn) anarâškielâ
  • (en-us) American English
  • (ase) American sign language
  • (an) aragonés
  • (aae) Arbërisht
  • (rup) armãneashti
  • (roa-rup) armãneashti
  • (frp) arpetan
  • (atj) Atikamekw
  • (ast) asturianu
  • (gn) Avañe'ẽ
  • (ay) Aymar aru
  • (az) azərbaycanca
  • (ksf) Bafia
  • (bfd) Bafut
  • (abs) bahasa ambon
  • (gor) Bahasa Hulontalo
  • (id) Bahasa Indonesia
  • (ms) Bahasa Melayu
  • (bdr) Bajau Sama
  • (bkc) Baka
  • (bkh) Bakoko
  • (bm) bamanankan
  • (bax) Bamum
  • (nan) 閩南語 / Bân-lâm-gú
  • (zh-min-nan) 閩南語 / Bân-lâm-gú
  • (bjn) Banjar
  • (ban) Basa Bali
  • (map-bms) Basa Banyumasan
  • (kge) Basa Kumoring
  • (bug) Basa Ugi
  • (bas) Basaa
  • (rw) Ikinyarwanda
  • (se-fi) davvisámegiella (Suoma bealde)
  • (ha) Hausa
  • (dag) dagbanli
  • (gag) Gagauz
  • (fmp) Fe'fe'
  • (bcl) Bikol Central
  • (dga) Dagaare
  • (etu) Ejagham
  • (dua) Duala
  • (ewo) Ewondo
  • (wls) Fakaʻuvea
  • (de-formal) Deutsch (Sie-Form)
  • (ibb) ibibio
  • (sje) bidumsámegiella
  • (eto) Eton
  • (eml) emiliàn e rumagnòl
  • (se-no) davvisámegiella (Norgga bealde)
  • (fy) Frysk
  • (es) español
  • (cy) Cymraeg
  • (ho) Hiri Motu
  • (hif) Fiji Hindi
  • (dsb) dolnoserbski
  • (cho) Chahta anumpa
  • (cbk-zam) Chavacano de Zamboanga
  • (mh) Ebon
  • (sei) Cmique Itom
  • (bbj) Ghomála'
  • (chn) chinuk wawa
  • (se) davvisámegiella
  • (en-gb) British English
  • (egl) emiliàn e rumagnòl
  • (igl) Igala
  • (gl) galego
  • (gv) Gaelg
  • (guw) gungbe
  • (frc) français cadien
  • (sm) Gagana Samoa
  • (haw) Hawaiʻi
  • (na) Dorerin Naoero
  • (cnh) Hakha Chin
  • (en) English
  • (sn) chiShona
  • (gaa) Ga
  • (hsb) hornjoserbsce
  • (bew) Betawi
  • (bbc) Batak Toba
  • (eo) Esperanto
  • (da) dansk
  • (fo) føroyskt
  • (io) Ido
  • (eu) euskara
  • (btm) Batak Mandailing
  • (co) corsu
  • (es-formal) español (formal)
  • (ga) Gaeilge
  • (fon) fɔ̀ngbè
  • (en-ca) Canadian English
  • (bar) Boarisch
  • (bbc-latn) Batak Toba
  • (ext) estremeñu
  • (br) brezhoneg
  • (ca) català
  • (hrx) Hunsrik
  • (brh) Bráhuí
  • (cps) Capiceño
  • (hr) hrvatski
  • (fr) français
  • (bs) bosanski
  • (cs) čeština
  • (nv) Diné bizaad
  • (gpe) Ghanaian Pidgin
  • (se-se) davvisámegiella (Ruoŧa bealde)
  • (bi) Bislama
  • (pdc) Deitsch
  • (efi) Efịk
  • (gd) Gàidhlig
  • (et) eesti
  • (hif-latn) Fiji Hindi
  • (es-419) español de América Latina
  • (de) Deutsch
  • (ee) eʋegbe
  • (vmw) emakhuwa
  • (fur) furlan
  • (ki) Gĩkũyũ
  • (ff) Fulfulde
  • (dtp) Dusun Bundu-liwan
  • (ig) Igbo
  • (ch) Chamoru
  • (gur) farefare
  • (gya) Gbaya
  • (gom-latn) Gõychi Konknni
  • (ceb) Cebuano
  • (aln) Gegë
  • (ny) Chi-Chewa
  • (tum) chiTumbuka
  • (rn) ikirundi
  • (sh) srpskohrvatski / српскохрватски
  • (pwn) pinayuanan
  • (kum) къумукъ
  • (sh-latn) srpskohrvatski (latinica)
  • (ko-kp) 조선말
  • (nmz) nawdm
  • (ady-cyrl) адыгабзэ
  • (shi-tfng) ⵜⴰⵛⵍⵃⵉⵜ
  • (pih) Norfuk / Pitkern
  • (bpy) বিষ্ণুপ্রিয়া মণিপুরী
  • (bg) български
  • (lg) Luganda
  • (kg) Kongo
  • (ng) Oshiwambo
  • (mg) Malagasy
  • (ojb) Ojibwemowin
  • (bh) भोजपुरी
  • (tg) тоҷикӣ
  • (sg) Sängö
  • (ug) ئۇيغۇرچە / Uyghurche
  • (pap) Papiamentu
  • (za) Vahcuengh
  • (gcr) kriyòl gwiyannen
  • (shi) Taclḥit
  • (tg-latn) tojikī
  • (mrj) кырык мары
  • (nyn) runyankore
  • (vut) Vute
  • (kbp) Kabɩyɛ
  • (pt-br) português do Brasil
  • (rut) мыхаӀбишды
  • (ckb) کوردی
  • (jut) jysk
  • (mnw) ဘာသာမန်
  • (cpx-latn) Pó-sing-gṳ̂ (Báⁿ-uā-ci̍)
  • (mi) Māori
  • (nyo) Orunyoro
  • (nnz) Nda'nda'
  • (fi) suomi
  • (mnc-mong) ᠮᠠᠨᠵᡠ ᡤᡳᠰᡠᠨ
  • (ce) нохчийн
  • (be) беларуская
  • (nds-nl) Nedersaksies
  • (nia) Li Niha
  • (ne) नेपाली
  • (wuu-hans) 吴语(简体)
  • (ie) Interlingue
  • (he) עברית
  • (ryu) 沖縄口
  • (te) తెలుగు
  • (mwl) Mirandés
  • (tg-cyrl) тоҷикӣ
  • (hi) हिन्दी
  • (tzm) ⵜⴰⵎⴰⵣⵉⵖⵜ
  • (nl-informal) Nederlands (informeel)
  • (nan-hani) 閩南語
  • (yue-hant) 粵語(繁體)
  • (skr-arab) سرائیکی
  • (kri) Krio
  • (tt-latn) tatarça
  • (si) සිංහල
  • (ti) ትግርኛ
  • (bqz) Mka'a
  • (sd) سنڌي
  • (mcp) Maka
  • (sh-cyrl) српскохрватски (ћирилица)
  • (dty) डोटेली
  • (yrl) Nhẽẽgatú
  • (is) íslenska
  • (ks) कॉशुर / کٲشُر
  • (zh) 中文
  • (os) ирон
  • (ps) پښتو
  • (ss) SiSwati
  • (sty) себертатар
  • (simple) Simple English
  • (ur) اردو
  • (zh-classical) 文言
  • (xh) isiXhosa
  • (kea) kabuverdianu
  • (mnc) ᠮᠠᠨᠵᡠ ᡤᡳᠰᡠᠨ
  • (as) অসমীয়া
  • (krj) Kinaray-a
  • (koi) перем коми
  • (kj) Kwanyama
  • (lzh) 文言
  • (kr) kanuri
  • (mr) मराठी
  • (or) ଓଡ଼ିଆ
  • (kk-latn) qazaqşa (latın)
  • (fj) Na Vosa Vakaviti
  • (sr) српски / srpski
  • (tru) Ṫuroyo
  • (crh) qırımtatarca
  • (byv) Medumba
  • (myv) эрзянь
  • (ar) العربية
  • (gan-hans) 赣语(简体)
  • (cr) Nēhiyawēwin / ᓀᐦᐃᔭᐍᐏᐣ
  • (syl) ꠍꠤꠟꠐꠤ
  • (nds) Plattdüütsch
  • (nnh) Ngiemboon
  • (sq) shqip
  • (crh-latn) qırımtatarca (Latin)
  • (arz) مصرى
  • (shy-latn) tacawit
  • (mk) македонски
  • (ary) الدارجة
  • (wes) Pidgin (Cameroon)
  • (luz) لئری دوٙمینی
  • (be-tarask) беларуская (тарашкевіца)
  • (kk) қазақша
  • (vep) vepsän kel’
  • (ses) Koyraboro Senni
  • (ker) Kera
  • (ts) Xitsonga
  • (rmc) romaňi čhib
  • (ik) Iñupiatun
  • (krl) karjal
  • (fkv) kvääni
  • (mdf) мокшень
  • (bo) བོད་ཡིག
  • (nso) Sesotho sa Leboa
  • (tk) Türkmençe
  • (ksw) စှီၤ
  • (tok) toki pona
  • (arn) mapudungun
  • (kk-cn) قازاقشا (جۇنگو)
  • (sk) slovenčina
  • (roa-tara) tarandíne
  • (pnt) Ποντιακά
  • (to) lea faka-Tonga
  • (so) Soomaaliga
  • (nb) norsk
  • (mo) молдовеняскэ
  • (tpi) Tok Pisin
  • (bto) Iriga Bicolano
  • (kcg) Tyap
  • (lo) ລາວ
  • (ko) 한국어
  • (fiu-vro) võro
  • (szl) ślůnski
  • (rsk) руски
  • (sah) саха тыла
  • (bn) বাংলা
  • (anp) अंगिका
  • (lrc) لۊری شومالی
  • (yi) ייִדיש
  • (rgn) Rumagnôl
  • (kab) Taqbaylit
  • (inh) гӀалгӀай
  • (nmg) Kwasio
  • (gcf) kréyòl Gwadloup
  • (tn) Setswana
  • (mn) монгол
  • (nn) norsk nynorsk
  • (vro) võro
  • (kn) ಕನ್ನಡ
  • (kjp) ဖၠုံလိက်
  • (kbd) адыгэбзэ
  • (lez) лезги
  • (nqo) ߒߞߏ
  • (lbe) лакку
  • (am) አማርኛ
  • (mhr) олык марий
  • (got) 𐌲𐌿𐍄𐌹𐍃𐌺
  • (gom-deva) गोंयची कोंकणी
  • (qug) Runa shimi
  • (kaa) Qaraqalpaqsha
  • (rm) rumantsch
  • (nrm) Nouormand
  • (om) Oromoo
  • (nod) ᨣᩤᩴᨾᩮᩬᩥᨦ
  • (km) ភាសាខ្មែរ
  • (arc) ܐܪܡܝܐ
  • (sat) ᱥᱟᱱᱛᱟᱲᱤ
  • (grc) Ἀρχαία ἑλληνικὴ
  • (hsn) 湘语
  • (nov) Novial
  • (crh-ro) tatarşa
  • (bqi) بختیاری
  • (yo) Yorùbá
  • (vo) Volapük
  • (new) नेपाल भाषा
  • (sl) slovenščina
  • (tl) Tagalog
  • (chr) ᏣᎳᎩ
  • (pl) polski
  • (ml) മലയാളം
  • (nl) Nederlands
  • (kl) kalaallisut
  • (vot) Vaďďa
  • (nys) Nyunga
  • (el) Ελληνικά
  • (ku-arab) كوردي (عەرەبی)
  • (mad) Madhurâ
  • (shn) ၽႃႇသႃႇတႆး
  • (lad) Ladino
  • (bgn) روچ کپتین بلوچی
  • (tcy) ತುಳು
  • (ku-latn) kurdî (latînî)
  • (nge) Ngémba
  • (jam) Patois
  • (zh-tw) 中文(臺灣)
  • (zh-sg) 中文(新加坡)
  • (zh-my) 中文(马来西亚)
  • (zh-mo) 中文(澳門)
  • (kai) Karai-karai
  • (ro) română
  • (alt) алтай тил
  • (zh-hans) 中文(简体)
  • (yue-hans) 粵语(简体)
  • (shi-latn) Taclḥit
  • (zgh) ⵜⴰⵎⴰⵣⵉⵖⵜ ⵜⴰⵏⴰⵡⴰⵢⵜ
  • (zea) Zeêuws
  • (zh-cn) 中文(中国大陆)
  • (mos) moore
  • (uz) oʻzbekcha / ўзбекча
  • (gan) 贛語
  • (tw) Twi
  • (ota) لسان عثمانى
  • (ybb) Yemba
  • (bho) भोजपुरी
  • (yas) Nugunu
  • (xsy) saisiyat
  • (xmf) მარგალური
  • (pi) पालि
  • (sco) Scots
  • (wuu-hant) 吳語(正體)
  • (wuu) 吴语
  • (wo) Wolof
  • (ady) адыгабзэ
  • (dz) ཇོང་ཁ
  • (war) Winaray
  • (vmf) Mainfränkisch
  • (liv) Līvõ kēļ
  • (hz) Otsiherero
  • (ike-cans) ᐃᓄᒃᑎᑐᑦ
  • (zu) isiZulu
  • (vi) Tiếng Việt
  • (vec) vèneto
  • (ve) Tshivenda
  • (uz-latn) oʻzbekcha
  • (uz-cyrl) ўзбекча
  • (uk) українська
  • (kjh) хакас
  • (kk-arab) قازاقشا (تٴوتە)
  • (isu) Isu
  • (lns) Lamnso'
  • (ug-latn) Uyghurche
  • (ug-arab) ئۇيغۇرچە
  • (udm) удмурт
  • (tyv) тыва дыл
  • (ty) reo tahiti
  • (my) မြန်မာဘာသာ
  • (yue) 粵語
  • (cak) Kaqchikel
  • (tvu) Tunen
  • (ttj) Orutooro
  • (hak) 客家語/Hak-kâ-ngî
  • (tt-cyrl) татарча
  • (lem) Nomaande
  • (guc) wayuunaiki
  • (de-ch) Schweizer Hochdeutsch
  • (cdo) 閩東語 / Mìng-dĕ̤ng-ngṳ̄
  • (trv) Seediq
  • (tr) Türkçe
  • (hy) հայերեն
  • (chy) Tsetsêhestâhese
  • (acm) عراقي
  • (olo) livvinkarjala
  • (ann) Obolo
  • (tet) tetun
  • (pnb) پنجابی
  • (kbd-cyrl) адыгэбзэ
  • (jbo) la .lojban.
  • (nog) ногайша
  • (szy) Sakizaya
  • (ksh) Ripoarisch
  • (th) ไทย
  • (arq) جازايرية
  • (kk-kz) қазақша (Қазақстан)
  • (bxr) буряад
  • (lfn) Lingua Franca Nova
  • (sms) nuõrttsääʹmǩiõll
  • (sdh) کوردی خوارگ
  • (ky) кыргызча
  • (bat-smg) žemaitėška
  • (vls) West-Vlams
  • (tdd) ᥖᥭᥰᥖᥬᥳᥑᥨᥒᥰ
  • (pcd) Picard
  • (nla) Ngombala
  • (hno) ہندکو
  • (pap-aw) Papiamento
  • (sw) Kiswahili
  • (kk-tr) qazaqşa (Türkïya)
  • (pcm) Naijá
  • (pfl) Pälzisch
  • (su) Sunda
  • (shy) tacawit
  • (aeb) تونسي / Tûnsî
  • (srq) mbia cheë
  • (hu-formal) magyar (formal)
  • (mua) Mundang
  • (ks-deva) कॉशुर
  • (sro) sardu campidanesu
  • (srn) Sranantongo
  • (sr-el) srpski (latinica)
  • (sr-ec) српски (ћирилица)
  • (lki) لەکی
  • (bcc) جهلسری بلوچی
  • (be-x-old) беларуская (тарашкевіца)
  • (rue) русиньскый
  • (lmo) lombard
  • (nah) Nāhuatl
  • (ka) ქართული
  • (ia) interlingua
  • (rki) ရခိုင်
  • (gan-hant) 贛語(繁體)
  • (stq) Seeltersk
  • (pa) ਪੰਜਾਬੀ
  • (smj) julevsámegiella
  • (ru) русский
  • (prg) prūsiskan
  • (lij) Ligure
  • (skr) سرائیکی
  • (mag) मगही
  • (blk) ပအိုဝ်ႏဘာႏသာႏ
  • (pag) Pangasinan
  • (mnc-latn) manju gisun
  • (hil) Ilonggo
  • (kw) kernowek
  • (pam) Kapampangan
  • (crh-cyrl) къырымтатарджа (Кирилл)
  • (ban-bali) ᬩᬲᬩᬮᬶ
  • (zh-hk) 中文(香港)
  • (mcn) vùn màsànà
  • (tly-cyrl) толыши
  • (sv) svenska
  • (ln) lingála
  • (bci) wawle
  • (scn) sicilianu
  • (zh-hant) 中文(繁體)
  • (csb) kaszëbsczi
  • (sgs) žemaitėška
  • (kk-cyrl) қазақша (кирил)
  • (cpx-hans) 莆仙语(简体)
  • (osa-latn) Wažáže íe
  • (ta) தமிழ்
  • (mni) ꯃꯤꯇꯩ ꯂꯣꯟ
  • (wa) walon
  • (sdc) Sassaresu
  • (rmy) romani čhib
  • (jv) Jawa
  • (cv) чӑвашла
  • (dv) ދިވެހިބަސް
  • (ks-arab) کٲشُر
  • (ruq) Vlăheşte
  • (sa) संस्कृतम्
  • (ruq-latn) Vlăheşte
  • (ruq-cyrl) Влахесте
  • (rmf) kaalengo tšimb
  • (kv) коми
  • (lv) latviešu
  • (ilo) Ilokano
  • (gld) на̄ни
  • (diq) Zazaki
  • (din) Thuɔŋjäŋ
  • (la) Latina
  • (li) Limburgs
  • (khw) کھوار
  • (fat) mfantse
  • (ami) Pangcah
  • (mus) Mvskoke
  • (min) Minangkabau
  • (ja) 日本語
  • (av) авар
  • (aeb-latn) Tûnsî
  • (aeb-arab) تونسي
  • (rif) Tarifit
  • (quc) Qatzijob\ʼal
  • (kus) Kʋsaal
  • (loz) Silozi
  • (iu) ᐃᓄᒃᑎᑐᑦ / inuktitut
  • (hu) magyar
  • (gu) ગુજરાતી
  • (awa) अवधी
  • (fa) فارسی
  • (pms) Piemontèis
  • (cu) словѣньскъ / ⰔⰎⰑⰂⰡⰐⰠⰔⰍⰟ
  • (azb) تۆرکجه
  • (qu) Runa Simi
  • (wya) Wyandot
  • (aa) Qafár af
  • (mai) मैथिली
  • (pdt) Plautdietsch
  • (ba) башҡортса
  • (ku) kurdî
  • (bag) Tuki
  • (nit) కొలామి
  • (de-at) Österreichisches Deutsch
  • (wal) wolaytta
  • (xal) хальмг
  • (zh-yue) 粵語
  • (st) Sesotho
  • (tt) татарча / tatarça
  • (niu) Niuē
  • (avk) Kotava
  • (tay) Tayal
  • (nap) Napulitano
  • (frr) Nordfriisk
  • (mzn) مازِرونی
  • (sjd) кӣллт са̄мь кӣлл
  • (nb) norsk bokmål
  • (it) italiano
  • (ltg) latgaļu
  • (mt) Malti
  • (ht) Kreyòl ayisyen
  • (lb) Lëtzebuergesch
  • (ms-arab) بهاس ملايو
  • (mrh) Mara
  • (cpx) 莆仙語 / Pó-sing-gṳ̂
  • (ii) ꆇꉙ
  • (hyw) Արեւմտահայերէն
  • (yav) Yangben
  • (pt) português
  • (sli) Schläsch
  • (lzz) Lazuri
  • (glk) گیلکی
  • (lt) lietuvių
  • (lus) Mizo ţawng
  • (lld) Ladin
  • (krc) къарачай-малкъар
  • (ab) аԥсшәа
  • (ike-latn) inuktitut
  • (rwr) मारवाड़ी
  • (bkm) Kom
  • (kiu) Kırmancki
  • (fit) meänkieli
  • (gom) गोंयची कोंकणी / Gõychi Konknni
  • (cpx-hant) 莆仙語(繁體)
  • (yat) Yambeta
  • (sju) ubmejesámiengiälla
  • (sc) sardu
  • (tly) tolışi
  • (oc) occitan

The previous list was generated by:

{{#invoke:Languages|forEachLanguage|preprocess=yes|pattern=<nowiki />
* <span style="font-size:smaller;">([[MediaWiki:Lang/$lc|<span style="font-family:monospace,monospace;" title="{{((}}#language:$lc{{!}}en{{))}}">{{((}}int{{!}}lang/$lc{{))}}</span>]])</span> <bdi lang="$lc" class="autonym lang-$lc">{{((}}#language:$lc{{))}}</bdi>
}}

Note that as of 2020-10-18, there's a new bug in Scribunto, which causes the standard "table.sort()" function to no longer accept a standard comparison function. Now when "table.sort()" fails, the error is correctly catched (instead of producing a visible error), but the list may not be sorted correctly (temporarily) in some cases. The bug is tracked and corrected in Mediawiki but waiting to be deployed with the fix. Nothing will need to be changed (using "perror()" will then no longer have any effect, it is just needed for now and the bug was not a bug of this module which was properly tested and sudddently failed unexpectedly). Thanks.

Note:

  • The list is retrieved using Module:Languages/List and sorted in native language name (LTR languages before RTL languages, then each one sorted by native script and then a locale-neutral sort order within each script) using Module:Multilingual description/sort (which is the consistant sort order used for multilingual navigation navigation boxes, or for showing lists of translations in multilingual descriptions, in a user-friendly way). For seeing the complete list of languages, tested with their directionality, look at the tests results table on Module talk:Multilingual description/sort/testcases.

Code

--[=[
Not globally exposed. Internal function only.

language_subpages( frame, transform, options )
Parameters
    frame:     The frame that was passed to the method invoked. The first argument or the page argument will be respected.
    transform: A transform function. Example: function( basepagename, subpagename, code, langname ) end
    options:   An object with options. Example: { abort= { on=function() end, time=0.8 }  }
        Following options are available:
        abort: Aborts iterating over the subpages if one of the conditions is met. If the process is aborted, nil is returned!
            on: Function to be called if an abort-condition was met.
            cycles: The maximum number of subpages to run over.
            time: Maximum time to spend running over the subpages.

]=]
local function language_subpages( frame, transform, options )
    local args, pargs, options = frame.args, ( frame:getParent() or {} ).args or {}, options or {};
    local title = args.page or args[1] or pargs.page or pargs[1] or "";
    local abort = options.abort or {};
    local at, clock = type( abort.on ), os.clock();
    local ac = function()
        if  at == 'function' or ( at == 'table' and getmetatable(abort.on).__call ) then
            abort.on();
        end
    end
    local tt = type( transform );
    local page = require( 'Module:Page' );

    title = page.clean(title);

    if tt == 'function' or ( tt == 'table' and getmetatable(transform).__call ) then
        local fetch, pages, langcode, langname = mw.language.fetchLanguageName, {};
--[==[

     / \
    / | \
   /  ·  \
   ¯¯¯¯¯¯¯
   Page.subpages() no longer works because it attempted to parse the HTML content generated by
   calling the parser function "Special:Prefixindex:" which is no longer expanded in Lua but
   converted to a "stripped tag" (containing a unique identifier surrounded by ASCII DEL characters)
   representing the tag name and its parameters.
   The actual expansion of stripped tags can no longer be performed in Lua.
   Now unstripping these tags just kills ALL these tags (except "wiki" tags) instead of performing
   their expansion by running the extension code. Only MediaWiki can unstrip these tags in texts after
   they have been returned by Lua.
   For this reason, page.subpages() is now completely empty (Module:Page no longer works).
   This cannot be bypassed, except by using a Scribunto extension library if lifting the limits set by mw.unstrip.
   Note that "Special:Prefixindex:" is also costly, even if it just requires a single database query to
   get all subpages, instead of one costly #ifexist or one costly mw.title() property reading per
   tested subpage to know if it exists.
   For now there's still no reliable way to get a list of subpages, or performing queries similar to
   the [[Special:Prefixindex]] page or list members of a category like when viewing a category page.
   Ideally, there should exist a method for such queries on Title objects returned by the mw.title library;
   but for now there's none.
   In Lua now, the only expansion possible with an immediate effect is the expansion of standard templates,
   all special tags or special pages, or parser function extensions do not work (Only the #expr parser
   function is supported by using an external Scribunto library).
--]==]
        for pg in page.subpages( title, { ignoreNS=true } ) do
            if abort.cycles then
                abort.cycles = abort.cycles - 1
                if 0 == abort.cycles then return ac()  end
            end
            if abort.time then
                if (os.clock() - clock) > abort.time then return ac()  end
            end
            if mw.ustring.len( pg ) <= 12 then
                langcode = string.lower( pg );
                langname = fetch( langcode );
                if langname ~= '' then
                    table.insert( pages, transform( title, pg, langcode, langname ) );
                end
            end
        end
        return pages;
    end
    return {};
end

local function cloneArgs(frame)
    local args, pargs = {}, {}
    for k,v in pairs( frame.args ) do args[k] = v end
    if frame:getParent() then
        for k,v in pairs( frame:getParent().args ) do pargs[k] = v end
    end
    return args, pargs
end



local p = {};

--[=[
Usage:
{{#invoke:languages|internal|Template:Adjective}}
]=]
function p.internal(frame)
    return table.concat(
        language_subpages( frame,
            function( title, page, code, name )
                return mw.ustring.format(
                    '<bdi class="language lang-%s" lang="%s">[[%s/%s|%s]]</bdi>',
                    code, code,
                    title, page,
                    name
                );
            end
        ),
        '&nbsp;<b>·</b>&#32;'
    );
end

--[=[
Usage:
{{#invoke:languages|external|Template:Adjective}}
]=]
function p.external(frame)
    return table.concat(
        language_subpages( frame,
            function( title, page, code, name )
                return mw.ustring.format(
                    '<bdi class="language lang-%s" lang="%s">[%s/%s %s]</bdi>',
                    code, code,
                    tostring( mw.uri.fullUrl( title ) ), page:gsub( ' ', '_' ),
                    name
                );
            end
        ),
        '&nbsp;<b>·</b>&#32;'
    );
end

--[=[
forEachLanguage

This function iterates over all language codes known to MediaWiki based on a maintained list
replacing patterns in a pattern-string for each language

Usage
{{#invoke:Languages|forEachLanguage
  |pattern=patternstring
  |before=string to insert before iteration
  |after=string added after iteration
  |sep=separator string between iterations
  |inLang=langcode used for $lnTrP and $lnTrUC1
}}

Parameters
    pattern: A pattern string which is processed for each language and which is concatenated at the end and returned as one string
    before: A string that is inserted before the concatenated result
    after: A string that is inserted after the concatenated result
    sep: A string that is inserted between each line created from the pattern while iterating (like ProcessedPattern_sep_ProcessedPattern_sep_ProcessedPattern)
    inLang: Langcode to use for $lnTrP and $lnTrUC1
    preprocess: if set to a non-empty value, the output will be preprocessed before being returned.

Warning
    The output is still not prepreprocessed by default: so parser functions and magic keywords generated by the pattern are still not executed and replaced,
    and template transclusions are still not expanded (see examples in other functions in this module).
    When using this function directly from a MediaWiki page or template, this means it is only possible to use patterns generating basic MediaWiki formatting
    or HTML tags. It you want the output to be preprocessed (in the given frame), set the preprocess parameter to a non-empty string.
    
Patterns
    $lc - language code such as en or de
    $lnP - language name in own language (autonym)
    $lnUC1 - language name in own language (autonym), first letter upper case
    $lnTrP - language name translated to the language requested by language code passed to inLang
    $lnTrUC1 - language name translated to the language requested by language code passed to inLang, first letter upper case

Example
    {{#invoke:Languages|forEachLanguage|pattern=<span lang="$lc" xml:lang="$lc" class="language lang-$lc">[[Page/$lc|$lnP]]</span>}}
]=]

-- =p.forEachLanguage({ args= { pattern = "$lc - $lnTrP\n", inLang = "en" } })
function p.forEachLanguage(frame)
    local l = require("Module:Languages/List")

    local ret = {}
    local lang    = mw.language
    local line
    local pattern = frame.args.pattern   or frame.args[1] or ""
    local prefix  = frame.args.before    or frame.args[2] or ""
    local postfix = frame.args.after     or frame.args[3] or ""
    local sep     = frame.args.sep       or frame.args.separator or frame.args[4] or ""
    local inLang  = frame.args.inLang    or frame.args[5] or nil
    local preprocess = frame.args.preprocess or frame.args[6] or ""

    local langNameUCFirstReq           = not not pattern:find( "$lnUC1", 1, true )
    local langNameReq                  = not not pattern:find( "$lnP", 1, true ) or langNameUCFirstReq
    local langNameTranslatedUCFirstReq = not not pattern:find( "$lnTrUC1", 1, true )
    local langNameTranslatedReq        = not not pattern:find( "$lnTrP", 1, true ) or langNameTranslatedUCFirstReq
    local contentLangInstance = mw.language.getContentLanguage()
    local inLangLangInstance
    local l = mw.language.fetchLanguageNames() -- autonyms
    local lTr
    local lcIdList = require('Module:Languages/List').getSortedList( l )

    if langNameTranslatedReq then
        inLangLangInstance = --[==[
            mw.getLanguage( inLang ) -- Quota hit in :ucfirst() if using too many langInstances
            --]==] contentLangInstance
        lTr = mw.language.fetchLanguageNames( inLang ) -- translated names
    end

    for _, lcId in pairs( lcIdList ) do
        local subst = lcId:gsub('%%', '%%%%')
        line = pattern:gsub( "%$lc", subst )
        local langName, langInstance
        -- autonym (name of lcId in locale lcId)
        if langNameReq then
            langName = l[lcId]
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnP", subst )
        end
        if langNameUCFirstReq then
            langInstance = --[==[
                mw.getLanguage( lcId ) -- Quota hit in :ucfirst() if using too many langInstances
                --]==] contentLangInstance
            langName = langInstance:ucfirst( langName )
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnUC1", subst )
        end

        -- translated name (name of lcId in locale inLang)
        if langNameTranslatedReq then
            langName = lTr[lcId]
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnTrP", subst )
        end
        if langNameTranslatedUCFirstReq then
            langName = inLangLangInstance:ucfirst( langName )
            subst = langName:gsub('%%', '%%%%')
            line = line:gsub( "%$lnTrUC1", subst )
        end

        table.insert(ret, line)
    end
    ret = prefix .. table.concat( ret, sep ) .. postfix
    if preprocess ~= '' then
        ret = frame:preprocess(ret)
    end
    return ret
end

--[=[
 Provide logic for [[Template:Lle]] (Language Links external, to be substituted, language names written exactly as #language would provide them)
 Warning: may expands too many costly #ifexist without limitation (if not substituted into a separate "/lang" template)
]=]
function p.lle(frame)
    return frame:preprocess(
        p.forEachLanguage({
            args = {
                pattern = '{{subst:#ifexist:{{{1}}}/$lc|[{{subst:fullurl:{{{1}}}/$lc}} <bdi class="language lang-$lc" lang="$lc">$lnP</bdi>]&nbsp;<b>∙</b>&#32;<!--\n-->}}'
            }
        })
    )
end

--[=[
 Provide logic for [[Template:Ll]] (Language Links internal, to be substituted, language names written exactly as #language would provide them)
 Warning: may expands too many costly #ifexist without limitation (if not substituted into a separate "/lang" template)
]=]
function p.ll(frame)
    return frame:preprocess(
        p.forEachLanguage({
            args = {
                pattern = '{{subst:#ifexist:{{{1}}}/$lc|[[{{{1}}}/$lc|<bdi class="language lang-$lc" lang="$lc">$lnP</bdi>]]&nbsp;<b>∙</b>&#32;<!--\n-->}}'
            }
        })
    )
end


--------------------------------------------------------
--- Different approaches for [[Template:Lang links]] ---
--------------------------------------------------------

--[=[
 Provide logic for [[Template:Lang links]]
 Using a cute Hybrid-Method:
    First check the subpages which is quite fast; if there are too many fall back to checking for each language page individually
]=]

-- =p.langLinksNonExpensive({ args= { page='Commons:Picture of the Year/2010' }, getParent=function() end })
-- =p.langLinksNonExpensive({ args= { page='Main Page' }, getParent=function() end })
-- =p.langLinksNonExpensive({ args= { page='Template:No_source_since' }, getParent=function() end })
-- =p.langLinksNonExpensive({ args= { page='MediaWiki:Gadget-HotCat' }, getParent=function() end })
function p.langLinksNonExpensive(frame)
    local args, pargs = frame.args, ( frame:getParent() or {} ).args or {};
    local title = args.page or args[1] or pargs.page or pargs[1] or "";
    local contentLangInstance = mw.language.getContentLanguage();
    local pages2
    if frame.preprocess == nil then
        frame = mw.getCurrentFrame()
    end
--[==[
    local options = {
        abort = {
            time = 3.5,
            on = function()
                pages2 = p.forEachLanguage({
                    args = {
                       pattern = '{{#ifexist:' .. title .. '/$lc|[[' .. title .. '/$lc|<bdi lang="$lc">$lnP</bdi>]]&nbsp;<b>∙</b>&#32;}}'
                    }
                })
            end
        }
    }
    local pages = language_subpages( frame,
        function( title, page, code, langname )
            return mw.ustring.format(
                '[[%s/%s|<bdi lang="%s">%s</bdi>]]</span>&nbsp;<b>∙</b>&#32;',
                title, page, code, langname
            )
        end, options );
    return pages2 and frame:preprocess(pages2) or table.concat(pages, '');
--]==]
    return frame:preprocess(
        p.forEachLanguage( {
            args = {
                pattern = '{{#ifexist:' .. title .. '/$lc|[[' .. title .. '/$lc|<bdi lang="$lc">$lnP</bdi>]]&nbsp;<b>∙</b>&#32;}}'
            }
        })
    )
end

---------------------------------------------------------
----------------- [[Template:Autolang]] -----------------
---------------------------------------------------------
--[[
  Works like {{autotranslate}} just allowing an unlimited number of arguments, even named arguments.
  It's doing Magic! No arguments should be passed to {{#invoke:}}
]]

function p.autolang(frame)
    local args, pargs = cloneArgs( frame )
    if nil == args.useargs then
        if not args.base then args = pargs end
    elseif 'both' == args.useargs then
        for k,v in pairs(args) do pargs[k] = v end
        args = pargs
    elseif 'parent' == args.useargs then
        args = pargs
        if pargs.base and not args.base then
            args.base = pargs.base
        end
    end
    local base = args.base
    local userlang = frame:callParserFunction('int', 'lang')
    local tl, tlns = 'Template:', 10
    local tlb, fallback1, currenttemplate, currenttemplatepage
    local fallback, contentlang = mw.text.split( userlang, '-', true )[1], mw.language.getContentLanguage():getCode()

    local function createReturn(title)
        local ret
        local tlargs = {}
         -- When LUA is invoked, templates are already expanded. This must be respected.
        return frame:expandTemplate{ title = title, args = args }
    end

    if not base then
        return ("'autolang' in [[Module:Languages]] was called but the 'base' parameter could not be found." ..
            "The base parameter specifies the template that's subpages will be sought for a suitable translation.")
    end
    tlb = tl .. base .. '/'

    currenttemplate = tlb .. userlang
    currenttemplatepage = mw.title.new( currenttemplate, tlns )
    if currenttemplatepage and currenttemplatepage.exists then
        return createReturn(currenttemplate)
    end

    fallback1 = frame:preprocess( '{{Fallback|1=' .. base .. '|2=' .. userlang .. '}}' )
    if fallback1 ~= contentlang then
        return createReturn(tlb .. fallback1)
    end

    currenttemplate = tlb .. fallback
    currenttemplatepage = mw.title.new( currenttemplate, tlns )
    if currenttemplatepage and currenttemplatepage.exists then
        return createReturn(currenttemplate)
    end

    currenttemplate = tlb .. contentlang
    currenttemplatepage = mw.title.new( currenttemplate, tlns )
    if currenttemplatepage and currenttemplatepage.exists then
        return createReturn(currenttemplate)
    end
    return createReturn(tl .. base)
end

--[=[
Usage:
{{#invoke:languages|isKnownLanguageTag|gsw}} -> 1
{{#invoke:languages|isKnownLanguageTag|doesNotExist}} ->
]=]
function p.isKnownLanguageTag(frame)
    return mw.language.isKnownLanguageTag( frame.args[1] or frame.args.tag or frame.args.code or '' ) and '1' or ''
end

function p.file_languages(frame)
    local M_link = require( 'Module:Link' )
    local contentLangInstance = mw.language.getContentLanguage()
    local pattern = frame.args.pattern or '%s (%s)'
    local original = frame.args.original or mw.title.getCurrentTitle().text
    local ext_start, _ = string.find( original, '\.%w+$' )
    local file_ext = string.sub( original, ext_start )
    original = string.sub( original, 0, ext_start - 1 )
    return frame:preprocess(
        '<gallery>\n' ..
        (table.concat(
            M_link.forEachLink(
                p.forEachLanguage({
                    args = { pattern = '[[$lc]]' }
                }),
                function( linkInfo )
                    local filename = mw.ustring.format( pattern, original, linkInfo.text ) .. file_ext
                    local filepage = mw.title.new( filename, 6 )
                    if filepage and filepage.exists then
                        return mw.ustring.format( '%s|%s',
                            filename,
                            mw.language.fetchLanguageName( linkInfo.text )
                        )
                    else
                        return nil
                    end
                end
            ), '\n'
        )) ..
        '\n</gallery>'
    )
end

function p.runTests()
    return p.langLinksNonExpensive({
        args = {
            page = 'Module:Languages/testcases/test'
        },
        getParent = function() end
    }) ==
        '[[Module:Languages/testcases/test/de|<bdi lang="de">Deutsch</bdi>]]&nbsp;<b>∙</b>&#32;' ..
        '[[Module:Languages/testcases/test/en|<bdi lang="en">English</bdi>]]&nbsp;<b>∙</b>&#32;'
end

return p;