2 * Experimental advanced wikitext parser-emitter.
3 * See: https://www.mediawiki.org/wiki/Extension:UploadWizard/MessageParser for docs
5 * @author neilk@wikimedia.org
6 * @author mflaschen@wikimedia.org
15 slice
= Array
.prototype.slice
,
18 PAGENAME
: mw
.config
.get( 'wgPageName' ),
19 PAGENAMEE
: mw
.util
.wikiUrlencode( mw
.config
.get( 'wgPageName' ) )
21 // Whitelist for allowed HTML elements in wikitext.
22 // Self-closing tags are not currently supported.
23 // Can be populated via setParserDefaults().
24 allowedHtmlElements
: [],
25 // Key tag name, value allowed attributes for that tag.
26 // See Sanitizer::setupAttributeWhitelist
27 allowedHtmlCommonAttributes
: [
40 // Attributes allowed for specific elements.
41 // Key is element name in lower case
42 // Value is array of allowed attributes for that element
43 allowedHtmlAttributesByElement
: {},
44 messages
: mw
.messages
,
45 language
: mw
.language
,
47 // Same meaning as in mediawiki.js.
49 // Only 'text', 'parse', and 'escaped' are supported, and the
50 // actual escaping for 'escaped' is done by other code (generally
51 // through mediawiki.js).
53 // However, note that this default only
54 // applies to direct calls to jqueryMsg. The default for mediawiki.js itself
55 // is 'text', including when it uses jqueryMsg.
60 * Wrapper around jQuery append that converts all non-objects to TextNode so append will not
61 * convert what it detects as an htmlString to an element.
63 * If our own HtmlEmitter jQuery object is given, its children will be unwrapped and appended to
66 * Object elements of children (jQuery, HTMLElement, TextNode, etc.) will be left as is.
69 * @param {jQuery} $parent Parent node wrapped by jQuery
70 * @param {Object|string|Array} children What to append, with the same possible types as jQuery
71 * @return {jQuery} $parent
73 function appendWithoutParsing( $parent
, children
) {
76 if ( !Array
.isArray( children
) ) {
77 children
= [ children
];
80 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
81 if ( typeof children
[ i
] !== 'object' ) {
82 children
[ i
] = document
.createTextNode( children
[ i
] );
84 if ( children
[ i
] instanceof $ && children
[ i
].hasClass( 'mediaWiki_htmlEmitter' ) ) {
85 children
[ i
] = children
[ i
].contents();
89 return $parent
.append( children
);
93 * Decodes the main HTML entities, those encoded by mw.html.escape.
96 * @param {string} encoded Encoded string
97 * @return {string} String with those entities decoded
99 function decodePrimaryHtmlEntities( encoded
) {
101 .replace( /'/g, '\'' )
102 .replace( /"/g, '"' )
103 .replace( /</g, '<' )
104 .replace( />/g, '>' )
105 .replace( /&/g, '&' );
109 * Turn input into a string.
112 * @param {string|jQuery} input
113 * @return {string} Textual value of input
115 function textify( input
) {
116 if ( input
instanceof $ ) {
117 input
= input
.text();
119 return String( input
);
123 * Given parser options, return a function that parses a key and replacements, returning jQuery object
125 * Try to parse a key and optional replacements, returning a jQuery object that may be a tree of jQuery nodes.
126 * If there was an error parsing, return the key and the error message (wrapped in jQuery). This should put the error right into
127 * the interface, without causing the page to halt script execution, and it hopefully should be clearer how to fix it.
130 * @param {Object} options Parser options
132 * @return {Array} return.args First element is the key, replacements may be in array in 2nd element, or remaining elements.
133 * @return {jQuery} return.return
135 function getFailableParserFn( options
) {
136 return function ( args
) {
138 parser
= new mw
.jqueryMsg
.Parser( options
),
140 argsArray
= Array
.isArray( args
[ 1 ] ) ? args
[ 1 ] : slice
.call( args
, 1 );
142 return parser
.parse( key
, argsArray
);
144 fallback
= parser
.settings
.messages
.get( key
);
145 mw
.log
.warn( 'mediawiki.jqueryMsg: ' + key
+ ': ' + e
.message
);
146 mw
.track( 'mediawiki.jqueryMsg.error', {
148 errorMessage
: e
.message
150 return $( '<span>' ).text( fallback
);
158 * Initialize parser defaults.
160 * ResourceLoaderJqueryMsgModule calls this to provide default values from
161 * Sanitizer.php for allowed HTML elements. To override this data for individual
162 * parsers, pass the relevant options to mw.jqueryMsg.Parser.
165 * @param {Object} data New data to extend parser defaults with
166 * @param {boolean} [deep=false] Whether the extend is done recursively (deep)
168 mw
.jqueryMsg
.setParserDefaults = function ( data
, deep
) {
170 $.extend( true, parserDefaults
, data
);
172 $.extend( parserDefaults
, data
);
177 * Get current parser defaults.
179 * Primarily used for the unit test. Returns a copy.
184 mw
.jqueryMsg
.getParserDefaults = function () {
185 return $.extend( {}, parserDefaults
);
189 * Returns a function suitable for static use, to construct strings from a message key (and optional replacements).
193 * var format = mediaWiki.jqueryMsg.getMessageFunction( options );
194 * $( '#example' ).text( format( 'hello-user', username ) );
196 * Tthis returns only strings, so it destroys any bindings. If you want to preserve bindings, use the
197 * jQuery plugin version instead. This was originally created to ease migration from `window.gM()`,
198 * from a time when the parser used by `mw.message` was not extendable.
200 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
201 * somefunction( a, b, c, d )
203 * somefunction( a, [b, c, d] )
205 * @param {Object} options parser options
206 * @return {Function} Function The message formatter
207 * @return {string} return.key Message key.
208 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
209 * @return {string} return.return Rendered HTML.
211 mw
.jqueryMsg
.getMessageFunction = function ( options
) {
212 var failableParserFn
, format
;
214 if ( options
&& options
.format
!== undefined ) {
215 format
= options
.format
;
217 format
= parserDefaults
.format
;
222 if ( !failableParserFn
) {
223 failableParserFn
= getFailableParserFn( options
);
225 failableResult
= failableParserFn( arguments
);
226 if ( format
=== 'text' || format
=== 'escaped' ) {
227 return failableResult
.text();
229 return failableResult
.html();
235 * Returns a jQuery plugin which parses the message in the message key, doing replacements optionally, and appends the nodes to
236 * the current selector. Bindings to passed-in jquery elements are preserved. Functions become click handlers for [$1 linktext] links.
239 * $.fn.msg = mediaWiki.jqueryMsg.getPlugin( options );
240 * var $userlink = $( '<a>' ).click( function () { alert( "hello!!" ) } );
241 * $( 'p#headline' ).msg( 'hello-user', $userlink );
243 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
244 * somefunction( a, b, c, d )
246 * somefunction( a, [b, c, d] )
248 * We append to 'this', which in a jQuery plugin context will be the selected elements.
250 * @param {Object} options Parser options
251 * @return {Function} Function suitable for assigning to jQuery plugin, such as jQuery#msg
252 * @return {string} return.key Message key.
253 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
254 * @return {jQuery} return.return
256 mw
.jqueryMsg
.getPlugin = function ( options
) {
257 var failableParserFn
;
261 if ( !failableParserFn
) {
262 failableParserFn
= getFailableParserFn( options
);
264 $target
= this.empty();
265 appendWithoutParsing( $target
, failableParserFn( arguments
) );
272 * Describes an object, whose primary duty is to .parse() message keys.
276 * @param {Object} options
278 mw
.jqueryMsg
.Parser = function ( options
) {
279 this.settings
= $.extend( {}, parserDefaults
, options
);
280 this.settings
.onlyCurlyBraceTransform
= ( this.settings
.format
=== 'text' || this.settings
.format
=== 'escaped' );
283 this.emitter
= new mw
.jqueryMsg
.HtmlEmitter( this.settings
.language
, this.settings
.magic
);
285 // Backwards-compatible alias
286 // @deprecated since 1.31
287 mw
.jqueryMsg
.parser
= mw
.jqueryMsg
.Parser
;
289 mw
.jqueryMsg
.Parser
.prototype = {
291 * Where the magic happens.
292 * Parses a message from the key, and swaps in replacements as necessary, wraps in jQuery
293 * If an error is thrown, returns original key, and logs the error
295 * @param {string} key Message key.
296 * @param {Array} replacements Variable replacements for $1, $2... $n
299 parse: function ( key
, replacements
) {
300 var ast
= this.getAst( key
, replacements
);
301 return this.emitter
.emit( ast
, replacements
);
305 * Fetch the message string associated with a key, return parsed structure. Memoized.
306 * Note that we pass '⧼' + key + '⧽' back for a missing message here.
308 * @param {string} key
309 * @param {Array} replacements Variable replacements for $1, $2... $n
310 * @return {string|Array} string of '⧼key⧽' if message missing, simple string if possible, array of arrays if needs parsing
312 getAst: function ( key
, replacements
) {
315 if ( !Object
.prototype.hasOwnProperty
.call( this.astCache
, key
) ) {
316 if ( mw
.config
.get( 'wgUserLanguage' ) === 'qqx' ) {
317 wikiText
= '(' + key
+ '$*)';
319 wikiText
= this.settings
.messages
.get( key
);
320 if ( typeof wikiText
!== 'string' ) {
321 wikiText
= '⧼' + key
+ '⧽';
324 wikiText
= mw
.internalDoTransformFormatForQqx( wikiText
, replacements
);
325 this.astCache
[ key
] = this.wikiTextToAst( wikiText
);
327 return this.astCache
[ key
];
331 * Parses the input wikiText into an abstract syntax tree, essentially an s-expression.
333 * CAVEAT: This does not parse all wikitext. It could be more efficient, but it's pretty good already.
334 * n.b. We want to move this functionality to the server. Nothing here is required to be on the client.
336 * @param {string} input Message string wikitext
338 * @return {Mixed} abstract syntax tree
340 wikiTextToAst: function ( input
) {
342 regularLiteral
, regularLiteralWithoutBar
, regularLiteralWithoutSpace
, regularLiteralWithSquareBrackets
,
343 doubleQuote
, singleQuote
, backslash
, anyCharacter
, asciiAlphabetLiteral
,
344 escapedOrLiteralWithoutSpace
, escapedOrLiteralWithoutBar
, escapedOrRegularLiteral
,
345 whitespace
, dollar
, digits
, htmlDoubleQuoteAttributeValue
, htmlSingleQuoteAttributeValue
,
346 htmlAttributeEquals
, openHtmlStartTag
, optionalForwardSlash
, openHtmlEndTag
, closeHtmlTag
,
347 openExtlink
, closeExtlink
, wikilinkContents
, openWikilink
, closeWikilink
, templateName
, pipe
, colon
,
348 templateContents
, openTemplate
, closeTemplate
,
349 nonWhitespaceExpression
, paramExpression
, expression
, curlyBraceTransformExpression
, result
,
350 settings
= this.settings
,
351 concat
= Array
.prototype.concat
;
353 // Indicates current position in input as we parse through it.
354 // Shared among all parsing functions below.
357 // =========================================================
358 // parsing combinators - could be a library on its own
359 // =========================================================
362 * Try parsers until one works, if none work return null
365 * @param {Function[]} ps
366 * @return {string|null}
368 function choice( ps
) {
371 for ( i
= 0; i
< ps
.length
; i
++ ) {
373 if ( result
!== null ) {
382 * Try several ps in a row, all must succeed or return null.
383 * This is the only eager one.
386 * @param {Function[]} ps
387 * @return {string|null}
389 function sequence( ps
) {
393 for ( i
= 0; i
< ps
.length
; i
++ ) {
395 if ( res
=== null ) {
405 * Run the same parser over and over until it fails.
406 * Must succeed a minimum of n times or return null.
410 * @param {Function} p
411 * @return {string|null}
413 function nOrMore( n
, p
) {
415 var originalPos
= pos
,
418 while ( parsed
!== null ) {
419 result
.push( parsed
);
422 if ( result
.length
< n
) {
431 * There is a general pattern -- parse a thing, if that worked, apply transform, otherwise return null.
433 * TODO: But using this as a combinator seems to cause problems when combined with #nOrMore().
434 * May be some scoping issue
437 * @param {Function} p
438 * @param {Function} fn
439 * @return {string|null}
441 function transform( p
, fn
) {
444 return result
=== null ? null : fn( result
);
449 * Just make parsers out of simpler JS builtin types
454 * @return {string} return.return
456 function makeStringParser( s
) {
460 if ( input
.substr( pos
, len
) === s
) {
469 * Makes a regex parser, given a RegExp object.
470 * The regex being passed in should start with a ^ to anchor it to the start
474 * @param {RegExp} regex anchored regex
475 * @return {Function} function to parse input based on the regex
477 function makeRegexParser( regex
) {
479 var matches
= input
.slice( pos
).match( regex
);
480 if ( matches
=== null ) {
483 pos
+= matches
[ 0 ].length
;
488 // ===================================================================
489 // General patterns above this line -- wikitext specific parsers below
490 // ===================================================================
492 // Parsing functions follow. All parsing functions work like this:
493 // They don't accept any arguments.
494 // Instead, they just operate non destructively on the string 'input'
495 // As they can consume parts of the string, they advance the shared variable pos,
496 // and return tokens (or whatever else they want to return).
497 // some things are defined as closures and other things as ordinary functions
498 // converting everything to a closure makes it a lot harder to debug... errors pop up
499 // but some debuggers can't tell you exactly where they come from. Also the mutually
500 // recursive functions seem not to work in all browsers then. (Tested IE6-7, Opera, Safari, FF)
501 // This may be because, to save code, memoization was removed
503 /* eslint-disable no-useless-escape */
504 regularLiteral
= makeRegexParser( /^[^{}\[\]$<\\]/ );
505 regularLiteralWithoutBar
= makeRegexParser( /^[^{}\[\]$\\|]/ );
506 regularLiteralWithoutSpace
= makeRegexParser( /^[^{}\[\]$\s]/ );
507 regularLiteralWithSquareBrackets
= makeRegexParser( /^[^{}$\\]/ );
508 /* eslint-enable no-useless-escape */
510 backslash
= makeStringParser( '\\' );
511 doubleQuote
= makeStringParser( '"' );
512 singleQuote
= makeStringParser( '\'' );
513 anyCharacter
= makeRegexParser( /^./ );
515 openHtmlStartTag
= makeStringParser( '<' );
516 optionalForwardSlash
= makeRegexParser( /^\/?/ );
517 openHtmlEndTag
= makeStringParser( '</' );
518 htmlAttributeEquals
= makeRegexParser( /^\s*=\s*/ );
519 closeHtmlTag
= makeRegexParser( /^\s*>/ );
521 function escapedLiteral() {
522 var result
= sequence( [
526 return result
=== null ? null : result
[ 1 ];
528 escapedOrLiteralWithoutSpace
= choice( [
530 regularLiteralWithoutSpace
532 escapedOrLiteralWithoutBar
= choice( [
534 regularLiteralWithoutBar
536 escapedOrRegularLiteral
= choice( [
540 // Used to define "literals" without spaces, in space-delimited situations
541 function literalWithoutSpace() {
542 var result
= nOrMore( 1, escapedOrLiteralWithoutSpace
)();
543 return result
=== null ? null : result
.join( '' );
545 // Used to define "literals" within template parameters. The pipe character is the parameter delimeter, so by default
546 // it is not a literal in the parameter
547 function literalWithoutBar() {
548 var result
= nOrMore( 1, escapedOrLiteralWithoutBar
)();
549 return result
=== null ? null : result
.join( '' );
553 var result
= nOrMore( 1, escapedOrRegularLiteral
)();
554 return result
=== null ? null : result
.join( '' );
557 function curlyBraceTransformExpressionLiteral() {
558 var result
= nOrMore( 1, regularLiteralWithSquareBrackets
)();
559 return result
=== null ? null : result
.join( '' );
562 asciiAlphabetLiteral
= makeRegexParser( /^[A-Za-z]+/ );
563 htmlDoubleQuoteAttributeValue
= makeRegexParser( /^[^"]*/ );
564 htmlSingleQuoteAttributeValue
= makeRegexParser( /^[^']*/ );
566 whitespace
= makeRegexParser( /^\s+/ );
567 dollar
= makeStringParser( '$' );
568 digits
= makeRegexParser( /^\d+/ );
570 function replacement() {
571 var result
= sequence( [
575 if ( result
=== null ) {
578 return [ 'REPLACE', parseInt( result
[ 1 ], 10 ) - 1 ];
580 openExtlink
= makeStringParser( '[' );
581 closeExtlink
= makeStringParser( ']' );
582 // this extlink MUST have inner contents, e.g. [foo] not allowed; [foo bar] [foo <i>bar</i>], etc. are allowed
584 var result
, parsedResult
, target
;
586 parsedResult
= sequence( [
588 nOrMore( 1, nonWhitespaceExpression
),
590 nOrMore( 1, expression
),
593 if ( parsedResult
!== null ) {
594 // When the entire link target is a single parameter, we can't use CONCAT, as we allow
595 // passing fancy parameters (like a whole jQuery object or a function) to use for the
596 // link. Check only if it's a single match, since we can either do CONCAT or not for
597 // singles with the same effect.
598 target
= parsedResult
[ 1 ].length
=== 1 ?
599 parsedResult
[ 1 ][ 0 ] :
600 [ 'CONCAT' ].concat( parsedResult
[ 1 ] );
604 [ 'CONCAT' ].concat( parsedResult
[ 3 ] )
609 openWikilink
= makeStringParser( '[[' );
610 closeWikilink
= makeStringParser( ']]' );
611 pipe
= makeStringParser( '|' );
613 function template() {
614 var result
= sequence( [
619 return result
=== null ? null : result
[ 1 ];
622 function pipedWikilink() {
623 var result
= sequence( [
624 nOrMore( 1, paramExpression
),
626 nOrMore( 1, expression
)
628 return result
=== null ? null : [
629 [ 'CONCAT' ].concat( result
[ 0 ] ),
630 [ 'CONCAT' ].concat( result
[ 2 ] )
634 function unpipedWikilink() {
635 var result
= sequence( [
636 nOrMore( 1, paramExpression
)
638 return result
=== null ? null : [
639 [ 'CONCAT' ].concat( result
[ 0 ] )
643 wikilinkContents
= choice( [
648 function wikilink() {
649 var result
, parsedResult
, parsedLinkContents
;
652 parsedResult
= sequence( [
657 if ( parsedResult
!== null ) {
658 parsedLinkContents
= parsedResult
[ 1 ];
659 result
= [ 'WIKILINK' ].concat( parsedLinkContents
);
664 // TODO: Support data- if appropriate
665 function doubleQuotedHtmlAttributeValue() {
666 var parsedResult
= sequence( [
668 htmlDoubleQuoteAttributeValue
,
671 return parsedResult
=== null ? null : parsedResult
[ 1 ];
674 function singleQuotedHtmlAttributeValue() {
675 var parsedResult
= sequence( [
677 htmlSingleQuoteAttributeValue
,
680 return parsedResult
=== null ? null : parsedResult
[ 1 ];
683 function htmlAttribute() {
684 var parsedResult
= sequence( [
686 asciiAlphabetLiteral
,
689 doubleQuotedHtmlAttributeValue
,
690 singleQuotedHtmlAttributeValue
693 return parsedResult
=== null ? null : [ parsedResult
[ 1 ], parsedResult
[ 3 ] ];
697 * Checks if HTML is allowed
699 * @param {string} startTagName HTML start tag name
700 * @param {string} endTagName HTML start tag name
701 * @param {Object} attributes array of consecutive key value pairs,
702 * with index 2 * n being a name and 2 * n + 1 the associated value
703 * @return {boolean} true if this is HTML is allowed, false otherwise
705 function isAllowedHtml( startTagName
, endTagName
, attributes
) {
706 var i
, len
, attributeName
;
708 startTagName
= startTagName
.toLowerCase();
709 endTagName
= endTagName
.toLowerCase();
710 if ( startTagName
!== endTagName
|| settings
.allowedHtmlElements
.indexOf( startTagName
) === -1 ) {
714 for ( i
= 0, len
= attributes
.length
; i
< len
; i
+= 2 ) {
715 attributeName
= attributes
[ i
];
716 if ( settings
.allowedHtmlCommonAttributes
.indexOf( attributeName
) === -1 &&
717 ( settings
.allowedHtmlAttributesByElement
[ startTagName
] || [] ).indexOf( attributeName
) === -1 ) {
725 function htmlAttributes() {
726 var parsedResult
= nOrMore( 0, htmlAttribute
)();
727 // Un-nest attributes array due to structure of jQueryMsg operations (see emit).
728 return concat
.apply( [ 'HTMLATTRIBUTES' ], parsedResult
);
731 // Subset of allowed HTML markup.
732 // Most elements and many attributes allowed on the server are not supported yet.
734 var parsedOpenTagResult
, parsedHtmlContents
, parsedCloseTagResult
,
735 wrappedAttributes
, attributes
, startTagName
, endTagName
, startOpenTagPos
,
736 startCloseTagPos
, endOpenTagPos
, endCloseTagPos
,
739 // Break into three sequence calls. That should allow accurate reconstruction of the original HTML, and requiring an exact tag name match.
740 // 1. open through closeHtmlTag
742 // 3. openHtmlEnd through close
743 // This will allow recording the positions to reconstruct if HTML is to be treated as text.
745 startOpenTagPos
= pos
;
746 parsedOpenTagResult
= sequence( [
748 asciiAlphabetLiteral
,
750 optionalForwardSlash
,
754 if ( parsedOpenTagResult
=== null ) {
759 startTagName
= parsedOpenTagResult
[ 1 ];
761 parsedHtmlContents
= nOrMore( 0, expression
)();
763 startCloseTagPos
= pos
;
764 parsedCloseTagResult
= sequence( [
766 asciiAlphabetLiteral
,
770 if ( parsedCloseTagResult
=== null ) {
771 // Closing tag failed. Return the start tag and contents.
772 return [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
773 .concat( parsedHtmlContents
);
776 endCloseTagPos
= pos
;
777 endTagName
= parsedCloseTagResult
[ 1 ];
778 wrappedAttributes
= parsedOpenTagResult
[ 2 ];
779 attributes
= wrappedAttributes
.slice( 1 );
780 if ( isAllowedHtml( startTagName
, endTagName
, attributes
) ) {
781 result
= [ 'HTMLELEMENT', startTagName
, wrappedAttributes
]
782 .concat( parsedHtmlContents
);
784 // HTML is not allowed, so contents will remain how
785 // it was, while HTML markup at this level will be
787 // E.g. assuming script tags are not allowed:
789 // <script>[[Foo|bar]]</script>
791 // results in '<script>' and '</script>'
792 // (not treated as an HTML tag), surrounding a fully
795 // Concatenate everything from the tag, flattening the contents.
796 result
= [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
797 .concat( parsedHtmlContents
, input
.slice( startCloseTagPos
, endCloseTagPos
) );
803 // <nowiki>...</nowiki> tag. The tags are stripped and the contents are returned unparsed.
805 var parsedResult
, plainText
,
808 parsedResult
= sequence( [
809 makeStringParser( '<nowiki>' ),
810 // We use a greedy non-backtracking parser, so we must ensure here that we don't take too much
811 makeRegexParser( /^.*?(?=<\/nowiki>)/ ),
812 makeStringParser( '</nowiki>' )
814 if ( parsedResult
!== null ) {
815 plainText
= parsedResult
[ 1 ];
816 result
= [ 'CONCAT' ].concat( plainText
);
822 templateName
= transform(
823 // see $wgLegalTitleChars
824 // not allowing : due to the need to catch "PLURAL:$1"
825 makeRegexParser( /^[ !"$&'()*,./0-9;=?@A
-Z
^_
`a-z~\x80-\xFF+-]+/ ),
826 function ( result ) { return result.toString(); }
828 function templateParam() {
832 nOrMore( 0, paramExpression )
834 if ( result === null ) {
838 // use a CONCAT operator if there are multiple nodes, otherwise return the first node, raw.
839 return expr.length > 1 ? [ 'CONCAT' ].concat( expr ) : expr[ 0 ];
842 function templateWithReplacement() {
843 var result = sequence( [
848 return result === null ? null : [ result[ 0 ], result[ 2 ] ];
850 function templateWithOutReplacement() {
851 var result = sequence( [
856 return result === null ? null : [ result[ 0 ], result[ 2 ] ];
858 function templateWithOutFirstParameter() {
859 var result = sequence( [
863 return result === null ? null : [ result[ 0 ], '' ];
865 colon = makeStringParser( ':' );
866 templateContents = choice( [
868 var res = sequence( [
869 // templates can have placeholders for dynamic replacement eg: {{PLURAL:$1|one car|$1 cars}}
870 // or no placeholders eg: {{GRAMMAR:genitive|{{SITENAME}}}
871 choice( [ templateWithReplacement, templateWithOutReplacement, templateWithOutFirstParameter ] ),
872 nOrMore( 0, templateParam )
874 return res === null ? null : res[ 0 ].concat( res[ 1 ] );
877 var res = sequence( [
879 nOrMore( 0, templateParam )
881 if ( res === null ) {
884 return [ res[ 0 ] ].concat( res[ 1 ] );
887 openTemplate = makeStringParser( '{{' );
888 closeTemplate = makeStringParser( '}}' );
889 nonWhitespaceExpression = choice( [
896 paramExpression = choice( [
904 expression = choice( [
914 // Used when only {{-transformation is wanted, for 'text'
915 // or 'escaped' formats
916 curlyBraceTransformExpression = choice( [
919 curlyBraceTransformExpressionLiteral
925 * @param {Function} rootExpression Root parse function
926 * @return {Array|null}
928 function start( rootExpression ) {
929 var result = nOrMore( 0, rootExpression )();
930 if ( result === null ) {
933 return [ 'CONCAT' ].concat( result );
935 // everything above this point is supposed to be stateless/static, but
936 // I am deferring the work of turning it into prototypes & objects. It's quite fast enough
937 // finally let's do some actual work...
939 result = start( this.settings.onlyCurlyBraceTransform ? curlyBraceTransformExpression : expression );
942 * For success, the p must have gotten to the end of the input
943 * and returned a non-null.
944 * n.b. This is part of language infrastructure, so we do not throw an internationalizable message.
946 if ( result === null || pos !== input.length ) {
947 throw new Error( 'Parse error at position ' + pos.toString() + ' in input: ' + input );
955 * Class that primarily exists to emit HTML from parser ASTs.
959 * @param {Object} language
960 * @param {Object} magic
962 mw.jqueryMsg.HtmlEmitter = function ( language, magic ) {
964 this.language = language;
965 // eslint-disable-next-line jquery/no-each-util
966 $.each( magic, function ( key, val ) {
967 jmsg[ key.toLowerCase() ] = function () {
973 * (We put this method definition here, and not in prototype, to make sure it's not overwritten by any magic.)
974 * Walk entire node structure, applying replacements and template functions when appropriate
976 * @param {Mixed} node Abstract syntax tree (top node or subnode)
977 * @param {Array} replacements for $1, $2, ... $n
978 * @return {Mixed} single-string node or array of nodes suitable for jQuery appending
980 this.emit = function ( node, replacements ) {
981 var ret, subnodes, operation,
983 switch ( typeof node ) {
988 // typeof returns object for arrays
990 // node is an array of nodes
991 // eslint-disable-next-line jquery/no-map-util
992 subnodes = $.map( node.slice( 1 ), function ( n ) {
993 return jmsg.emit( n, replacements );
995 operation = node[ 0 ].toLowerCase();
996 if ( typeof jmsg[ operation ] === 'function' ) {
997 ret = jmsg[ operation ]( subnodes, replacements );
999 throw new Error( 'Unknown operation "' + operation + '"' );
1003 // Parsing the empty string (as an entire expression, or as a paramExpression in a template) results in undefined
1004 // Perhaps a more clever parser can detect this, and return the empty string? Or is that useful information?
1005 // The logical thing is probably to return the empty string here when we encounter undefined.
1009 throw new Error( 'Unexpected type in AST: ' + typeof node );
1015 // For everything in input that follows double-open-curly braces, there should be an equivalent parser
1016 // function. For instance {{PLURAL ... }} will be processed by 'plural'.
1017 // If you have 'magic words' then configure the parser to have them upon creation.
1019 // An emitter method takes the parent node, the array of subnodes and the array of replacements (the values that $1, $2... should translate to).
1020 // Note: all such functions must be pure, with the exception of referring to other pure functions via this.language (convertPlural and so on)
1021 mw.jqueryMsg.HtmlEmitter.prototype = {
1023 * Parsing has been applied depth-first we can assume that all nodes here are single nodes
1024 * Must return a single node to parents -- a jQuery with synthetic span
1025 * However, unwrap any other synthetic spans in our children and pass them upwards
1027 * @param {Mixed[]} nodes Some single nodes, some arrays of nodes
1030 concat: function ( nodes ) {
1031 var $span = $( '<span>' ).addClass( 'mediaWiki_htmlEmitter' );
1032 // eslint-disable-next-line jquery/no-each-util
1033 $.each( nodes, function ( i, node ) {
1034 // Let jQuery append nodes, arrays of nodes and jQuery objects
1035 // other things (strings, numbers, ..) are appended as text nodes (not as HTML strings)
1036 appendWithoutParsing( $span, node );
1042 * Return escaped replacement of correct index, or string if unavailable.
1043 * Note that we expect the parsed parameter to be zero-based. i.e. $1 should have become [ 0 ].
1044 * if the specified parameter is not found return the same string
1045 * (e.g. "$99" -> parameter 98 -> not found -> return "$99" )
1047 * TODO: Throw error if nodes.length > 1 ?
1049 * @param {Array} nodes List of one element, integer, n >= 0
1050 * @param {Array} replacements List of at least n strings
1051 * @return {string|jQuery} replacement
1053 replace: function ( nodes, replacements ) {
1054 var index = parseInt( nodes[ 0 ], 10 );
1056 if ( index < replacements.length ) {
1057 return replacements[ index ];
1059 // index not found, fallback to displaying variable
1060 return '$' + ( index + 1 );
1065 * Transform wiki-link
1068 * It only handles basic cases, either no pipe, or a pipe with an explicit
1071 * It does not attempt to handle features like the pipe trick.
1072 * However, the pipe trick should usually not be present in wikitext retrieved
1073 * from the server, since the replacement is done at save time.
1074 * It may, though, if the wikitext appears in extension-controlled content.
1076 * @param {string[]} nodes
1079 wikilink: function ( nodes ) {
1080 var page, anchor, url, $el;
1082 page = textify( nodes[ 0 ] );
1083 // Strip leading ':', which is used to suppress special behavior in wikitext links,
1084 // e.g. [[:Category:Foo]] or [[:File:Foo.jpg]]
1085 if ( page.charAt( 0 ) === ':' ) {
1086 page = page.slice( 1 );
1088 url = mw.util.getUrl( page );
1090 if ( nodes.length === 1 ) {
1091 // [[Some Page]] or [[Namespace:Some Page]]
1094 // [[Some Page|anchor text]] or [[Namespace:Some Page|anchor]]
1095 anchor = nodes[ 1 ];
1098 $el = $( '<a>' ).attr( {
1102 return appendWithoutParsing( $el, anchor );
1106 * Converts array of HTML element key value pairs to object
1108 * @param {Array} nodes Array of consecutive key value pairs, with index 2 * n being a
1109 * name and 2 * n + 1 the associated value
1110 * @return {Object} Object mapping attribute name to attribute value
1112 htmlattributes: function ( nodes ) {
1113 var i, len, mapping = {};
1114 for ( i = 0, len = nodes.length; i < len; i += 2 ) {
1115 mapping[ nodes[ i ] ] = decodePrimaryHtmlEntities( nodes[ i + 1 ] );
1121 * Handles an (already-validated) HTML element.
1123 * @param {Array} nodes Nodes to process when creating element
1126 htmlelement: function ( nodes ) {
1127 var tagName, attributes, contents, $element;
1129 tagName = nodes.shift();
1130 attributes = nodes.shift();
1132 $element = $( document.createElement( tagName ) ).attr( attributes );
1133 return appendWithoutParsing( $element, contents );
1137 * Transform parsed structure into external link.
1139 * The "href" can be:
1140 * - a jQuery object, treat it as "enclosing" the link text.
1141 * - a function, treat it as the click handler.
1142 * - a string, or our HtmlEmitter jQuery object, treat it as a URI after stringifying.
1144 * TODO: throw an error if nodes.length > 2 ?
1146 * @param {Array} nodes List of two elements, {jQuery|Function|String} and {string}
1149 extlink: function ( nodes ) {
1152 contents = nodes[ 1 ];
1153 if ( arg instanceof $ && !arg.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1157 if ( typeof arg === 'function' ) {
1161 } ).on( 'click keypress', function ( e ) {
1163 e.type === 'click' ||
1164 e.type === 'keypress' && e.which === 13
1166 arg.call( this, e );
1170 $el.attr( 'href', textify( arg ) );
1173 return appendWithoutParsing( $el.empty(), contents );
1177 * Transform parsed structure into pluralization
1178 * n.b. The first node may be a non-integer (for instance, a string representing an Arabic number).
1179 * So convert it back with the current language's convertNumber.
1181 * @param {Array} nodes List of nodes, [ {string|number}, {string}, {string} ... ]
1182 * @return {string|jQuery} selected pluralized form according to current language
1184 plural: function ( nodes ) {
1185 var forms, firstChild, firstChildText, explicitPluralFormNumber, formIndex, form, count,
1186 explicitPluralForms = {};
1188 count = parseFloat( this.language.convertNumber( textify( nodes[ 0 ] ), true ) );
1189 forms = nodes.slice( 1 );
1190 for ( formIndex = 0; formIndex < forms.length; formIndex++ ) {
1191 form = forms[ formIndex ];
1193 if ( form instanceof $ && form.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1194 // This is a nested node, may be an explicit plural form like 5=[$2 linktext]
1195 firstChild = form.contents().get( 0 );
1196 if ( firstChild && firstChild.nodeType === Node.TEXT_NODE ) {
1197 firstChildText = firstChild.textContent;
1198 if ( /^\d+=/.test( firstChildText ) ) {
1199 explicitPluralFormNumber = parseInt( firstChildText.split( /=/ )[ 0 ], 10 );
1200 // Use the digit part as key and rest of first text node and
1201 // rest of child nodes as value.
1202 firstChild.textContent = firstChildText.slice( firstChildText.indexOf( '=' ) + 1 );
1203 explicitPluralForms[ explicitPluralFormNumber ] = form;
1204 forms[ formIndex ] = undefined;
1207 } else if ( /^\d+=/.test( form ) ) {
1208 // Simple explicit plural forms like 12=a dozen
1209 explicitPluralFormNumber = parseInt( form.split( /=/ )[ 0 ], 10 );
1210 explicitPluralForms[ explicitPluralFormNumber ] = form.slice( form.indexOf( '=' ) + 1 );
1211 forms[ formIndex ] = undefined;
1215 // Remove explicit plural forms from the forms. They were set undefined in the above loop.
1216 // eslint-disable-next-line jquery/no-map-util
1217 forms = $.map( forms, function ( form ) {
1221 return this.language.convertPlural( count, forms, explicitPluralForms );
1225 * Transform parsed structure according to gender.
1227 * Usage: {{gender:[ mw.user object | '' | 'male' | 'female' | 'unknown' ] | masculine form | feminine form | neutral form}}.
1229 * The first node must be one of:
1230 * - the mw.user object (or a compatible one)
1231 * - an empty string - indicating the current user, same effect as passing the mw.user object
1232 * - a gender string ('male', 'female' or 'unknown')
1234 * @param {Array} nodes List of nodes, [ {string|mw.user}, {string}, {string}, {string} ]
1235 * @return {string|jQuery} Selected gender form according to current language
1237 gender: function ( nodes ) {
1239 maybeUser = nodes[ 0 ],
1240 forms = nodes.slice( 1 );
1242 if ( maybeUser === '' ) {
1243 maybeUser = mw.user;
1246 // If we are passed a mw.user-like object, check their gender.
1247 // Otherwise, assume the gender string itself was passed .
1248 if ( maybeUser && maybeUser.options instanceof mw.Map ) {
1249 gender = maybeUser.options.get( 'gender' );
1251 gender = textify( maybeUser );
1254 return this.language.gender( gender, forms );
1258 * Transform parsed structure into grammar conversion.
1259 * Invoked by putting `{{grammar
:form
|word
}}` in a message
1261 * @param {Array} nodes List of nodes [{Grammar case eg: genitive}, {string word}]
1262 * @return {string|jQuery} selected grammatical form according to current language
1264 grammar: function ( nodes ) {
1265 var form = nodes[ 0 ],
1267 // These could be jQuery objects (passed as message parameters),
1268 // in which case we can't transform them (like rawParams() in PHP).
1269 if ( typeof form === 'string' && typeof word === 'string' ) {
1270 return this.language.convertGrammar( word, form );
1276 * Tranform parsed structure into a int: (interface language) message include
1277 * Invoked by putting `{{int:othermessage
}}` into a message
1279 * TODO Syntax in the included message is not parsed, this seems like a bug?
1281 * @param {Array} nodes List of nodes
1282 * @return {string} Other message
1284 int: function ( nodes ) {
1285 var msg = textify( nodes[ 0 ] );
1286 return mw.jqueryMsg.getMessageFunction()( msg.charAt( 0 ).toLowerCase() + msg.slice( 1 ) );
1290 * Get localized namespace name from canonical name or namespace number.
1291 * Invoked by putting `{{ns
:foo
}}` into a message
1293 * @param {Array} nodes List of nodes
1294 * @return {string} Localized namespace name
1296 ns: function ( nodes ) {
1297 var ns = textify( nodes[ 0 ] ).trim();
1298 if ( !/^\d+$/.test( ns ) ) {
1299 ns = mw.config.get( 'wgNamespaceIds' )[ ns.replace( / /g, '_' ).toLowerCase() ];
1301 ns = mw.config.get( 'wgFormattedNamespaces' )[ ns ];
1306 * Takes an unformatted number (arab, no group separators and . as decimal separator)
1307 * and outputs it in the localized digit script and formatted with decimal
1308 * separator, according to the current language.
1310 * @param {Array} nodes List of nodes
1311 * @return {number|string|jQuery} Formatted number
1313 formatnum: function ( nodes ) {
1314 var isInteger = !!nodes[ 1 ] && nodes[ 1 ] === 'R',
1315 number = nodes[ 0 ];
1317 // These could be jQuery objects (passed as message parameters),
1318 // in which case we can't transform them (like rawParams() in PHP).
1319 if ( typeof number === 'string' || typeof number === 'number' ) {
1320 return this.language.convertNumber( number, isInteger );
1328 * @param {Array} nodes List of nodes
1329 * @return {string} The given text, all in lowercase
1331 lc: function ( nodes ) {
1332 return textify( nodes[ 0 ] ).toLowerCase();
1338 * @param {Array} nodes List of nodes
1339 * @return {string} The given text, all in uppercase
1341 uc: function ( nodes ) {
1342 return textify( nodes[ 0 ] ).toUpperCase();
1346 * Lowercase first letter of input, leaving the rest unchanged
1348 * @param {Array} nodes List of nodes
1349 * @return {string} The given text, with the first character in lowercase
1351 lcfirst: function ( nodes ) {
1352 var text = textify( nodes[ 0 ] );
1353 return text.charAt( 0 ).toLowerCase() + text.slice( 1 );
1357 * Uppercase first letter of input, leaving the rest unchanged
1359 * @param {Array} nodes List of nodes
1360 * @return {string} The given text, with the first character in uppercase
1362 ucfirst: function ( nodes ) {
1363 var text = textify( nodes[ 0 ] );
1364 return text.charAt( 0 ).toUpperCase() + text.slice( 1 );
1371 * @see mw.jqueryMsg#getPlugin
1373 $.fn.msg = mw.jqueryMsg.getPlugin();
1375 // Replace the default message parser with jqueryMsg
1376 oldParser = mw.Message.prototype.parser;
1377 mw.Message.prototype.parser = function () {
1378 // Fall back to mw.msg's simple parser where possible
1380 // Plain text output always uses the simple parser
1381 this.format === 'plain' ||
1383 // jqueryMsg parser is needed for messages containing wikitext
1384 !/\{\{|[<>[&]/.test( this.map.get( this.key ) ) &&
1385 // jqueryMsg parser is needed when jQuery objects or DOM nodes are passed in as parameters
1386 !this.parameters.some( function ( param ) {
1387 return param instanceof $ || ( param && param.nodeType !== undefined );
1391 return oldParser.apply( this );
1394 if ( !Object.prototype.hasOwnProperty.call( this.map, this.format ) ) {
1395 this.map[ this.format ] = mw.jqueryMsg.getMessageFunction( {
1397 // For format 'escaped', escaping part is handled by mediawiki.js
1401 return this.map[ this.format ]( this.key, this.parameters );
1405 * Parse the message to DOM nodes, rather than HTML string like #parse.
1407 * This method is only available when jqueryMsg is loaded.
1411 * @member mw.Message
1414 mw.Message.prototype.parseDom = ( function () {
1415 var $wrapper = $( '<div>' );
1416 return function () {
1417 return $wrapper.msg( this.key, this.parameters ).contents().detach();