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 setPrivateData().
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 ( !$.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 jQuery
&& 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 jQuery
) {
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 // eslint-disable-next-line new-cap
139 parser
= new mw
.jqueryMsg
.parser( options
),
141 argsArray
= $.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 use as a global, to construct strings from the message key (and optional replacements).
193 * window.gM = mediaWiki.jqueryMsg.getMessageFunction( options );
194 * $( 'p#headline' ).html( gM( 'hello-user', username ) );
196 * Like the old gM() function this returns only strings, so it destroys any bindings. If you want to preserve bindings use the
197 * jQuery plugin version instead. This is only included for backwards compatibility with gM().
199 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
200 * somefunction( a, b, c, d )
202 * somefunction( a, [b, c, d] )
204 * @param {Object} options parser options
205 * @return {Function} Function suitable for assigning to window.gM
206 * @return {string} return.key Message key.
207 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
208 * @return {string} return.return Rendered HTML.
210 mw
.jqueryMsg
.getMessageFunction = function ( options
) {
211 var failableParserFn
, format
;
213 if ( options
&& options
.format
!== undefined ) {
214 format
= options
.format
;
216 format
= parserDefaults
.format
;
221 if ( !failableParserFn
) {
222 failableParserFn
= getFailableParserFn( options
);
224 failableResult
= failableParserFn( arguments
);
225 if ( format
=== 'text' || format
=== 'escaped' ) {
226 return failableResult
.text();
228 return failableResult
.html();
234 * Returns a jQuery plugin which parses the message in the message key, doing replacements optionally, and appends the nodes to
235 * the current selector. Bindings to passed-in jquery elements are preserved. Functions become click handlers for [$1 linktext] links.
238 * $.fn.msg = mediaWiki.jqueryMsg.getPlugin( options );
239 * var userlink = $( '<a>' ).click( function () { alert( "hello!!" ) } );
240 * $( 'p#headline' ).msg( 'hello-user', userlink );
242 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
243 * somefunction( a, b, c, d )
245 * somefunction( a, [b, c, d] )
247 * We append to 'this', which in a jQuery plugin context will be the selected elements.
249 * @param {Object} options Parser options
250 * @return {Function} Function suitable for assigning to jQuery plugin, such as jQuery#msg
251 * @return {string} return.key Message key.
252 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
253 * @return {jQuery} return.return
255 mw
.jqueryMsg
.getPlugin = function ( options
) {
256 var failableParserFn
;
260 if ( !failableParserFn
) {
261 failableParserFn
= getFailableParserFn( options
);
263 $target
= this.empty();
264 appendWithoutParsing( $target
, failableParserFn( arguments
) );
271 * Describes an object, whose primary duty is to .parse() message keys.
275 * @param {Object} options
277 mw
.jqueryMsg
.parser = function ( options
) {
278 this.settings
= $.extend( {}, parserDefaults
, options
);
279 this.settings
.onlyCurlyBraceTransform
= ( this.settings
.format
=== 'text' || this.settings
.format
=== 'escaped' );
282 // eslint-disable-next-line new-cap
283 this.emitter
= new mw
.jqueryMsg
.htmlEmitter( this.settings
.language
, this.settings
.magic
);
286 mw
.jqueryMsg
.parser
.prototype = {
288 * Where the magic happens.
289 * Parses a message from the key, and swaps in replacements as necessary, wraps in jQuery
290 * If an error is thrown, returns original key, and logs the error
292 * @param {string} key Message key.
293 * @param {Array} replacements Variable replacements for $1, $2... $n
296 parse: function ( key
, replacements
) {
297 var ast
= this.getAst( key
);
298 return this.emitter
.emit( ast
, replacements
);
302 * Fetch the message string associated with a key, return parsed structure. Memoized.
303 * Note that we pass '⧼' + key + '⧽' back for a missing message here.
305 * @param {string} key
306 * @return {string|Array} string of '⧼key⧽' if message missing, simple string if possible, array of arrays if needs parsing
308 getAst: function ( key
) {
311 if ( !this.astCache
.hasOwnProperty( key
) ) {
312 wikiText
= this.settings
.messages
.get( key
);
313 if ( typeof wikiText
!== 'string' ) {
314 wikiText
= '⧼' + key
+ '⧽';
316 this.astCache
[ key
] = this.wikiTextToAst( wikiText
);
318 return this.astCache
[ key
];
322 * Parses the input wikiText into an abstract syntax tree, essentially an s-expression.
324 * CAVEAT: This does not parse all wikitext. It could be more efficient, but it's pretty good already.
325 * n.b. We want to move this functionality to the server. Nothing here is required to be on the client.
327 * @param {string} input Message string wikitext
329 * @return {Mixed} abstract syntax tree
331 wikiTextToAst: function ( input
) {
333 regularLiteral
, regularLiteralWithoutBar
, regularLiteralWithoutSpace
, regularLiteralWithSquareBrackets
,
334 doubleQuote
, singleQuote
, backslash
, anyCharacter
, asciiAlphabetLiteral
,
335 escapedOrLiteralWithoutSpace
, escapedOrLiteralWithoutBar
, escapedOrRegularLiteral
,
336 whitespace
, dollar
, digits
, htmlDoubleQuoteAttributeValue
, htmlSingleQuoteAttributeValue
,
337 htmlAttributeEquals
, openHtmlStartTag
, optionalForwardSlash
, openHtmlEndTag
, closeHtmlTag
,
338 openExtlink
, closeExtlink
, wikilinkContents
, openWikilink
, closeWikilink
, templateName
, pipe
, colon
,
339 templateContents
, openTemplate
, closeTemplate
,
340 nonWhitespaceExpression
, paramExpression
, expression
, curlyBraceTransformExpression
, result
,
341 settings
= this.settings
,
342 concat
= Array
.prototype.concat
;
344 // Indicates current position in input as we parse through it.
345 // Shared among all parsing functions below.
348 // =========================================================
349 // parsing combinators - could be a library on its own
350 // =========================================================
353 * Try parsers until one works, if none work return null
356 * @param {Function[]} ps
357 * @return {string|null}
359 function choice( ps
) {
362 for ( i
= 0; i
< ps
.length
; i
++ ) {
364 if ( result
!== null ) {
373 * Try several ps in a row, all must succeed or return null.
374 * This is the only eager one.
377 * @param {Function[]} ps
378 * @return {string|null}
380 function sequence( ps
) {
384 for ( i
= 0; i
< ps
.length
; i
++ ) {
386 if ( res
=== null ) {
396 * Run the same parser over and over until it fails.
397 * Must succeed a minimum of n times or return null.
401 * @param {Function} p
402 * @return {string|null}
404 function nOrMore( n
, p
) {
406 var originalPos
= pos
,
409 while ( parsed
!== null ) {
410 result
.push( parsed
);
413 if ( result
.length
< n
) {
422 * There is a general pattern -- parse a thing, if that worked, apply transform, otherwise return null.
424 * TODO: But using this as a combinator seems to cause problems when combined with #nOrMore().
425 * May be some scoping issue
428 * @param {Function} p
429 * @param {Function} fn
430 * @return {string|null}
432 function transform( p
, fn
) {
435 return result
=== null ? null : fn( result
);
440 * Just make parsers out of simpler JS builtin types
445 * @return {string} return.return
447 function makeStringParser( s
) {
451 if ( input
.substr( pos
, len
) === s
) {
460 * Makes a regex parser, given a RegExp object.
461 * The regex being passed in should start with a ^ to anchor it to the start
465 * @param {RegExp} regex anchored regex
466 * @return {Function} function to parse input based on the regex
468 function makeRegexParser( regex
) {
470 var matches
= input
.slice( pos
).match( regex
);
471 if ( matches
=== null ) {
474 pos
+= matches
[ 0 ].length
;
479 // ===================================================================
480 // General patterns above this line -- wikitext specific parsers below
481 // ===================================================================
483 // Parsing functions follow. All parsing functions work like this:
484 // They don't accept any arguments.
485 // Instead, they just operate non destructively on the string 'input'
486 // As they can consume parts of the string, they advance the shared variable pos,
487 // and return tokens (or whatever else they want to return).
488 // some things are defined as closures and other things as ordinary functions
489 // converting everything to a closure makes it a lot harder to debug... errors pop up
490 // but some debuggers can't tell you exactly where they come from. Also the mutually
491 // recursive functions seem not to work in all browsers then. (Tested IE6-7, Opera, Safari, FF)
492 // This may be because, to save code, memoization was removed
494 regularLiteral
= makeRegexParser( /^[^{}\[\]$<\\]/ );
495 regularLiteralWithoutBar
= makeRegexParser( /^[^{}\[\]$\\|]/ );
496 regularLiteralWithoutSpace
= makeRegexParser( /^[^{}\[\]$\s]/ );
497 regularLiteralWithSquareBrackets
= makeRegexParser( /^[^{}$\\]/ );
499 backslash
= makeStringParser( '\\' );
500 doubleQuote
= makeStringParser( '"' );
501 singleQuote
= makeStringParser( '\'' );
502 anyCharacter
= makeRegexParser( /^./ );
504 openHtmlStartTag
= makeStringParser( '<' );
505 optionalForwardSlash
= makeRegexParser( /^\/?/ );
506 openHtmlEndTag
= makeStringParser( '</' );
507 htmlAttributeEquals
= makeRegexParser( /^\s*=\s*/ );
508 closeHtmlTag
= makeRegexParser( /^\s*>/ );
510 function escapedLiteral() {
511 var result
= sequence( [
515 return result
=== null ? null : result
[ 1 ];
517 escapedOrLiteralWithoutSpace
= choice( [
519 regularLiteralWithoutSpace
521 escapedOrLiteralWithoutBar
= choice( [
523 regularLiteralWithoutBar
525 escapedOrRegularLiteral
= choice( [
529 // Used to define "literals" without spaces, in space-delimited situations
530 function literalWithoutSpace() {
531 var result
= nOrMore( 1, escapedOrLiteralWithoutSpace
)();
532 return result
=== null ? null : result
.join( '' );
534 // Used to define "literals" within template parameters. The pipe character is the parameter delimeter, so by default
535 // it is not a literal in the parameter
536 function literalWithoutBar() {
537 var result
= nOrMore( 1, escapedOrLiteralWithoutBar
)();
538 return result
=== null ? null : result
.join( '' );
542 var result
= nOrMore( 1, escapedOrRegularLiteral
)();
543 return result
=== null ? null : result
.join( '' );
546 function curlyBraceTransformExpressionLiteral() {
547 var result
= nOrMore( 1, regularLiteralWithSquareBrackets
)();
548 return result
=== null ? null : result
.join( '' );
551 asciiAlphabetLiteral
= makeRegexParser( /^[A-Za-z]+/ );
552 htmlDoubleQuoteAttributeValue
= makeRegexParser( /^[^"]*/ );
553 htmlSingleQuoteAttributeValue
= makeRegexParser( /^[^']*/ );
555 whitespace
= makeRegexParser( /^\s+/ );
556 dollar
= makeStringParser( '$' );
557 digits
= makeRegexParser( /^\d+/ );
559 function replacement() {
560 var result
= sequence( [
564 if ( result
=== null ) {
567 return [ 'REPLACE', parseInt( result
[ 1 ], 10 ) - 1 ];
569 openExtlink
= makeStringParser( '[' );
570 closeExtlink
= makeStringParser( ']' );
571 // this extlink MUST have inner contents, e.g. [foo] not allowed; [foo bar] [foo <i>bar</i>], etc. are allowed
573 var result
, parsedResult
, target
;
575 parsedResult
= sequence( [
577 nOrMore( 1, nonWhitespaceExpression
),
579 nOrMore( 1, expression
),
582 if ( parsedResult
!== null ) {
583 // When the entire link target is a single parameter, we can't use CONCAT, as we allow
584 // passing fancy parameters (like a whole jQuery object or a function) to use for the
585 // link. Check only if it's a single match, since we can either do CONCAT or not for
586 // singles with the same effect.
587 target
= parsedResult
[ 1 ].length
=== 1 ?
588 parsedResult
[ 1 ][ 0 ] :
589 [ 'CONCAT' ].concat( parsedResult
[ 1 ] );
593 [ 'CONCAT' ].concat( parsedResult
[ 3 ] )
598 openWikilink
= makeStringParser( '[[' );
599 closeWikilink
= makeStringParser( ']]' );
600 pipe
= makeStringParser( '|' );
602 function template() {
603 var result
= sequence( [
608 return result
=== null ? null : result
[ 1 ];
611 function pipedWikilink() {
612 var result
= sequence( [
613 nOrMore( 1, paramExpression
),
615 nOrMore( 1, expression
)
617 return result
=== null ? null : [
618 [ 'CONCAT' ].concat( result
[ 0 ] ),
619 [ 'CONCAT' ].concat( result
[ 2 ] )
623 function unpipedWikilink() {
624 var result
= sequence( [
625 nOrMore( 1, paramExpression
)
627 return result
=== null ? null : [
628 [ 'CONCAT' ].concat( result
[ 0 ] )
632 wikilinkContents
= choice( [
637 function wikilink() {
638 var result
, parsedResult
, parsedLinkContents
;
641 parsedResult
= sequence( [
646 if ( parsedResult
!== null ) {
647 parsedLinkContents
= parsedResult
[ 1 ];
648 result
= [ 'WIKILINK' ].concat( parsedLinkContents
);
653 // TODO: Support data- if appropriate
654 function doubleQuotedHtmlAttributeValue() {
655 var parsedResult
= sequence( [
657 htmlDoubleQuoteAttributeValue
,
660 return parsedResult
=== null ? null : parsedResult
[ 1 ];
663 function singleQuotedHtmlAttributeValue() {
664 var parsedResult
= sequence( [
666 htmlSingleQuoteAttributeValue
,
669 return parsedResult
=== null ? null : parsedResult
[ 1 ];
672 function htmlAttribute() {
673 var parsedResult
= sequence( [
675 asciiAlphabetLiteral
,
678 doubleQuotedHtmlAttributeValue
,
679 singleQuotedHtmlAttributeValue
682 return parsedResult
=== null ? null : [ parsedResult
[ 1 ], parsedResult
[ 3 ] ];
686 * Checks if HTML is allowed
688 * @param {string} startTagName HTML start tag name
689 * @param {string} endTagName HTML start tag name
690 * @param {Object} attributes array of consecutive key value pairs,
691 * with index 2 * n being a name and 2 * n + 1 the associated value
692 * @return {boolean} true if this is HTML is allowed, false otherwise
694 function isAllowedHtml( startTagName
, endTagName
, attributes
) {
695 var i
, len
, attributeName
;
697 startTagName
= startTagName
.toLowerCase();
698 endTagName
= endTagName
.toLowerCase();
699 if ( startTagName
!== endTagName
|| $.inArray( startTagName
, settings
.allowedHtmlElements
) === -1 ) {
703 for ( i
= 0, len
= attributes
.length
; i
< len
; i
+= 2 ) {
704 attributeName
= attributes
[ i
];
705 if ( $.inArray( attributeName
, settings
.allowedHtmlCommonAttributes
) === -1 &&
706 $.inArray( attributeName
, settings
.allowedHtmlAttributesByElement
[ startTagName
] || [] ) === -1 ) {
714 function htmlAttributes() {
715 var parsedResult
= nOrMore( 0, htmlAttribute
)();
716 // Un-nest attributes array due to structure of jQueryMsg operations (see emit).
717 return concat
.apply( [ 'HTMLATTRIBUTES' ], parsedResult
);
720 // Subset of allowed HTML markup.
721 // Most elements and many attributes allowed on the server are not supported yet.
723 var parsedOpenTagResult
, parsedHtmlContents
, parsedCloseTagResult
,
724 wrappedAttributes
, attributes
, startTagName
, endTagName
, startOpenTagPos
,
725 startCloseTagPos
, endOpenTagPos
, endCloseTagPos
,
728 // Break into three sequence calls. That should allow accurate reconstruction of the original HTML, and requiring an exact tag name match.
729 // 1. open through closeHtmlTag
731 // 3. openHtmlEnd through close
732 // This will allow recording the positions to reconstruct if HTML is to be treated as text.
734 startOpenTagPos
= pos
;
735 parsedOpenTagResult
= sequence( [
737 asciiAlphabetLiteral
,
739 optionalForwardSlash
,
743 if ( parsedOpenTagResult
=== null ) {
748 startTagName
= parsedOpenTagResult
[ 1 ];
750 parsedHtmlContents
= nOrMore( 0, expression
)();
752 startCloseTagPos
= pos
;
753 parsedCloseTagResult
= sequence( [
755 asciiAlphabetLiteral
,
759 if ( parsedCloseTagResult
=== null ) {
760 // Closing tag failed. Return the start tag and contents.
761 return [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
762 .concat( parsedHtmlContents
);
765 endCloseTagPos
= pos
;
766 endTagName
= parsedCloseTagResult
[ 1 ];
767 wrappedAttributes
= parsedOpenTagResult
[ 2 ];
768 attributes
= wrappedAttributes
.slice( 1 );
769 if ( isAllowedHtml( startTagName
, endTagName
, attributes
) ) {
770 result
= [ 'HTMLELEMENT', startTagName
, wrappedAttributes
]
771 .concat( parsedHtmlContents
);
773 // HTML is not allowed, so contents will remain how
774 // it was, while HTML markup at this level will be
776 // E.g. assuming script tags are not allowed:
778 // <script>[[Foo|bar]]</script>
780 // results in '<script>' and '</script>'
781 // (not treated as an HTML tag), surrounding a fully
784 // Concatenate everything from the tag, flattening the contents.
785 result
= [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
786 .concat( parsedHtmlContents
, input
.slice( startCloseTagPos
, endCloseTagPos
) );
792 // <nowiki>...</nowiki> tag. The tags are stripped and the contents are returned unparsed.
794 var parsedResult
, plainText
,
797 parsedResult
= sequence( [
798 makeStringParser( '<nowiki>' ),
799 // We use a greedy non-backtracking parser, so we must ensure here that we don't take too much
800 makeRegexParser( /^.*?(?=<\/nowiki>)/ ),
801 makeStringParser( '</nowiki>' )
803 if ( parsedResult
!== null ) {
804 plainText
= parsedResult
[ 1 ];
805 result
= [ 'CONCAT' ].concat( plainText
);
811 templateName
= transform(
812 // see $wgLegalTitleChars
813 // not allowing : due to the need to catch "PLURAL:$1"
814 makeRegexParser( /^[ !"$&'()*,.\/0-9;=?@A-Z\^_`a-z~\x80-\xFF+\-]+/ ),
815 function ( result
) { return result
.toString(); }
817 function templateParam() {
821 nOrMore( 0, paramExpression
)
823 if ( result
=== null ) {
827 // use a CONCAT operator if there are multiple nodes, otherwise return the first node, raw.
828 return expr
.length
> 1 ? [ 'CONCAT' ].concat( expr
) : expr
[ 0 ];
831 function templateWithReplacement() {
832 var result
= sequence( [
837 return result
=== null ? null : [ result
[ 0 ], result
[ 2 ] ];
839 function templateWithOutReplacement() {
840 var result
= sequence( [
845 return result
=== null ? null : [ result
[ 0 ], result
[ 2 ] ];
847 function templateWithOutFirstParameter() {
848 var result
= sequence( [
852 return result
=== null ? null : [ result
[ 0 ], '' ];
854 colon
= makeStringParser( ':' );
855 templateContents
= choice( [
857 var res
= sequence( [
858 // templates can have placeholders for dynamic replacement eg: {{PLURAL:$1|one car|$1 cars}}
859 // or no placeholders eg: {{GRAMMAR:genitive|{{SITENAME}}}
860 choice( [ templateWithReplacement
, templateWithOutReplacement
, templateWithOutFirstParameter
] ),
861 nOrMore( 0, templateParam
)
863 return res
=== null ? null : res
[ 0 ].concat( res
[ 1 ] );
866 var res
= sequence( [
868 nOrMore( 0, templateParam
)
870 if ( res
=== null ) {
873 return [ res
[ 0 ] ].concat( res
[ 1 ] );
876 openTemplate
= makeStringParser( '{{' );
877 closeTemplate
= makeStringParser( '}}' );
878 nonWhitespaceExpression
= choice( [
885 paramExpression
= choice( [
893 expression
= choice( [
903 // Used when only {{-transformation is wanted, for 'text'
904 // or 'escaped' formats
905 curlyBraceTransformExpression
= choice( [
908 curlyBraceTransformExpressionLiteral
914 * @param {Function} rootExpression Root parse function
915 * @return {Array|null}
917 function start( rootExpression
) {
918 var result
= nOrMore( 0, rootExpression
)();
919 if ( result
=== null ) {
922 return [ 'CONCAT' ].concat( result
);
924 // everything above this point is supposed to be stateless/static, but
925 // I am deferring the work of turning it into prototypes & objects. It's quite fast enough
926 // finally let's do some actual work...
928 result
= start( this.settings
.onlyCurlyBraceTransform
? curlyBraceTransformExpression
: expression
);
931 * For success, the p must have gotten to the end of the input
932 * and returned a non-null.
933 * n.b. This is part of language infrastructure, so we do not throw an internationalizable message.
935 if ( result
=== null || pos
!== input
.length
) {
936 throw new Error( 'Parse error at position ' + pos
.toString() + ' in input: ' + input
);
944 * htmlEmitter - object which primarily exists to emit HTML from parser ASTs
946 * @param {Object} language
947 * @param {Object} magic
949 mw
.jqueryMsg
.htmlEmitter = function ( language
, magic
) {
951 this.language
= language
;
952 $.each( magic
, function ( key
, val
) {
953 jmsg
[ key
.toLowerCase() ] = function () {
959 * (We put this method definition here, and not in prototype, to make sure it's not overwritten by any magic.)
960 * Walk entire node structure, applying replacements and template functions when appropriate
962 * @param {Mixed} node Abstract syntax tree (top node or subnode)
963 * @param {Array} replacements for $1, $2, ... $n
964 * @return {Mixed} single-string node or array of nodes suitable for jQuery appending
966 this.emit = function ( node
, replacements
) {
967 var ret
, subnodes
, operation
,
969 switch ( typeof node
) {
974 // typeof returns object for arrays
976 // node is an array of nodes
977 subnodes
= $.map( node
.slice( 1 ), function ( n
) {
978 return jmsg
.emit( n
, replacements
);
980 operation
= node
[ 0 ].toLowerCase();
981 if ( typeof jmsg
[ operation
] === 'function' ) {
982 ret
= jmsg
[ operation
]( subnodes
, replacements
);
984 throw new Error( 'Unknown operation "' + operation
+ '"' );
988 // Parsing the empty string (as an entire expression, or as a paramExpression in a template) results in undefined
989 // Perhaps a more clever parser can detect this, and return the empty string? Or is that useful information?
990 // The logical thing is probably to return the empty string here when we encounter undefined.
994 throw new Error( 'Unexpected type in AST: ' + typeof node
);
1000 // For everything in input that follows double-open-curly braces, there should be an equivalent parser
1001 // function. For instance {{PLURAL ... }} will be processed by 'plural'.
1002 // If you have 'magic words' then configure the parser to have them upon creation.
1004 // An emitter method takes the parent node, the array of subnodes and the array of replacements (the values that $1, $2... should translate to).
1005 // Note: all such functions must be pure, with the exception of referring to other pure functions via this.language (convertPlural and so on)
1006 mw
.jqueryMsg
.htmlEmitter
.prototype = {
1008 * Parsing has been applied depth-first we can assume that all nodes here are single nodes
1009 * Must return a single node to parents -- a jQuery with synthetic span
1010 * However, unwrap any other synthetic spans in our children and pass them upwards
1012 * @param {Mixed[]} nodes Some single nodes, some arrays of nodes
1015 concat: function ( nodes
) {
1016 var $span
= $( '<span>' ).addClass( 'mediaWiki_htmlEmitter' );
1017 $.each( nodes
, function ( i
, node
) {
1018 // Let jQuery append nodes, arrays of nodes and jQuery objects
1019 // other things (strings, numbers, ..) are appended as text nodes (not as HTML strings)
1020 appendWithoutParsing( $span
, node
);
1026 * Return escaped replacement of correct index, or string if unavailable.
1027 * Note that we expect the parsed parameter to be zero-based. i.e. $1 should have become [ 0 ].
1028 * if the specified parameter is not found return the same string
1029 * (e.g. "$99" -> parameter 98 -> not found -> return "$99" )
1031 * TODO: Throw error if nodes.length > 1 ?
1033 * @param {Array} nodes List of one element, integer, n >= 0
1034 * @param {Array} replacements List of at least n strings
1035 * @return {string} replacement
1037 replace: function ( nodes
, replacements
) {
1038 var index
= parseInt( nodes
[ 0 ], 10 );
1040 if ( index
< replacements
.length
) {
1041 return replacements
[ index
];
1043 // index not found, fallback to displaying variable
1044 return '$' + ( index
+ 1 );
1049 * Transform wiki-link
1052 * It only handles basic cases, either no pipe, or a pipe with an explicit
1055 * It does not attempt to handle features like the pipe trick.
1056 * However, the pipe trick should usually not be present in wikitext retrieved
1057 * from the server, since the replacement is done at save time.
1058 * It may, though, if the wikitext appears in extension-controlled content.
1060 * @param {string[]} nodes
1063 wikilink: function ( nodes
) {
1064 var page
, anchor
, url
, $el
;
1066 page
= textify( nodes
[ 0 ] );
1067 // Strip leading ':', which is used to suppress special behavior in wikitext links,
1068 // e.g. [[:Category:Foo]] or [[:File:Foo.jpg]]
1069 if ( page
.charAt( 0 ) === ':' ) {
1070 page
= page
.slice( 1 );
1072 url
= mw
.util
.getUrl( page
);
1074 if ( nodes
.length
=== 1 ) {
1075 // [[Some Page]] or [[Namespace:Some Page]]
1078 // [[Some Page|anchor text]] or [[Namespace:Some Page|anchor]]
1079 anchor
= nodes
[ 1 ];
1082 $el
= $( '<a>' ).attr( {
1086 return appendWithoutParsing( $el
, anchor
);
1090 * Converts array of HTML element key value pairs to object
1092 * @param {Array} nodes Array of consecutive key value pairs, with index 2 * n being a
1093 * name and 2 * n + 1 the associated value
1094 * @return {Object} Object mapping attribute name to attribute value
1096 htmlattributes: function ( nodes
) {
1097 var i
, len
, mapping
= {};
1098 for ( i
= 0, len
= nodes
.length
; i
< len
; i
+= 2 ) {
1099 mapping
[ nodes
[ i
] ] = decodePrimaryHtmlEntities( nodes
[ i
+ 1 ] );
1105 * Handles an (already-validated) HTML element.
1107 * @param {Array} nodes Nodes to process when creating element
1108 * @return {jQuery|Array} jQuery node for valid HTML or array for disallowed element
1110 htmlelement: function ( nodes
) {
1111 var tagName
, attributes
, contents
, $element
;
1113 tagName
= nodes
.shift();
1114 attributes
= nodes
.shift();
1116 $element
= $( document
.createElement( tagName
) ).attr( attributes
);
1117 return appendWithoutParsing( $element
, contents
);
1121 * Transform parsed structure into external link.
1123 * The "href" can be:
1124 * - a jQuery object, treat it as "enclosing" the link text.
1125 * - a function, treat it as the click handler.
1126 * - a string, or our htmlEmitter jQuery object, treat it as a URI after stringifying.
1128 * TODO: throw an error if nodes.length > 2 ?
1130 * @param {Array} nodes List of two elements, {jQuery|Function|String} and {string}
1133 extlink: function ( nodes
) {
1136 contents
= nodes
[ 1 ];
1137 if ( arg
instanceof jQuery
&& !arg
.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1141 if ( typeof arg
=== 'function' ) {
1146 .on( 'click keypress', function ( e
) {
1148 e
.type
=== 'click' ||
1149 e
.type
=== 'keypress' && e
.which
=== 13
1151 arg
.call( this, e
);
1155 $el
.attr( 'href', textify( arg
) );
1158 return appendWithoutParsing( $el
.empty(), contents
);
1162 * Transform parsed structure into pluralization
1163 * n.b. The first node may be a non-integer (for instance, a string representing an Arabic number).
1164 * So convert it back with the current language's convertNumber.
1166 * @param {Array} nodes List of nodes, [ {string|number}, {string}, {string} ... ]
1167 * @return {string} selected pluralized form according to current language
1169 plural: function ( nodes
) {
1170 var forms
, firstChild
, firstChildText
, explicitPluralFormNumber
, formIndex
, form
, count
,
1171 explicitPluralForms
= {};
1173 count
= parseFloat( this.language
.convertNumber( nodes
[ 0 ], true ) );
1174 forms
= nodes
.slice( 1 );
1175 for ( formIndex
= 0; formIndex
< forms
.length
; formIndex
++ ) {
1176 form
= forms
[ formIndex
];
1178 if ( form
instanceof jQuery
&& form
.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1179 // This is a nested node, may be an explicit plural form like 5=[$2 linktext]
1180 firstChild
= form
.contents().get( 0 );
1181 if ( firstChild
&& firstChild
.nodeType
=== Node
.TEXT_NODE
) {
1182 firstChildText
= firstChild
.textContent
;
1183 if ( /^\d+=/.test( firstChildText
) ) {
1184 explicitPluralFormNumber
= parseInt( firstChildText
.split( /=/ )[ 0 ], 10 );
1185 // Use the digit part as key and rest of first text node and
1186 // rest of child nodes as value.
1187 firstChild
.textContent
= firstChildText
.slice( firstChildText
.indexOf( '=' ) + 1 );
1188 explicitPluralForms
[ explicitPluralFormNumber
] = form
;
1189 forms
[ formIndex
] = undefined;
1192 } else if ( /^\d+=/.test( form
) ) {
1193 // Simple explicit plural forms like 12=a dozen
1194 explicitPluralFormNumber
= parseInt( form
.split( /=/ )[ 0 ], 10 );
1195 explicitPluralForms
[ explicitPluralFormNumber
] = form
.slice( form
.indexOf( '=' ) + 1 );
1196 forms
[ formIndex
] = undefined;
1200 // Remove explicit plural forms from the forms. They were set undefined in the above loop.
1201 forms
= $.map( forms
, function ( form
) {
1205 return this.language
.convertPlural( count
, forms
, explicitPluralForms
);
1209 * Transform parsed structure according to gender.
1211 * Usage: {{gender:[ mw.user object | '' | 'male' | 'female' | 'unknown' ] | masculine form | feminine form | neutral form}}.
1213 * The first node must be one of:
1214 * - the mw.user object (or a compatible one)
1215 * - an empty string - indicating the current user, same effect as passing the mw.user object
1216 * - a gender string ('male', 'female' or 'unknown')
1218 * @param {Array} nodes List of nodes, [ {string|mw.user}, {string}, {string}, {string} ]
1219 * @return {string} Selected gender form according to current language
1221 gender: function ( nodes
) {
1223 maybeUser
= nodes
[ 0 ],
1224 forms
= nodes
.slice( 1 );
1226 if ( maybeUser
=== '' ) {
1227 maybeUser
= mw
.user
;
1230 // If we are passed a mw.user-like object, check their gender.
1231 // Otherwise, assume the gender string itself was passed .
1232 if ( maybeUser
&& maybeUser
.options
instanceof mw
.Map
) {
1233 gender
= maybeUser
.options
.get( 'gender' );
1238 return this.language
.gender( gender
, forms
);
1242 * Transform parsed structure into grammar conversion.
1243 * Invoked by putting `{{grammar:form|word}}` in a message
1245 * @param {Array} nodes List of nodes [{Grammar case eg: genitive}, {string word}]
1246 * @return {string} selected grammatical form according to current language
1248 grammar: function ( nodes
) {
1249 var form
= nodes
[ 0 ],
1251 return word
&& form
&& this.language
.convertGrammar( word
, form
);
1255 * Tranform parsed structure into a int: (interface language) message include
1256 * Invoked by putting `{{int:othermessage}}` into a message
1258 * @param {Array} nodes List of nodes
1259 * @return {string} Other message
1261 'int': function ( nodes
) {
1262 var msg
= nodes
[ 0 ];
1263 return mw
.jqueryMsg
.getMessageFunction()( msg
.charAt( 0 ).toLowerCase() + msg
.slice( 1 ) );
1267 * Get localized namespace name from canonical name or namespace number.
1268 * Invoked by putting `{{ns:foo}}` into a message
1270 * @param {Array} nodes List of nodes
1271 * @return {string} Localized namespace name
1273 ns: function ( nodes
) {
1274 var ns
= $.trim( textify( nodes
[ 0 ] ) );
1275 if ( !/^\d+$/.test( ns
) ) {
1276 ns
= mw
.config
.get( 'wgNamespaceIds' )[ ns
.replace( / /g
, '_' ).toLowerCase() ];
1278 ns
= mw
.config
.get( 'wgFormattedNamespaces' )[ ns
];
1283 * Takes an unformatted number (arab, no group separators and . as decimal separator)
1284 * and outputs it in the localized digit script and formatted with decimal
1285 * separator, according to the current language.
1287 * @param {Array} nodes List of nodes
1288 * @return {number|string} Formatted number
1290 formatnum: function ( nodes
) {
1291 var isInteger
= !!nodes
[ 1 ] && nodes
[ 1 ] === 'R',
1292 number
= nodes
[ 0 ];
1294 return this.language
.convertNumber( number
, isInteger
);
1300 * @param {Array} nodes List of nodes
1301 * @return {string} The given text, all in lowercase
1303 lc: function ( nodes
) {
1304 return textify( nodes
[ 0 ] ).toLowerCase();
1310 * @param {Array} nodes List of nodes
1311 * @return {string} The given text, all in uppercase
1313 uc: function ( nodes
) {
1314 return textify( nodes
[ 0 ] ).toUpperCase();
1318 * Lowercase first letter of input, leaving the rest unchanged
1320 * @param {Array} nodes List of nodes
1321 * @return {string} The given text, with the first character in lowercase
1323 lcfirst: function ( nodes
) {
1324 var text
= textify( nodes
[ 0 ] );
1325 return text
.charAt( 0 ).toLowerCase() + text
.slice( 1 );
1329 * Uppercase first letter of input, leaving the rest unchanged
1331 * @param {Array} nodes List of nodes
1332 * @return {string} The given text, with the first character in uppercase
1334 ucfirst: function ( nodes
) {
1335 var text
= textify( nodes
[ 0 ] );
1336 return text
.charAt( 0 ).toUpperCase() + text
.slice( 1 );
1340 // Deprecated! don't rely on gM existing.
1341 // The window.gM ought not to be required - or if required, not required here.
1342 // But moving it to extensions breaks it (?!)
1343 // Need to fix plugin so it could do attributes as well, then will be okay to remove this.
1344 // @deprecated since 1.23
1345 mw
.log
.deprecate( window
, 'gM', mw
.jqueryMsg
.getMessageFunction(), 'Use mw.message( ... ).parse() instead.' );
1350 * @see mw.jqueryMsg#getPlugin
1352 $.fn
.msg
= mw
.jqueryMsg
.getPlugin();
1354 // Replace the default message parser with jqueryMsg
1355 oldParser
= mw
.Message
.prototype.parser
;
1356 mw
.Message
.prototype.parser = function () {
1357 if ( this.format
=== 'plain' || !/\{\{|[\[<>&]/.test( this.map
.get( this.key
) ) ) {
1358 // Fall back to mw.msg's simple parser
1359 return oldParser
.apply( this );
1362 if ( !this.map
.hasOwnProperty( this.format
) ) {
1363 this.map
[ this.format
] = mw
.jqueryMsg
.getMessageFunction( {
1365 // For format 'escaped', escaping part is handled by mediawiki.js
1369 return this.map
[ this.format
]( this.key
, this.parameters
);
1373 * Parse the message to DOM nodes, rather than HTML string like #parse.
1375 * This method is only available when jqueryMsg is loaded.
1379 * @member mw.Message
1382 mw
.Message
.prototype.parseDom
= ( function () {
1383 var reusableParent
= $( '<div>' );
1384 return function () {
1385 return reusableParent
.msg( this.key
, this.parameters
).contents().detach();
1389 }( mediaWiki
, jQuery
) );