1 /* eslint-disable no-restricted-properties */
3 * Experimental advanced wikitext parser-emitter.
4 * See: https://www.mediawiki.org/wiki/Extension:UploadWizard/MessageParser for docs
6 * @author neilk@wikimedia.org
7 * @author mflaschen@wikimedia.org
16 slice
= Array
.prototype.slice
,
19 PAGENAME
: mw
.config
.get( 'wgPageName' ),
20 PAGENAMEE
: mw
.util
.wikiUrlencode( mw
.config
.get( 'wgPageName' ) )
22 // Whitelist for allowed HTML elements in wikitext.
23 // Self-closing tags are not currently supported.
24 // Can be populated via setParserDefaults().
25 allowedHtmlElements
: [],
26 // Key tag name, value allowed attributes for that tag.
27 // See Sanitizer::setupAttributeWhitelist
28 allowedHtmlCommonAttributes
: [
41 // Attributes allowed for specific elements.
42 // Key is element name in lower case
43 // Value is array of allowed attributes for that element
44 allowedHtmlAttributesByElement
: {},
45 messages
: mw
.messages
,
46 language
: mw
.language
,
48 // Same meaning as in mediawiki.js.
50 // Only 'text', 'parse', and 'escaped' are supported, and the
51 // actual escaping for 'escaped' is done by other code (generally
52 // through mediawiki.js).
54 // However, note that this default only
55 // applies to direct calls to jqueryMsg. The default for mediawiki.js itself
56 // is 'text', including when it uses jqueryMsg.
61 * Wrapper around jQuery append that converts all non-objects to TextNode so append will not
62 * convert what it detects as an htmlString to an element.
64 * If our own HtmlEmitter jQuery object is given, its children will be unwrapped and appended to
67 * Object elements of children (jQuery, HTMLElement, TextNode, etc.) will be left as is.
70 * @param {jQuery} $parent Parent node wrapped by jQuery
71 * @param {Object|string|Array} children What to append, with the same possible types as jQuery
72 * @return {jQuery} $parent
74 function appendWithoutParsing( $parent
, children
) {
77 if ( !Array
.isArray( children
) ) {
78 children
= [ children
];
81 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
82 if ( typeof children
[ i
] !== 'object' ) {
83 children
[ i
] = document
.createTextNode( children
[ i
] );
85 if ( children
[ i
] instanceof $ && children
[ i
].hasClass( 'mediaWiki_htmlEmitter' ) ) {
86 children
[ i
] = children
[ i
].contents();
90 return $parent
.append( children
);
94 * Decodes the main HTML entities, those encoded by mw.html.escape.
97 * @param {string} encoded Encoded string
98 * @return {string} String with those entities decoded
100 function decodePrimaryHtmlEntities( encoded
) {
102 .replace( /'/g, '\'' )
103 .replace( /"/g, '"' )
104 .replace( /</g, '<' )
105 .replace( />/g, '>' )
106 .replace( /&/g, '&' );
110 * Turn input into a string.
113 * @param {string|jQuery} input
114 * @return {string} Textual value of input
116 function textify( input
) {
117 if ( input
instanceof $ ) {
118 input
= input
.text();
120 return String( input
);
124 * Given parser options, return a function that parses a key and replacements, returning jQuery object
126 * Try to parse a key and optional replacements, returning a jQuery object that may be a tree of jQuery nodes.
127 * If there was an error parsing, return the key and the error message (wrapped in jQuery). This should put the error right into
128 * the interface, without causing the page to halt script execution, and it hopefully should be clearer how to fix it.
131 * @param {Object} options Parser options
133 * @return {Array} return.args First element is the key, replacements may be in array in 2nd element, or remaining elements.
134 * @return {jQuery} return.return
136 function getFailableParserFn( options
) {
137 return function ( args
) {
139 parser
= new mw
.jqueryMsg
.Parser( options
),
141 argsArray
= Array
.isArray( args
[ 1 ] ) ? args
[ 1 ] : slice
.call( args
, 1 );
143 return parser
.parse( key
, argsArray
);
145 fallback
= parser
.settings
.messages
.get( key
);
146 mw
.log
.warn( 'mediawiki.jqueryMsg: ' + key
+ ': ' + e
.message
);
147 mw
.track( 'mediawiki.jqueryMsg.error', {
149 errorMessage
: e
.message
151 return $( '<span>' ).text( fallback
);
159 * Initialize parser defaults.
161 * ResourceLoaderJqueryMsgModule calls this to provide default values from
162 * Sanitizer.php for allowed HTML elements. To override this data for individual
163 * parsers, pass the relevant options to mw.jqueryMsg.Parser.
166 * @param {Object} data New data to extend parser defaults with
167 * @param {boolean} [deep=false] Whether the extend is done recursively (deep)
169 mw
.jqueryMsg
.setParserDefaults = function ( data
, deep
) {
171 $.extend( true, parserDefaults
, data
);
173 $.extend( parserDefaults
, data
);
178 * Get current parser defaults.
180 * Primarily used for the unit test. Returns a copy.
185 mw
.jqueryMsg
.getParserDefaults = function () {
186 return $.extend( {}, parserDefaults
);
190 * Returns a function suitable for static use, to construct strings from a message key (and optional replacements).
194 * var format = mediaWiki.jqueryMsg.getMessageFunction( options );
195 * $( '#example' ).text( format( 'hello-user', username ) );
197 * Tthis returns only strings, so it destroys any bindings. If you want to preserve bindings, use the
198 * jQuery plugin version instead. This was originally created to ease migration from `window.gM()`,
199 * from a time when the parser used by `mw.message` was not extendable.
201 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
202 * somefunction( a, b, c, d )
204 * somefunction( a, [b, c, d] )
206 * @param {Object} options parser options
207 * @return {Function} Function The message formatter
208 * @return {string} return.key Message key.
209 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
210 * @return {string} return.return Rendered HTML.
212 mw
.jqueryMsg
.getMessageFunction = function ( options
) {
213 var failableParserFn
, format
;
215 if ( options
&& options
.format
!== undefined ) {
216 format
= options
.format
;
218 format
= parserDefaults
.format
;
223 if ( !failableParserFn
) {
224 failableParserFn
= getFailableParserFn( options
);
226 failableResult
= failableParserFn( arguments
);
227 if ( format
=== 'text' || format
=== 'escaped' ) {
228 return failableResult
.text();
230 return failableResult
.html();
236 * Returns a jQuery plugin which parses the message in the message key, doing replacements optionally, and appends the nodes to
237 * the current selector. Bindings to passed-in jquery elements are preserved. Functions become click handlers for [$1 linktext] links.
240 * $.fn.msg = mediaWiki.jqueryMsg.getPlugin( options );
241 * var $userlink = $( '<a>' ).click( function () { alert( "hello!!" ) } );
242 * $( 'p#headline' ).msg( 'hello-user', $userlink );
244 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
245 * somefunction( a, b, c, d )
247 * somefunction( a, [b, c, d] )
249 * We append to 'this', which in a jQuery plugin context will be the selected elements.
251 * @param {Object} options Parser options
252 * @return {Function} Function suitable for assigning to jQuery plugin, such as jQuery#msg
253 * @return {string} return.key Message key.
254 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
255 * @return {jQuery} return.return
257 mw
.jqueryMsg
.getPlugin = function ( options
) {
258 var failableParserFn
;
262 if ( !failableParserFn
) {
263 failableParserFn
= getFailableParserFn( options
);
265 $target
= this.empty();
266 appendWithoutParsing( $target
, failableParserFn( arguments
) );
273 * Describes an object, whose primary duty is to .parse() message keys.
277 * @param {Object} options
279 mw
.jqueryMsg
.Parser = function ( options
) {
280 this.settings
= $.extend( {}, parserDefaults
, options
);
281 this.settings
.onlyCurlyBraceTransform
= ( this.settings
.format
=== 'text' || this.settings
.format
=== 'escaped' );
284 this.emitter
= new mw
.jqueryMsg
.HtmlEmitter( this.settings
.language
, this.settings
.magic
);
286 // Backwards-compatible alias
287 // @deprecated since 1.31
288 mw
.jqueryMsg
.parser
= mw
.jqueryMsg
.Parser
;
290 mw
.jqueryMsg
.Parser
.prototype = {
292 * Where the magic happens.
293 * Parses a message from the key, and swaps in replacements as necessary, wraps in jQuery
294 * If an error is thrown, returns original key, and logs the error
296 * @param {string} key Message key.
297 * @param {Array} replacements Variable replacements for $1, $2... $n
300 parse: function ( key
, replacements
) {
301 var ast
= this.getAst( key
);
302 return this.emitter
.emit( ast
, replacements
);
306 * Fetch the message string associated with a key, return parsed structure. Memoized.
307 * Note that we pass '⧼' + key + '⧽' back for a missing message here.
309 * @param {string} key
310 * @return {string|Array} string of '⧼key⧽' if message missing, simple string if possible, array of arrays if needs parsing
312 getAst: function ( key
) {
315 if ( !Object
.prototype.hasOwnProperty
.call( this.astCache
, key
) ) {
316 wikiText
= this.settings
.messages
.get( key
);
317 if ( typeof wikiText
!== 'string' ) {
318 wikiText
= '⧼' + key
+ '⧽';
320 this.astCache
[ key
] = this.wikiTextToAst( wikiText
);
322 return this.astCache
[ key
];
326 * Parses the input wikiText into an abstract syntax tree, essentially an s-expression.
328 * CAVEAT: This does not parse all wikitext. It could be more efficient, but it's pretty good already.
329 * n.b. We want to move this functionality to the server. Nothing here is required to be on the client.
331 * @param {string} input Message string wikitext
333 * @return {Mixed} abstract syntax tree
335 wikiTextToAst: function ( input
) {
337 regularLiteral
, regularLiteralWithoutBar
, regularLiteralWithoutSpace
, regularLiteralWithSquareBrackets
,
338 doubleQuote
, singleQuote
, backslash
, anyCharacter
, asciiAlphabetLiteral
,
339 escapedOrLiteralWithoutSpace
, escapedOrLiteralWithoutBar
, escapedOrRegularLiteral
,
340 whitespace
, dollar
, digits
, htmlDoubleQuoteAttributeValue
, htmlSingleQuoteAttributeValue
,
341 htmlAttributeEquals
, openHtmlStartTag
, optionalForwardSlash
, openHtmlEndTag
, closeHtmlTag
,
342 openExtlink
, closeExtlink
, wikilinkContents
, openWikilink
, closeWikilink
, templateName
, pipe
, colon
,
343 templateContents
, openTemplate
, closeTemplate
,
344 nonWhitespaceExpression
, paramExpression
, expression
, curlyBraceTransformExpression
, result
,
345 settings
= this.settings
,
346 concat
= Array
.prototype.concat
;
348 // Indicates current position in input as we parse through it.
349 // Shared among all parsing functions below.
352 // =========================================================
353 // parsing combinators - could be a library on its own
354 // =========================================================
357 * Try parsers until one works, if none work return null
360 * @param {Function[]} ps
361 * @return {string|null}
363 function choice( ps
) {
366 for ( i
= 0; i
< ps
.length
; i
++ ) {
368 if ( result
!== null ) {
377 * Try several ps in a row, all must succeed or return null.
378 * This is the only eager one.
381 * @param {Function[]} ps
382 * @return {string|null}
384 function sequence( ps
) {
388 for ( i
= 0; i
< ps
.length
; i
++ ) {
390 if ( res
=== null ) {
400 * Run the same parser over and over until it fails.
401 * Must succeed a minimum of n times or return null.
405 * @param {Function} p
406 * @return {string|null}
408 function nOrMore( n
, p
) {
410 var originalPos
= pos
,
413 while ( parsed
!== null ) {
414 result
.push( parsed
);
417 if ( result
.length
< n
) {
426 * There is a general pattern -- parse a thing, if that worked, apply transform, otherwise return null.
428 * TODO: But using this as a combinator seems to cause problems when combined with #nOrMore().
429 * May be some scoping issue
432 * @param {Function} p
433 * @param {Function} fn
434 * @return {string|null}
436 function transform( p
, fn
) {
439 return result
=== null ? null : fn( result
);
444 * Just make parsers out of simpler JS builtin types
449 * @return {string} return.return
451 function makeStringParser( s
) {
455 if ( input
.substr( pos
, len
) === s
) {
464 * Makes a regex parser, given a RegExp object.
465 * The regex being passed in should start with a ^ to anchor it to the start
469 * @param {RegExp} regex anchored regex
470 * @return {Function} function to parse input based on the regex
472 function makeRegexParser( regex
) {
474 var matches
= input
.slice( pos
).match( regex
);
475 if ( matches
=== null ) {
478 pos
+= matches
[ 0 ].length
;
483 // ===================================================================
484 // General patterns above this line -- wikitext specific parsers below
485 // ===================================================================
487 // Parsing functions follow. All parsing functions work like this:
488 // They don't accept any arguments.
489 // Instead, they just operate non destructively on the string 'input'
490 // As they can consume parts of the string, they advance the shared variable pos,
491 // and return tokens (or whatever else they want to return).
492 // some things are defined as closures and other things as ordinary functions
493 // converting everything to a closure makes it a lot harder to debug... errors pop up
494 // but some debuggers can't tell you exactly where they come from. Also the mutually
495 // recursive functions seem not to work in all browsers then. (Tested IE6-7, Opera, Safari, FF)
496 // This may be because, to save code, memoization was removed
498 /* eslint-disable no-useless-escape */
499 regularLiteral
= makeRegexParser( /^[^{}\[\]$<\\]/ );
500 regularLiteralWithoutBar
= makeRegexParser( /^[^{}\[\]$\\|]/ );
501 regularLiteralWithoutSpace
= makeRegexParser( /^[^{}\[\]$\s]/ );
502 regularLiteralWithSquareBrackets
= makeRegexParser( /^[^{}$\\]/ );
503 /* eslint-enable no-useless-escape */
505 backslash
= makeStringParser( '\\' );
506 doubleQuote
= makeStringParser( '"' );
507 singleQuote
= makeStringParser( '\'' );
508 anyCharacter
= makeRegexParser( /^./ );
510 openHtmlStartTag
= makeStringParser( '<' );
511 optionalForwardSlash
= makeRegexParser( /^\/?/ );
512 openHtmlEndTag
= makeStringParser( '</' );
513 htmlAttributeEquals
= makeRegexParser( /^\s*=\s*/ );
514 closeHtmlTag
= makeRegexParser( /^\s*>/ );
516 function escapedLiteral() {
517 var result
= sequence( [
521 return result
=== null ? null : result
[ 1 ];
523 escapedOrLiteralWithoutSpace
= choice( [
525 regularLiteralWithoutSpace
527 escapedOrLiteralWithoutBar
= choice( [
529 regularLiteralWithoutBar
531 escapedOrRegularLiteral
= choice( [
535 // Used to define "literals" without spaces, in space-delimited situations
536 function literalWithoutSpace() {
537 var result
= nOrMore( 1, escapedOrLiteralWithoutSpace
)();
538 return result
=== null ? null : result
.join( '' );
540 // Used to define "literals" within template parameters. The pipe character is the parameter delimeter, so by default
541 // it is not a literal in the parameter
542 function literalWithoutBar() {
543 var result
= nOrMore( 1, escapedOrLiteralWithoutBar
)();
544 return result
=== null ? null : result
.join( '' );
548 var result
= nOrMore( 1, escapedOrRegularLiteral
)();
549 return result
=== null ? null : result
.join( '' );
552 function curlyBraceTransformExpressionLiteral() {
553 var result
= nOrMore( 1, regularLiteralWithSquareBrackets
)();
554 return result
=== null ? null : result
.join( '' );
557 asciiAlphabetLiteral
= makeRegexParser( /^[A-Za-z]+/ );
558 htmlDoubleQuoteAttributeValue
= makeRegexParser( /^[^"]*/ );
559 htmlSingleQuoteAttributeValue
= makeRegexParser( /^[^']*/ );
561 whitespace
= makeRegexParser( /^\s+/ );
562 dollar
= makeStringParser( '$' );
563 digits
= makeRegexParser( /^\d+/ );
565 function replacement() {
566 var result
= sequence( [
570 if ( result
=== null ) {
573 return [ 'REPLACE', parseInt( result
[ 1 ], 10 ) - 1 ];
575 openExtlink
= makeStringParser( '[' );
576 closeExtlink
= makeStringParser( ']' );
577 // this extlink MUST have inner contents, e.g. [foo] not allowed; [foo bar] [foo <i>bar</i>], etc. are allowed
579 var result
, parsedResult
, target
;
581 parsedResult
= sequence( [
583 nOrMore( 1, nonWhitespaceExpression
),
585 nOrMore( 1, expression
),
588 if ( parsedResult
!== null ) {
589 // When the entire link target is a single parameter, we can't use CONCAT, as we allow
590 // passing fancy parameters (like a whole jQuery object or a function) to use for the
591 // link. Check only if it's a single match, since we can either do CONCAT or not for
592 // singles with the same effect.
593 target
= parsedResult
[ 1 ].length
=== 1 ?
594 parsedResult
[ 1 ][ 0 ] :
595 [ 'CONCAT' ].concat( parsedResult
[ 1 ] );
599 [ 'CONCAT' ].concat( parsedResult
[ 3 ] )
604 openWikilink
= makeStringParser( '[[' );
605 closeWikilink
= makeStringParser( ']]' );
606 pipe
= makeStringParser( '|' );
608 function template() {
609 var result
= sequence( [
614 return result
=== null ? null : result
[ 1 ];
617 function pipedWikilink() {
618 var result
= sequence( [
619 nOrMore( 1, paramExpression
),
621 nOrMore( 1, expression
)
623 return result
=== null ? null : [
624 [ 'CONCAT' ].concat( result
[ 0 ] ),
625 [ 'CONCAT' ].concat( result
[ 2 ] )
629 function unpipedWikilink() {
630 var result
= sequence( [
631 nOrMore( 1, paramExpression
)
633 return result
=== null ? null : [
634 [ 'CONCAT' ].concat( result
[ 0 ] )
638 wikilinkContents
= choice( [
643 function wikilink() {
644 var result
, parsedResult
, parsedLinkContents
;
647 parsedResult
= sequence( [
652 if ( parsedResult
!== null ) {
653 parsedLinkContents
= parsedResult
[ 1 ];
654 result
= [ 'WIKILINK' ].concat( parsedLinkContents
);
659 // TODO: Support data- if appropriate
660 function doubleQuotedHtmlAttributeValue() {
661 var parsedResult
= sequence( [
663 htmlDoubleQuoteAttributeValue
,
666 return parsedResult
=== null ? null : parsedResult
[ 1 ];
669 function singleQuotedHtmlAttributeValue() {
670 var parsedResult
= sequence( [
672 htmlSingleQuoteAttributeValue
,
675 return parsedResult
=== null ? null : parsedResult
[ 1 ];
678 function htmlAttribute() {
679 var parsedResult
= sequence( [
681 asciiAlphabetLiteral
,
684 doubleQuotedHtmlAttributeValue
,
685 singleQuotedHtmlAttributeValue
688 return parsedResult
=== null ? null : [ parsedResult
[ 1 ], parsedResult
[ 3 ] ];
692 * Checks if HTML is allowed
694 * @param {string} startTagName HTML start tag name
695 * @param {string} endTagName HTML start tag name
696 * @param {Object} attributes array of consecutive key value pairs,
697 * with index 2 * n being a name and 2 * n + 1 the associated value
698 * @return {boolean} true if this is HTML is allowed, false otherwise
700 function isAllowedHtml( startTagName
, endTagName
, attributes
) {
701 var i
, len
, attributeName
;
703 startTagName
= startTagName
.toLowerCase();
704 endTagName
= endTagName
.toLowerCase();
705 if ( startTagName
!== endTagName
|| settings
.allowedHtmlElements
.indexOf( startTagName
) === -1 ) {
709 for ( i
= 0, len
= attributes
.length
; i
< len
; i
+= 2 ) {
710 attributeName
= attributes
[ i
];
711 if ( settings
.allowedHtmlCommonAttributes
.indexOf( attributeName
) === -1 &&
712 ( settings
.allowedHtmlAttributesByElement
[ startTagName
] || [] ).indexOf( attributeName
) === -1 ) {
720 function htmlAttributes() {
721 var parsedResult
= nOrMore( 0, htmlAttribute
)();
722 // Un-nest attributes array due to structure of jQueryMsg operations (see emit).
723 return concat
.apply( [ 'HTMLATTRIBUTES' ], parsedResult
);
726 // Subset of allowed HTML markup.
727 // Most elements and many attributes allowed on the server are not supported yet.
729 var parsedOpenTagResult
, parsedHtmlContents
, parsedCloseTagResult
,
730 wrappedAttributes
, attributes
, startTagName
, endTagName
, startOpenTagPos
,
731 startCloseTagPos
, endOpenTagPos
, endCloseTagPos
,
734 // Break into three sequence calls. That should allow accurate reconstruction of the original HTML, and requiring an exact tag name match.
735 // 1. open through closeHtmlTag
737 // 3. openHtmlEnd through close
738 // This will allow recording the positions to reconstruct if HTML is to be treated as text.
740 startOpenTagPos
= pos
;
741 parsedOpenTagResult
= sequence( [
743 asciiAlphabetLiteral
,
745 optionalForwardSlash
,
749 if ( parsedOpenTagResult
=== null ) {
754 startTagName
= parsedOpenTagResult
[ 1 ];
756 parsedHtmlContents
= nOrMore( 0, expression
)();
758 startCloseTagPos
= pos
;
759 parsedCloseTagResult
= sequence( [
761 asciiAlphabetLiteral
,
765 if ( parsedCloseTagResult
=== null ) {
766 // Closing tag failed. Return the start tag and contents.
767 return [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
768 .concat( parsedHtmlContents
);
771 endCloseTagPos
= pos
;
772 endTagName
= parsedCloseTagResult
[ 1 ];
773 wrappedAttributes
= parsedOpenTagResult
[ 2 ];
774 attributes
= wrappedAttributes
.slice( 1 );
775 if ( isAllowedHtml( startTagName
, endTagName
, attributes
) ) {
776 result
= [ 'HTMLELEMENT', startTagName
, wrappedAttributes
]
777 .concat( parsedHtmlContents
);
779 // HTML is not allowed, so contents will remain how
780 // it was, while HTML markup at this level will be
782 // E.g. assuming script tags are not allowed:
784 // <script>[[Foo|bar]]</script>
786 // results in '<script>' and '</script>'
787 // (not treated as an HTML tag), surrounding a fully
790 // Concatenate everything from the tag, flattening the contents.
791 result
= [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
792 .concat( parsedHtmlContents
, input
.slice( startCloseTagPos
, endCloseTagPos
) );
798 // <nowiki>...</nowiki> tag. The tags are stripped and the contents are returned unparsed.
800 var parsedResult
, plainText
,
803 parsedResult
= sequence( [
804 makeStringParser( '<nowiki>' ),
805 // We use a greedy non-backtracking parser, so we must ensure here that we don't take too much
806 makeRegexParser( /^.*?(?=<\/nowiki>)/ ),
807 makeStringParser( '</nowiki>' )
809 if ( parsedResult
!== null ) {
810 plainText
= parsedResult
[ 1 ];
811 result
= [ 'CONCAT' ].concat( plainText
);
817 templateName
= transform(
818 // see $wgLegalTitleChars
819 // not allowing : due to the need to catch "PLURAL:$1"
820 makeRegexParser( /^[ !"$&'()*,./0-9;=?@A
-Z
^_
`a-z~\x80-\xFF+-]+/ ),
821 function ( result ) { return result.toString(); }
823 function templateParam() {
827 nOrMore( 0, paramExpression )
829 if ( result === null ) {
833 // use a CONCAT operator if there are multiple nodes, otherwise return the first node, raw.
834 return expr.length > 1 ? [ 'CONCAT' ].concat( expr ) : expr[ 0 ];
837 function templateWithReplacement() {
838 var result = sequence( [
843 return result === null ? null : [ result[ 0 ], result[ 2 ] ];
845 function templateWithOutReplacement() {
846 var result = sequence( [
851 return result === null ? null : [ result[ 0 ], result[ 2 ] ];
853 function templateWithOutFirstParameter() {
854 var result = sequence( [
858 return result === null ? null : [ result[ 0 ], '' ];
860 colon = makeStringParser( ':' );
861 templateContents = choice( [
863 var res = sequence( [
864 // templates can have placeholders for dynamic replacement eg: {{PLURAL:$1|one car|$1 cars}}
865 // or no placeholders eg: {{GRAMMAR:genitive|{{SITENAME}}}
866 choice( [ templateWithReplacement, templateWithOutReplacement, templateWithOutFirstParameter ] ),
867 nOrMore( 0, templateParam )
869 return res === null ? null : res[ 0 ].concat( res[ 1 ] );
872 var res = sequence( [
874 nOrMore( 0, templateParam )
876 if ( res === null ) {
879 return [ res[ 0 ] ].concat( res[ 1 ] );
882 openTemplate = makeStringParser( '{{' );
883 closeTemplate = makeStringParser( '}}' );
884 nonWhitespaceExpression = choice( [
891 paramExpression = choice( [
899 expression = choice( [
909 // Used when only {{-transformation is wanted, for 'text'
910 // or 'escaped' formats
911 curlyBraceTransformExpression = choice( [
914 curlyBraceTransformExpressionLiteral
920 * @param {Function} rootExpression Root parse function
921 * @return {Array|null}
923 function start( rootExpression ) {
924 var result = nOrMore( 0, rootExpression )();
925 if ( result === null ) {
928 return [ 'CONCAT' ].concat( result );
930 // everything above this point is supposed to be stateless/static, but
931 // I am deferring the work of turning it into prototypes & objects. It's quite fast enough
932 // finally let's do some actual work...
934 result = start( this.settings.onlyCurlyBraceTransform ? curlyBraceTransformExpression : expression );
937 * For success, the p must have gotten to the end of the input
938 * and returned a non-null.
939 * n.b. This is part of language infrastructure, so we do not throw an internationalizable message.
941 if ( result === null || pos !== input.length ) {
942 throw new Error( 'Parse error at position ' + pos.toString() + ' in input: ' + input );
950 * Class that primarily exists to emit HTML from parser ASTs.
954 * @param {Object} language
955 * @param {Object} magic
957 mw.jqueryMsg.HtmlEmitter = function ( language, magic ) {
959 this.language = language;
960 // eslint-disable-next-line jquery/no-each-util
961 $.each( magic, function ( key, val ) {
962 jmsg[ key.toLowerCase() ] = function () {
968 * (We put this method definition here, and not in prototype, to make sure it's not overwritten by any magic.)
969 * Walk entire node structure, applying replacements and template functions when appropriate
971 * @param {Mixed} node Abstract syntax tree (top node or subnode)
972 * @param {Array} replacements for $1, $2, ... $n
973 * @return {Mixed} single-string node or array of nodes suitable for jQuery appending
975 this.emit = function ( node, replacements ) {
976 var ret, subnodes, operation,
978 switch ( typeof node ) {
983 // typeof returns object for arrays
985 // node is an array of nodes
986 // eslint-disable-next-line jquery/no-map-util
987 subnodes = $.map( node.slice( 1 ), function ( n ) {
988 return jmsg.emit( n, replacements );
990 operation = node[ 0 ].toLowerCase();
991 if ( typeof jmsg[ operation ] === 'function' ) {
992 ret = jmsg[ operation ]( subnodes, replacements );
994 throw new Error( 'Unknown operation "' + operation + '"' );
998 // Parsing the empty string (as an entire expression, or as a paramExpression in a template) results in undefined
999 // Perhaps a more clever parser can detect this, and return the empty string? Or is that useful information?
1000 // The logical thing is probably to return the empty string here when we encounter undefined.
1004 throw new Error( 'Unexpected type in AST: ' + typeof node );
1010 // For everything in input that follows double-open-curly braces, there should be an equivalent parser
1011 // function. For instance {{PLURAL ... }} will be processed by 'plural'.
1012 // If you have 'magic words' then configure the parser to have them upon creation.
1014 // An emitter method takes the parent node, the array of subnodes and the array of replacements (the values that $1, $2... should translate to).
1015 // Note: all such functions must be pure, with the exception of referring to other pure functions via this.language (convertPlural and so on)
1016 mw.jqueryMsg.HtmlEmitter.prototype = {
1018 * Parsing has been applied depth-first we can assume that all nodes here are single nodes
1019 * Must return a single node to parents -- a jQuery with synthetic span
1020 * However, unwrap any other synthetic spans in our children and pass them upwards
1022 * @param {Mixed[]} nodes Some single nodes, some arrays of nodes
1025 concat: function ( nodes ) {
1026 var $span = $( '<span>' ).addClass( 'mediaWiki_htmlEmitter' );
1027 // eslint-disable-next-line jquery/no-each-util
1028 $.each( nodes, function ( i, node ) {
1029 // Let jQuery append nodes, arrays of nodes and jQuery objects
1030 // other things (strings, numbers, ..) are appended as text nodes (not as HTML strings)
1031 appendWithoutParsing( $span, node );
1037 * Return escaped replacement of correct index, or string if unavailable.
1038 * Note that we expect the parsed parameter to be zero-based. i.e. $1 should have become [ 0 ].
1039 * if the specified parameter is not found return the same string
1040 * (e.g. "$99" -> parameter 98 -> not found -> return "$99" )
1042 * TODO: Throw error if nodes.length > 1 ?
1044 * @param {Array} nodes List of one element, integer, n >= 0
1045 * @param {Array} replacements List of at least n strings
1046 * @return {string|jQuery} replacement
1048 replace: function ( nodes, replacements ) {
1049 var index = parseInt( nodes[ 0 ], 10 );
1051 if ( index < replacements.length ) {
1052 return replacements[ index ];
1054 // index not found, fallback to displaying variable
1055 return '$' + ( index + 1 );
1060 * Transform wiki-link
1063 * It only handles basic cases, either no pipe, or a pipe with an explicit
1066 * It does not attempt to handle features like the pipe trick.
1067 * However, the pipe trick should usually not be present in wikitext retrieved
1068 * from the server, since the replacement is done at save time.
1069 * It may, though, if the wikitext appears in extension-controlled content.
1071 * @param {string[]} nodes
1074 wikilink: function ( nodes ) {
1075 var page, anchor, url, $el;
1077 page = textify( nodes[ 0 ] );
1078 // Strip leading ':', which is used to suppress special behavior in wikitext links,
1079 // e.g. [[:Category:Foo]] or [[:File:Foo.jpg]]
1080 if ( page.charAt( 0 ) === ':' ) {
1081 page = page.slice( 1 );
1083 url = mw.util.getUrl( page );
1085 if ( nodes.length === 1 ) {
1086 // [[Some Page]] or [[Namespace:Some Page]]
1089 // [[Some Page|anchor text]] or [[Namespace:Some Page|anchor]]
1090 anchor = nodes[ 1 ];
1093 $el = $( '<a>' ).attr( {
1097 return appendWithoutParsing( $el, anchor );
1101 * Converts array of HTML element key value pairs to object
1103 * @param {Array} nodes Array of consecutive key value pairs, with index 2 * n being a
1104 * name and 2 * n + 1 the associated value
1105 * @return {Object} Object mapping attribute name to attribute value
1107 htmlattributes: function ( nodes ) {
1108 var i, len, mapping = {};
1109 for ( i = 0, len = nodes.length; i < len; i += 2 ) {
1110 mapping[ nodes[ i ] ] = decodePrimaryHtmlEntities( nodes[ i + 1 ] );
1116 * Handles an (already-validated) HTML element.
1118 * @param {Array} nodes Nodes to process when creating element
1121 htmlelement: function ( nodes ) {
1122 var tagName, attributes, contents, $element;
1124 tagName = nodes.shift();
1125 attributes = nodes.shift();
1127 $element = $( document.createElement( tagName ) ).attr( attributes );
1128 return appendWithoutParsing( $element, contents );
1132 * Transform parsed structure into external link.
1134 * The "href" can be:
1135 * - a jQuery object, treat it as "enclosing" the link text.
1136 * - a function, treat it as the click handler.
1137 * - a string, or our HtmlEmitter jQuery object, treat it as a URI after stringifying.
1139 * TODO: throw an error if nodes.length > 2 ?
1141 * @param {Array} nodes List of two elements, {jQuery|Function|String} and {string}
1144 extlink: function ( nodes ) {
1147 contents = nodes[ 1 ];
1148 if ( arg instanceof $ && !arg.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1152 if ( typeof arg === 'function' ) {
1156 } ).on( 'click keypress', function ( e ) {
1158 e.type === 'click' ||
1159 e.type === 'keypress' && e.which === 13
1161 arg.call( this, e );
1165 $el.attr( 'href', textify( arg ) );
1168 return appendWithoutParsing( $el.empty(), contents );
1172 * Transform parsed structure into pluralization
1173 * n.b. The first node may be a non-integer (for instance, a string representing an Arabic number).
1174 * So convert it back with the current language's convertNumber.
1176 * @param {Array} nodes List of nodes, [ {string|number}, {string}, {string} ... ]
1177 * @return {string|jQuery} selected pluralized form according to current language
1179 plural: function ( nodes ) {
1180 var forms, firstChild, firstChildText, explicitPluralFormNumber, formIndex, form, count,
1181 explicitPluralForms = {};
1183 count = parseFloat( this.language.convertNumber( textify( nodes[ 0 ] ), true ) );
1184 forms = nodes.slice( 1 );
1185 for ( formIndex = 0; formIndex < forms.length; formIndex++ ) {
1186 form = forms[ formIndex ];
1188 if ( form instanceof $ && form.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1189 // This is a nested node, may be an explicit plural form like 5=[$2 linktext]
1190 firstChild = form.contents().get( 0 );
1191 if ( firstChild && firstChild.nodeType === Node.TEXT_NODE ) {
1192 firstChildText = firstChild.textContent;
1193 if ( /^\d+=/.test( firstChildText ) ) {
1194 explicitPluralFormNumber = parseInt( firstChildText.split( /=/ )[ 0 ], 10 );
1195 // Use the digit part as key and rest of first text node and
1196 // rest of child nodes as value.
1197 firstChild.textContent = firstChildText.slice( firstChildText.indexOf( '=' ) + 1 );
1198 explicitPluralForms[ explicitPluralFormNumber ] = form;
1199 forms[ formIndex ] = undefined;
1202 } else if ( /^\d+=/.test( form ) ) {
1203 // Simple explicit plural forms like 12=a dozen
1204 explicitPluralFormNumber = parseInt( form.split( /=/ )[ 0 ], 10 );
1205 explicitPluralForms[ explicitPluralFormNumber ] = form.slice( form.indexOf( '=' ) + 1 );
1206 forms[ formIndex ] = undefined;
1210 // Remove explicit plural forms from the forms. They were set undefined in the above loop.
1211 // eslint-disable-next-line jquery/no-map-util
1212 forms = $.map( forms, function ( form ) {
1216 return this.language.convertPlural( count, forms, explicitPluralForms );
1220 * Transform parsed structure according to gender.
1222 * Usage: {{gender:[ mw.user object | '' | 'male' | 'female' | 'unknown' ] | masculine form | feminine form | neutral form}}.
1224 * The first node must be one of:
1225 * - the mw.user object (or a compatible one)
1226 * - an empty string - indicating the current user, same effect as passing the mw.user object
1227 * - a gender string ('male', 'female' or 'unknown')
1229 * @param {Array} nodes List of nodes, [ {string|mw.user}, {string}, {string}, {string} ]
1230 * @return {string|jQuery} Selected gender form according to current language
1232 gender: function ( nodes ) {
1234 maybeUser = nodes[ 0 ],
1235 forms = nodes.slice( 1 );
1237 if ( maybeUser === '' ) {
1238 maybeUser = mw.user;
1241 // If we are passed a mw.user-like object, check their gender.
1242 // Otherwise, assume the gender string itself was passed .
1243 if ( maybeUser && maybeUser.options instanceof mw.Map ) {
1244 gender = maybeUser.options.get( 'gender' );
1246 gender = textify( maybeUser );
1249 return this.language.gender( gender, forms );
1253 * Transform parsed structure into grammar conversion.
1254 * Invoked by putting `{{grammar
:form
|word
}}` in a message
1256 * @param {Array} nodes List of nodes [{Grammar case eg: genitive}, {string word}]
1257 * @return {string|jQuery} selected grammatical form according to current language
1259 grammar: function ( nodes ) {
1260 var form = nodes[ 0 ],
1262 // These could be jQuery objects (passed as message parameters),
1263 // in which case we can't transform them (like rawParams() in PHP).
1264 if ( typeof form === 'string' && typeof word === 'string' ) {
1265 return this.language.convertGrammar( word, form );
1271 * Tranform parsed structure into a int: (interface language) message include
1272 * Invoked by putting `{{int:othermessage
}}` into a message
1274 * TODO Syntax in the included message is not parsed, this seems like a bug?
1276 * @param {Array} nodes List of nodes
1277 * @return {string} Other message
1279 'int': function ( nodes ) {
1280 var msg = textify( nodes[ 0 ] );
1281 return mw.jqueryMsg.getMessageFunction()( msg.charAt( 0 ).toLowerCase() + msg.slice( 1 ) );
1285 * Get localized namespace name from canonical name or namespace number.
1286 * Invoked by putting `{{ns
:foo
}}` into a message
1288 * @param {Array} nodes List of nodes
1289 * @return {string} Localized namespace name
1291 ns: function ( nodes ) {
1292 var ns = textify( nodes[ 0 ] ).trim();
1293 if ( !/^\d+$/.test( ns ) ) {
1294 ns = mw.config.get( 'wgNamespaceIds' )[ ns.replace( / /g, '_' ).toLowerCase() ];
1296 ns = mw.config.get( 'wgFormattedNamespaces' )[ ns ];
1301 * Takes an unformatted number (arab, no group separators and . as decimal separator)
1302 * and outputs it in the localized digit script and formatted with decimal
1303 * separator, according to the current language.
1305 * @param {Array} nodes List of nodes
1306 * @return {number|string|jQuery} Formatted number
1308 formatnum: function ( nodes ) {
1309 var isInteger = !!nodes[ 1 ] && nodes[ 1 ] === 'R',
1310 number = nodes[ 0 ];
1312 // These could be jQuery objects (passed as message parameters),
1313 // in which case we can't transform them (like rawParams() in PHP).
1314 if ( typeof number === 'string' || typeof number === 'number' ) {
1315 return this.language.convertNumber( number, isInteger );
1323 * @param {Array} nodes List of nodes
1324 * @return {string} The given text, all in lowercase
1326 lc: function ( nodes ) {
1327 return textify( nodes[ 0 ] ).toLowerCase();
1333 * @param {Array} nodes List of nodes
1334 * @return {string} The given text, all in uppercase
1336 uc: function ( nodes ) {
1337 return textify( nodes[ 0 ] ).toUpperCase();
1341 * Lowercase first letter of input, leaving the rest unchanged
1343 * @param {Array} nodes List of nodes
1344 * @return {string} The given text, with the first character in lowercase
1346 lcfirst: function ( nodes ) {
1347 var text = textify( nodes[ 0 ] );
1348 return text.charAt( 0 ).toLowerCase() + text.slice( 1 );
1352 * Uppercase first letter of input, leaving the rest unchanged
1354 * @param {Array} nodes List of nodes
1355 * @return {string} The given text, with the first character in uppercase
1357 ucfirst: function ( nodes ) {
1358 var text = textify( nodes[ 0 ] );
1359 return text.charAt( 0 ).toUpperCase() + text.slice( 1 );
1366 * @see mw.jqueryMsg#getPlugin
1368 $.fn.msg = mw.jqueryMsg.getPlugin();
1370 // Replace the default message parser with jqueryMsg
1371 oldParser = mw.Message.prototype.parser;
1372 mw.Message.prototype.parser = function () {
1373 // Fall back to mw.msg's simple parser where possible
1375 // Plain text output always uses the simple parser
1376 this.format === 'plain' ||
1378 // jqueryMsg parser is needed for messages containing wikitext
1379 !/\{\{|[<>[&]/.test( this.map.get( this.key ) ) &&
1380 // jqueryMsg parser is needed when jQuery objects or DOM nodes are passed in as parameters
1381 !this.parameters.some( function ( param ) {
1382 return param instanceof $ || ( param && param.nodeType !== undefined );
1386 return oldParser.apply( this );
1389 if ( !Object.prototype.hasOwnProperty.call( this.map, this.format ) ) {
1390 this.map[ this.format ] = mw.jqueryMsg.getMessageFunction( {
1392 // For format 'escaped', escaping part is handled by mediawiki.js
1396 return this.map[ this.format ]( this.key, this.parameters );
1400 * Parse the message to DOM nodes, rather than HTML string like #parse.
1402 * This method is only available when jqueryMsg is loaded.
1406 * @member mw.Message
1409 mw.Message.prototype.parseDom = ( function () {
1410 var $wrapper = $( '<div>' );
1411 return function () {
1412 return $wrapper.msg( this.key, this.parameters ).contents().detach();