Parser variables, behavior switches, and parser functions in MediaWiki.
Magic words are localizable keywords in wikitext that the parser recognizes and replaces with dynamic values or that control parser behavior. From magicword.md:
Magic words are localizable keywords used in wikitext. They are used for many small fragments of text, including the names of parser functions, the names of variables, double-underscore behavior switches, and image link parameter names.
Each magic word has a unique ID, a case-sensitivity flag, and a list of synonyms. The MagicWord class matches wikitext against these synonyms by compiling them into a regular expression.
Double-underscore keywords that toggle parser behavior. Examples: __TOC__, __NOTOC__, __NOINDEX__, __FORCETOC__. They produce no output but modify how the page is rendered.
Variables
Transclusion-style keywords that expand to dynamic values. Examples: {{PAGENAME}}, {{CURRENTDAY}}, {{NUMBEROFARTICLES}}. They take no arguments.
Parser functions
Variable-style keywords that accept arguments: {{urlencode:foo bar}}, {{#if: condition | then | else }}. The #-prefixed form is conventional for extension-defined functions.
Image parameters
Keywords used inside [[File:...]] syntax to control image rendering: thumb, right, left, center, frameless.
Create a file named ExtensionName.i18n.magic.php. The array is keyed by language code, then by magic word ID. Index 0 is the case sensitivity flag (0 = case-insensitive, 1 = case-sensitive); subsequent indices are synonyms.
Check ParserOutput in your hook to detect whether the switch was used:
// In an OutputPageParserOutput hook, or similar:public static function onOutputPageParserOutput( OutputPage $out, ParserOutput $parserOutput): void { if ( $parserOutput->getPageProperty( 'mag_nosidebar' ) !== null ) { // Page used __NOSIDEBAR__, apply the effect }}
The MagicWord class provides methods for matching text against a magic word:
$mwFactory = MediaWikiServices::getInstance()->getMagicWordFactory();$mw = $mwFactory->get( 'redirect' );if ( $mw->match( $text ) ) { // $text is a redirect keyword in the content language}// Match and remove from a stringif ( $mw->matchAndRemove( $text ) ) { // $text was modified in-place, keyword stripped}// Match any magic word from a list$mwArray = $mwFactory->newArray( [ 'redirect', 'img_right', 'img_left' ] );$matched = $mwArray->matchAndRemove( $text );
Avoid extracting raw synonym lists from MagicWord and writing special-case string comparisons. Add a new match()-style method to the MagicWord or MagicWordArray class if the built-in matching methods don’t cover your use case.