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 SITENAME
: mw
.config
.get( 'wgSiteName' )
20 // Whitelist for allowed HTML elements in wikitext.
21 // Self-closing tags are not currently supported.
22 // Can be populated via setPrivateData().
23 allowedHtmlElements
: [],
24 // Key tag name, value allowed attributes for that tag.
25 // See Sanitizer::setupAttributeWhitelist
26 allowedHtmlCommonAttributes
: [
39 // Attributes allowed for specific elements.
40 // Key is element name in lower case
41 // Value is array of allowed attributes for that element
42 allowedHtmlAttributesByElement
: {},
43 messages
: mw
.messages
,
44 language
: mw
.language
,
46 // Same meaning as in mediawiki.js.
48 // Only 'text', 'parse', and 'escaped' are supported, and the
49 // actual escaping for 'escaped' is done by other code (generally
50 // through mediawiki.js).
52 // However, note that this default only
53 // applies to direct calls to jqueryMsg. The default for mediawiki.js itself
54 // is 'text', including when it uses jqueryMsg.
59 * Wrapper around jQuery append that converts all non-objects to TextNode so append will not
60 * convert what it detects as an htmlString to an element.
62 * If our own htmlEmitter jQuery object is given, its children will be unwrapped and appended to
65 * Object elements of children (jQuery, HTMLElement, TextNode, etc.) will be left as is.
68 * @param {jQuery} $parent Parent node wrapped by jQuery
69 * @param {Object|string|Array} children What to append, with the same possible types as jQuery
70 * @return {jQuery} $parent
72 function appendWithoutParsing( $parent
, children
) {
75 if ( !$.isArray( children
) ) {
76 children
= [ children
];
79 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
80 if ( typeof children
[ i
] !== 'object' ) {
81 children
[ i
] = document
.createTextNode( children
[ i
] );
83 if ( children
[ i
] instanceof jQuery
&& children
[ i
].hasClass( 'mediaWiki_htmlEmitter' ) ) {
84 children
[ i
] = children
[ i
].contents();
88 return $parent
.append( children
);
92 * Decodes the main HTML entities, those encoded by mw.html.escape.
95 * @param {string} encoded Encoded string
96 * @return {string} String with those entities decoded
98 function decodePrimaryHtmlEntities( encoded
) {
100 .replace( /'/g, '\'' )
101 .replace( /"/g, '"' )
102 .replace( /</g, '<' )
103 .replace( />/g, '>' )
104 .replace( /&/g, '&' );
108 * Turn input into a string.
111 * @param {string|jQuery} input
112 * @return {string} Textual value of input
114 function textify( input
) {
115 if ( input
instanceof jQuery
) {
116 input
= input
.text();
118 return String( input
);
122 * Given parser options, return a function that parses a key and replacements, returning jQuery object
124 * Try to parse a key and optional replacements, returning a jQuery object that may be a tree of jQuery nodes.
125 * If there was an error parsing, return the key and the error message (wrapped in jQuery). This should put the error right into
126 * the interface, without causing the page to halt script execution, and it hopefully should be clearer how to fix it.
129 * @param {Object} options Parser options
131 * @return {Array} return.args First element is the key, replacements may be in array in 2nd element, or remaining elements.
132 * @return {jQuery} return.return
134 function getFailableParserFn( options
) {
135 return function ( args
) {
137 parser
= new mw
.jqueryMsg
.parser( options
),
139 argsArray
= $.isArray( args
[ 1 ] ) ? args
[ 1 ] : slice
.call( args
, 1 );
141 return parser
.parse( key
, argsArray
);
143 fallback
= parser
.settings
.messages
.get( key
);
144 mw
.log
.warn( 'mediawiki.jqueryMsg: ' + key
+ ': ' + e
.message
);
145 mw
.track( 'mediawiki.jqueryMsg.error', {
147 errorMessage
: e
.message
149 return $( '<span>' ).text( fallback
);
157 * Initialize parser defaults.
159 * ResourceLoaderJqueryMsgModule calls this to provide default values from
160 * Sanitizer.php for allowed HTML elements. To override this data for individual
161 * parsers, pass the relevant options to mw.jqueryMsg.parser.
164 * @param {Object} data
166 mw
.jqueryMsg
.setParserDefaults = function ( data
) {
167 $.extend( parserDefaults
, data
);
171 * Get current parser defaults.
173 * Primarily used for the unit test. Returns a copy.
178 mw
.jqueryMsg
.getParserDefaults = function () {
179 return $.extend( {}, parserDefaults
);
183 * Returns a function suitable for use as a global, to construct strings from the message key (and optional replacements).
186 * window.gM = mediaWiki.jqueryMsg.getMessageFunction( options );
187 * $( 'p#headline' ).html( gM( 'hello-user', username ) );
189 * Like the old gM() function this returns only strings, so it destroys any bindings. If you want to preserve bindings use the
190 * jQuery plugin version instead. This is only included for backwards compatibility with gM().
192 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
193 * somefunction( a, b, c, d )
195 * somefunction( a, [b, c, d] )
197 * @param {Object} options parser options
198 * @return {Function} Function suitable for assigning to window.gM
199 * @return {string} return.key Message key.
200 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
201 * @return {string} return.return Rendered HTML.
203 mw
.jqueryMsg
.getMessageFunction = function ( options
) {
204 var failableParserFn
, format
;
206 if ( options
&& options
.format
!== undefined ) {
207 format
= options
.format
;
209 format
= parserDefaults
.format
;
213 if ( !failableParserFn
) {
214 failableParserFn
= getFailableParserFn( options
);
216 var failableResult
= failableParserFn( arguments
);
217 if ( format
=== 'text' || format
=== 'escaped' ) {
218 return failableResult
.text();
220 return failableResult
.html();
226 * Returns a jQuery plugin which parses the message in the message key, doing replacements optionally, and appends the nodes to
227 * the current selector. Bindings to passed-in jquery elements are preserved. Functions become click handlers for [$1 linktext] links.
230 * $.fn.msg = mediaWiki.jqueryMsg.getPlugin( options );
231 * var userlink = $( '<a>' ).click( function () { alert( "hello!!" ) } );
232 * $( 'p#headline' ).msg( 'hello-user', userlink );
234 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
235 * somefunction( a, b, c, d )
237 * somefunction( a, [b, c, d] )
239 * We append to 'this', which in a jQuery plugin context will be the selected elements.
241 * @param {Object} options Parser options
242 * @return {Function} Function suitable for assigning to jQuery plugin, such as jQuery#msg
243 * @return {string} return.key Message key.
244 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
245 * @return {jQuery} return.return
247 mw
.jqueryMsg
.getPlugin = function ( options
) {
248 var failableParserFn
;
251 if ( !failableParserFn
) {
252 failableParserFn
= getFailableParserFn( options
);
254 var $target
= this.empty();
255 appendWithoutParsing( $target
, failableParserFn( arguments
) );
262 * Describes an object, whose primary duty is to .parse() message keys.
266 * @param {Object} options
268 mw
.jqueryMsg
.parser = function ( options
) {
269 this.settings
= $.extend( {}, parserDefaults
, options
);
270 this.settings
.onlyCurlyBraceTransform
= ( this.settings
.format
=== 'text' || this.settings
.format
=== 'escaped' );
273 this.emitter
= new mw
.jqueryMsg
.htmlEmitter( this.settings
.language
, this.settings
.magic
);
276 mw
.jqueryMsg
.parser
.prototype = {
278 * Where the magic happens.
279 * Parses a message from the key, and swaps in replacements as necessary, wraps in jQuery
280 * If an error is thrown, returns original key, and logs the error
282 * @param {string} key Message key.
283 * @param {Array} replacements Variable replacements for $1, $2... $n
286 parse: function ( key
, replacements
) {
287 var ast
= this.getAst( key
);
288 return this.emitter
.emit( ast
, replacements
);
292 * Fetch the message string associated with a key, return parsed structure. Memoized.
293 * Note that we pass '[' + key + ']' back for a missing message here.
295 * @param {string} key
296 * @return {string|Array} string of '[key]' if message missing, simple string if possible, array of arrays if needs parsing
298 getAst: function ( key
) {
301 if ( !this.astCache
.hasOwnProperty( key
) ) {
302 wikiText
= this.settings
.messages
.get( key
);
303 if ( typeof wikiText
!== 'string' ) {
304 wikiText
= '\\[' + key
+ '\\]';
306 this.astCache
[ key
] = this.wikiTextToAst( wikiText
);
308 return this.astCache
[ key
];
312 * Parses the input wikiText into an abstract syntax tree, essentially an s-expression.
314 * CAVEAT: This does not parse all wikitext. It could be more efficient, but it's pretty good already.
315 * n.b. We want to move this functionality to the server. Nothing here is required to be on the client.
317 * @param {string} input Message string wikitext
319 * @return {Mixed} abstract syntax tree
321 wikiTextToAst: function ( input
) {
323 regularLiteral
, regularLiteralWithoutBar
, regularLiteralWithoutSpace
, regularLiteralWithSquareBrackets
,
324 doubleQuote
, singleQuote
, backslash
, anyCharacter
, asciiAlphabetLiteral
,
325 escapedOrLiteralWithoutSpace
, escapedOrLiteralWithoutBar
, escapedOrRegularLiteral
,
326 whitespace
, dollar
, digits
, htmlDoubleQuoteAttributeValue
, htmlSingleQuoteAttributeValue
,
327 htmlAttributeEquals
, openHtmlStartTag
, optionalForwardSlash
, openHtmlEndTag
, closeHtmlTag
,
328 openExtlink
, closeExtlink
, wikilinkContents
, openWikilink
, closeWikilink
, templateName
, pipe
, colon
,
329 templateContents
, openTemplate
, closeTemplate
,
330 nonWhitespaceExpression
, paramExpression
, expression
, curlyBraceTransformExpression
, result
,
331 settings
= this.settings
,
332 concat
= Array
.prototype.concat
;
334 // Indicates current position in input as we parse through it.
335 // Shared among all parsing functions below.
338 // =========================================================
339 // parsing combinators - could be a library on its own
340 // =========================================================
343 * Try parsers until one works, if none work return null
346 * @param {Function[]} ps
347 * @return {string|null}
349 function choice( ps
) {
352 for ( i
= 0; i
< ps
.length
; i
++ ) {
354 if ( result
!== null ) {
363 * Try several ps in a row, all must succeed or return null.
364 * This is the only eager one.
367 * @param {Function[]} ps
368 * @return {string|null}
370 function sequence( ps
) {
374 for ( i
= 0; i
< ps
.length
; i
++ ) {
376 if ( res
=== null ) {
386 * Run the same parser over and over until it fails.
387 * Must succeed a minimum of n times or return null.
391 * @param {Function} p
392 * @return {string|null}
394 function nOrMore( n
, p
) {
396 var originalPos
= pos
,
399 while ( parsed
!== null ) {
400 result
.push( parsed
);
403 if ( result
.length
< n
) {
412 * There is a general pattern -- parse a thing, if that worked, apply transform, otherwise return null.
414 * TODO: But using this as a combinator seems to cause problems when combined with #nOrMore().
415 * May be some scoping issue
418 * @param {Function} p
419 * @param {Function} fn
420 * @return {string|null}
422 function transform( p
, fn
) {
425 return result
=== null ? null : fn( result
);
430 * Just make parsers out of simpler JS builtin types
435 * @return {string} return.return
437 function makeStringParser( s
) {
441 if ( input
.substr( pos
, len
) === s
) {
450 * Makes a regex parser, given a RegExp object.
451 * The regex being passed in should start with a ^ to anchor it to the start
455 * @param {RegExp} regex anchored regex
456 * @return {Function} function to parse input based on the regex
458 function makeRegexParser( regex
) {
460 var matches
= input
.slice( pos
).match( regex
);
461 if ( matches
=== null ) {
464 pos
+= matches
[ 0 ].length
;
469 // ===================================================================
470 // General patterns above this line -- wikitext specific parsers below
471 // ===================================================================
473 // Parsing functions follow. All parsing functions work like this:
474 // They don't accept any arguments.
475 // Instead, they just operate non destructively on the string 'input'
476 // As they can consume parts of the string, they advance the shared variable pos,
477 // and return tokens (or whatever else they want to return).
478 // some things are defined as closures and other things as ordinary functions
479 // converting everything to a closure makes it a lot harder to debug... errors pop up
480 // but some debuggers can't tell you exactly where they come from. Also the mutually
481 // recursive functions seem not to work in all browsers then. (Tested IE6-7, Opera, Safari, FF)
482 // This may be because, to save code, memoization was removed
484 regularLiteral
= makeRegexParser( /^[^{}\[\]$<\\]/ );
485 regularLiteralWithoutBar
= makeRegexParser( /^[^{}\[\]$\\|]/ );
486 regularLiteralWithoutSpace
= makeRegexParser( /^[^{}\[\]$\s]/ );
487 regularLiteralWithSquareBrackets
= makeRegexParser( /^[^{}$\\]/ );
489 backslash
= makeStringParser( '\\' );
490 doubleQuote
= makeStringParser( '"' );
491 singleQuote
= makeStringParser( '\'' );
492 anyCharacter
= makeRegexParser( /^./ );
494 openHtmlStartTag
= makeStringParser( '<' );
495 optionalForwardSlash
= makeRegexParser( /^\/?/ );
496 openHtmlEndTag
= makeStringParser( '</' );
497 htmlAttributeEquals
= makeRegexParser( /^\s*=\s*/ );
498 closeHtmlTag
= makeRegexParser( /^\s*>/ );
500 function escapedLiteral() {
501 var result
= sequence( [
505 return result
=== null ? null : result
[ 1 ];
507 escapedOrLiteralWithoutSpace
= choice( [
509 regularLiteralWithoutSpace
511 escapedOrLiteralWithoutBar
= choice( [
513 regularLiteralWithoutBar
515 escapedOrRegularLiteral
= choice( [
519 // Used to define "literals" without spaces, in space-delimited situations
520 function literalWithoutSpace() {
521 var result
= nOrMore( 1, escapedOrLiteralWithoutSpace
)();
522 return result
=== null ? null : result
.join( '' );
524 // Used to define "literals" within template parameters. The pipe character is the parameter delimeter, so by default
525 // it is not a literal in the parameter
526 function literalWithoutBar() {
527 var result
= nOrMore( 1, escapedOrLiteralWithoutBar
)();
528 return result
=== null ? null : result
.join( '' );
532 var result
= nOrMore( 1, escapedOrRegularLiteral
)();
533 return result
=== null ? null : result
.join( '' );
536 function curlyBraceTransformExpressionLiteral() {
537 var result
= nOrMore( 1, regularLiteralWithSquareBrackets
)();
538 return result
=== null ? null : result
.join( '' );
541 asciiAlphabetLiteral
= makeRegexParser( /^[A-Za-z]+/ );
542 htmlDoubleQuoteAttributeValue
= makeRegexParser( /^[^"]*/ );
543 htmlSingleQuoteAttributeValue
= makeRegexParser( /^[^']*/ );
545 whitespace
= makeRegexParser( /^\s+/ );
546 dollar
= makeStringParser( '$' );
547 digits
= makeRegexParser( /^\d+/ );
549 function replacement() {
550 var result
= sequence( [
554 if ( result
=== null ) {
557 return [ 'REPLACE', parseInt( result
[ 1 ], 10 ) - 1 ];
559 openExtlink
= makeStringParser( '[' );
560 closeExtlink
= makeStringParser( ']' );
561 // this extlink MUST have inner contents, e.g. [foo] not allowed; [foo bar] [foo <i>bar</i>], etc. are allowed
563 var result
, parsedResult
, target
;
565 parsedResult
= sequence( [
567 nOrMore( 1, nonWhitespaceExpression
),
569 nOrMore( 1, expression
),
572 if ( parsedResult
!== null ) {
573 // When the entire link target is a single parameter, we can't use CONCAT, as we allow
574 // passing fancy parameters (like a whole jQuery object or a function) to use for the
575 // link. Check only if it's a single match, since we can either do CONCAT or not for
576 // singles with the same effect.
577 target
= parsedResult
[ 1 ].length
=== 1 ?
578 parsedResult
[ 1 ][ 0 ] :
579 [ 'CONCAT' ].concat( parsedResult
[ 1 ] );
583 [ 'CONCAT' ].concat( parsedResult
[ 3 ] )
588 openWikilink
= makeStringParser( '[[' );
589 closeWikilink
= makeStringParser( ']]' );
590 pipe
= makeStringParser( '|' );
592 function template() {
593 var result
= sequence( [
598 return result
=== null ? null : result
[ 1 ];
601 function pipedWikilink() {
602 var result
= sequence( [
603 nOrMore( 1, paramExpression
),
605 nOrMore( 1, expression
)
607 return result
=== null ? null : [
608 [ 'CONCAT' ].concat( result
[ 0 ] ),
609 [ 'CONCAT' ].concat( result
[ 2 ] )
613 function unpipedWikilink() {
614 var result
= sequence( [
615 nOrMore( 1, paramExpression
)
617 return result
=== null ? null : [
618 [ 'CONCAT' ].concat( result
[ 0 ] )
622 wikilinkContents
= choice( [
627 function wikilink() {
628 var result
, parsedResult
, parsedLinkContents
;
631 parsedResult
= sequence( [
636 if ( parsedResult
!== null ) {
637 parsedLinkContents
= parsedResult
[ 1 ];
638 result
= [ 'WIKILINK' ].concat( parsedLinkContents
);
643 // TODO: Support data- if appropriate
644 function doubleQuotedHtmlAttributeValue() {
645 var parsedResult
= sequence( [
647 htmlDoubleQuoteAttributeValue
,
650 return parsedResult
=== null ? null : parsedResult
[ 1 ];
653 function singleQuotedHtmlAttributeValue() {
654 var parsedResult
= sequence( [
656 htmlSingleQuoteAttributeValue
,
659 return parsedResult
=== null ? null : parsedResult
[ 1 ];
662 function htmlAttribute() {
663 var parsedResult
= sequence( [
665 asciiAlphabetLiteral
,
668 doubleQuotedHtmlAttributeValue
,
669 singleQuotedHtmlAttributeValue
672 return parsedResult
=== null ? null : [ parsedResult
[ 1 ], parsedResult
[ 3 ] ];
676 * Checks if HTML is allowed
678 * @param {string} startTagName HTML start tag name
679 * @param {string} endTagName HTML start tag name
680 * @param {Object} attributes array of consecutive key value pairs,
681 * with index 2 * n being a name and 2 * n + 1 the associated value
682 * @return {boolean} true if this is HTML is allowed, false otherwise
684 function isAllowedHtml( startTagName
, endTagName
, attributes
) {
685 var i
, len
, attributeName
;
687 startTagName
= startTagName
.toLowerCase();
688 endTagName
= endTagName
.toLowerCase();
689 if ( startTagName
!== endTagName
|| $.inArray( startTagName
, settings
.allowedHtmlElements
) === -1 ) {
693 for ( i
= 0, len
= attributes
.length
; i
< len
; i
+= 2 ) {
694 attributeName
= attributes
[ i
];
695 if ( $.inArray( attributeName
, settings
.allowedHtmlCommonAttributes
) === -1 &&
696 $.inArray( attributeName
, settings
.allowedHtmlAttributesByElement
[ startTagName
] || [] ) === -1 ) {
704 function htmlAttributes() {
705 var parsedResult
= nOrMore( 0, htmlAttribute
)();
706 // Un-nest attributes array due to structure of jQueryMsg operations (see emit).
707 return concat
.apply( [ 'HTMLATTRIBUTES' ], parsedResult
);
710 // Subset of allowed HTML markup.
711 // Most elements and many attributes allowed on the server are not supported yet.
713 var parsedOpenTagResult
, parsedHtmlContents
, parsedCloseTagResult
,
714 wrappedAttributes
, attributes
, startTagName
, endTagName
, startOpenTagPos
,
715 startCloseTagPos
, endOpenTagPos
, endCloseTagPos
,
718 // Break into three sequence calls. That should allow accurate reconstruction of the original HTML, and requiring an exact tag name match.
719 // 1. open through closeHtmlTag
721 // 3. openHtmlEnd through close
722 // This will allow recording the positions to reconstruct if HTML is to be treated as text.
724 startOpenTagPos
= pos
;
725 parsedOpenTagResult
= sequence( [
727 asciiAlphabetLiteral
,
729 optionalForwardSlash
,
733 if ( parsedOpenTagResult
=== null ) {
738 startTagName
= parsedOpenTagResult
[ 1 ];
740 parsedHtmlContents
= nOrMore( 0, expression
)();
742 startCloseTagPos
= pos
;
743 parsedCloseTagResult
= sequence( [
745 asciiAlphabetLiteral
,
749 if ( parsedCloseTagResult
=== null ) {
750 // Closing tag failed. Return the start tag and contents.
751 return [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
752 .concat( parsedHtmlContents
);
755 endCloseTagPos
= pos
;
756 endTagName
= parsedCloseTagResult
[ 1 ];
757 wrappedAttributes
= parsedOpenTagResult
[ 2 ];
758 attributes
= wrappedAttributes
.slice( 1 );
759 if ( isAllowedHtml( startTagName
, endTagName
, attributes
) ) {
760 result
= [ 'HTMLELEMENT', startTagName
, wrappedAttributes
]
761 .concat( parsedHtmlContents
);
763 // HTML is not allowed, so contents will remain how
764 // it was, while HTML markup at this level will be
766 // E.g. assuming script tags are not allowed:
768 // <script>[[Foo|bar]]</script>
770 // results in '<script>' and '</script>'
771 // (not treated as an HTML tag), surrounding a fully
774 // Concatenate everything from the tag, flattening the contents.
775 result
= [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
776 .concat( parsedHtmlContents
, input
.slice( startCloseTagPos
, endCloseTagPos
) );
782 // <nowiki>...</nowiki> tag. The tags are stripped and the contents are returned unparsed.
784 var parsedResult
, plainText
,
787 parsedResult
= sequence( [
788 makeStringParser( '<nowiki>' ),
789 // We use a greedy non-backtracking parser, so we must ensure here that we don't take too much
790 makeRegexParser( /^.*?(?=<\/nowiki>)/ ),
791 makeStringParser( '</nowiki>' )
793 if ( parsedResult
!== null ) {
794 plainText
= parsedResult
[ 1 ];
795 result
= [ 'CONCAT' ].concat( plainText
);
801 templateName
= transform(
802 // see $wgLegalTitleChars
803 // not allowing : due to the need to catch "PLURAL:$1"
804 makeRegexParser( /^[ !"$&'()*,.\/0-9;=?@A-Z\^_`a-z~\x80-\xFF+\-]+/ ),
805 function ( result
) { return result
.toString(); }
807 function templateParam() {
811 nOrMore( 0, paramExpression
)
813 if ( result
=== null ) {
817 // use a CONCAT operator if there are multiple nodes, otherwise return the first node, raw.
818 return expr
.length
> 1 ? [ 'CONCAT' ].concat( expr
) : expr
[ 0 ];
821 function templateWithReplacement() {
822 var result
= sequence( [
827 return result
=== null ? null : [ result
[ 0 ], result
[ 2 ] ];
829 function templateWithOutReplacement() {
830 var result
= sequence( [
835 return result
=== null ? null : [ result
[ 0 ], result
[ 2 ] ];
837 function templateWithOutFirstParameter() {
838 var result
= sequence( [
842 return result
=== null ? null : [ result
[ 0 ], '' ];
844 colon
= makeStringParser( ':' );
845 templateContents
= choice( [
847 var res
= sequence( [
848 // templates can have placeholders for dynamic replacement eg: {{PLURAL:$1|one car|$1 cars}}
849 // or no placeholders eg: {{GRAMMAR:genitive|{{SITENAME}}}
850 choice( [ templateWithReplacement
, templateWithOutReplacement
, templateWithOutFirstParameter
] ),
851 nOrMore( 0, templateParam
)
853 return res
=== null ? null : res
[ 0 ].concat( res
[ 1 ] );
856 var res
= sequence( [
858 nOrMore( 0, templateParam
)
860 if ( res
=== null ) {
863 return [ res
[ 0 ] ].concat( res
[ 1 ] );
866 openTemplate
= makeStringParser( '{{' );
867 closeTemplate
= makeStringParser( '}}' );
868 nonWhitespaceExpression
= choice( [
875 paramExpression
= choice( [
883 expression
= choice( [
893 // Used when only {{-transformation is wanted, for 'text'
894 // or 'escaped' formats
895 curlyBraceTransformExpression
= choice( [
898 curlyBraceTransformExpressionLiteral
904 * @param {Function} rootExpression root parse function
906 function start( rootExpression
) {
907 var result
= nOrMore( 0, rootExpression
)();
908 if ( result
=== null ) {
911 return [ 'CONCAT' ].concat( result
);
913 // everything above this point is supposed to be stateless/static, but
914 // I am deferring the work of turning it into prototypes & objects. It's quite fast enough
915 // finally let's do some actual work...
917 result
= start( this.settings
.onlyCurlyBraceTransform
? curlyBraceTransformExpression
: expression
);
920 * For success, the p must have gotten to the end of the input
921 * and returned a non-null.
922 * n.b. This is part of language infrastructure, so we do not throw an internationalizable message.
924 if ( result
=== null || pos
!== input
.length
) {
925 throw new Error( 'Parse error at position ' + pos
.toString() + ' in input: ' + input
);
933 * htmlEmitter - object which primarily exists to emit HTML from parser ASTs
935 mw
.jqueryMsg
.htmlEmitter = function ( language
, magic
) {
936 this.language
= language
;
938 $.each( magic
, function ( key
, val
) {
939 jmsg
[ key
.toLowerCase() ] = function () {
945 * (We put this method definition here, and not in prototype, to make sure it's not overwritten by any magic.)
946 * Walk entire node structure, applying replacements and template functions when appropriate
948 * @param {Mixed} node Abstract syntax tree (top node or subnode)
949 * @param {Array} replacements for $1, $2, ... $n
950 * @return {Mixed} single-string node or array of nodes suitable for jQuery appending
952 this.emit = function ( node
, replacements
) {
953 var ret
, subnodes
, operation
,
955 switch ( typeof node
) {
960 // typeof returns object for arrays
962 // node is an array of nodes
963 subnodes
= $.map( node
.slice( 1 ), function ( n
) {
964 return jmsg
.emit( n
, replacements
);
966 operation
= node
[ 0 ].toLowerCase();
967 if ( typeof jmsg
[ operation
] === 'function' ) {
968 ret
= jmsg
[ operation
]( subnodes
, replacements
);
970 throw new Error( 'Unknown operation "' + operation
+ '"' );
974 // Parsing the empty string (as an entire expression, or as a paramExpression in a template) results in undefined
975 // Perhaps a more clever parser can detect this, and return the empty string? Or is that useful information?
976 // The logical thing is probably to return the empty string here when we encounter undefined.
980 throw new Error( 'Unexpected type in AST: ' + typeof node
);
986 // For everything in input that follows double-open-curly braces, there should be an equivalent parser
987 // function. For instance {{PLURAL ... }} will be processed by 'plural'.
988 // If you have 'magic words' then configure the parser to have them upon creation.
990 // An emitter method takes the parent node, the array of subnodes and the array of replacements (the values that $1, $2... should translate to).
991 // Note: all such functions must be pure, with the exception of referring to other pure functions via this.language (convertPlural and so on)
992 mw
.jqueryMsg
.htmlEmitter
.prototype = {
994 * Parsing has been applied depth-first we can assume that all nodes here are single nodes
995 * Must return a single node to parents -- a jQuery with synthetic span
996 * However, unwrap any other synthetic spans in our children and pass them upwards
998 * @param {Mixed[]} nodes Some single nodes, some arrays of nodes
1001 concat: function ( nodes
) {
1002 var $span
= $( '<span>' ).addClass( 'mediaWiki_htmlEmitter' );
1003 $.each( nodes
, function ( i
, node
) {
1004 // Let jQuery append nodes, arrays of nodes and jQuery objects
1005 // other things (strings, numbers, ..) are appended as text nodes (not as HTML strings)
1006 appendWithoutParsing( $span
, node
);
1012 * Return escaped replacement of correct index, or string if unavailable.
1013 * Note that we expect the parsed parameter to be zero-based. i.e. $1 should have become [ 0 ].
1014 * if the specified parameter is not found return the same string
1015 * (e.g. "$99" -> parameter 98 -> not found -> return "$99" )
1017 * TODO: Throw error if nodes.length > 1 ?
1019 * @param {Array} nodes List of one element, integer, n >= 0
1020 * @param {Array} replacements List of at least n strings
1021 * @return {string} replacement
1023 replace: function ( nodes
, replacements
) {
1024 var index
= parseInt( nodes
[ 0 ], 10 );
1026 if ( index
< replacements
.length
) {
1027 return replacements
[ index
];
1029 // index not found, fallback to displaying variable
1030 return '$' + ( index
+ 1 );
1035 * Transform wiki-link
1038 * It only handles basic cases, either no pipe, or a pipe with an explicit
1041 * It does not attempt to handle features like the pipe trick.
1042 * However, the pipe trick should usually not be present in wikitext retrieved
1043 * from the server, since the replacement is done at save time.
1044 * It may, though, if the wikitext appears in extension-controlled content.
1046 * @param {string[]} nodes
1048 wikilink: function ( nodes
) {
1049 var page
, anchor
, url
, $el
;
1051 page
= textify( nodes
[ 0 ] );
1052 // Strip leading ':', which is used to suppress special behavior in wikitext links,
1053 // e.g. [[:Category:Foo]] or [[:File:Foo.jpg]]
1054 if ( page
.charAt( 0 ) === ':' ) {
1055 page
= page
.slice( 1 );
1057 url
= mw
.util
.getUrl( page
);
1059 if ( nodes
.length
=== 1 ) {
1060 // [[Some Page]] or [[Namespace:Some Page]]
1063 // [[Some Page|anchor text]] or [[Namespace:Some Page|anchor]]
1064 anchor
= nodes
[ 1 ];
1067 $el
= $( '<a>' ).attr( {
1071 return appendWithoutParsing( $el
, anchor
);
1075 * Converts array of HTML element key value pairs to object
1077 * @param {Array} nodes Array of consecutive key value pairs, with index 2 * n being a
1078 * name and 2 * n + 1 the associated value
1079 * @return {Object} Object mapping attribute name to attribute value
1081 htmlattributes: function ( nodes
) {
1082 var i
, len
, mapping
= {};
1083 for ( i
= 0, len
= nodes
.length
; i
< len
; i
+= 2 ) {
1084 mapping
[ nodes
[ i
] ] = decodePrimaryHtmlEntities( nodes
[ i
+ 1 ] );
1090 * Handles an (already-validated) HTML element.
1092 * @param {Array} nodes Nodes to process when creating element
1093 * @return {jQuery|Array} jQuery node for valid HTML or array for disallowed element
1095 htmlelement: function ( nodes
) {
1096 var tagName
, attributes
, contents
, $element
;
1098 tagName
= nodes
.shift();
1099 attributes
= nodes
.shift();
1101 $element
= $( document
.createElement( tagName
) ).attr( attributes
);
1102 return appendWithoutParsing( $element
, contents
);
1106 * Transform parsed structure into external link.
1108 * The "href" can be:
1109 * - a jQuery object, treat it as "enclosing" the link text.
1110 * - a function, treat it as the click handler.
1111 * - a string, or our htmlEmitter jQuery object, treat it as a URI after stringifying.
1113 * TODO: throw an error if nodes.length > 2 ?
1115 * @param {Array} nodes List of two elements, {jQuery|Function|String} and {string}
1118 extlink: function ( nodes
) {
1121 contents
= nodes
[ 1 ];
1122 if ( arg
instanceof jQuery
&& !arg
.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1126 if ( typeof arg
=== 'function' ) {
1127 $el
.attr( 'href', '#' )
1128 .click( function ( e
) {
1133 $el
.attr( 'href', textify( arg
) );
1136 return appendWithoutParsing( $el
.empty(), contents
);
1140 * Transform parsed structure into pluralization
1141 * n.b. The first node may be a non-integer (for instance, a string representing an Arabic number).
1142 * So convert it back with the current language's convertNumber.
1144 * @param {Array} nodes List of nodes, [ {string|number}, {string}, {string} ... ]
1145 * @return {string} selected pluralized form according to current language
1147 plural: function ( nodes
) {
1148 var forms
, firstChild
, firstChildText
, explicitPluralFormNumber
, formIndex
, form
, count
,
1149 explicitPluralForms
= {};
1151 count
= parseFloat( this.language
.convertNumber( nodes
[ 0 ], true ) );
1152 forms
= nodes
.slice( 1 );
1153 for ( formIndex
= 0; formIndex
< forms
.length
; formIndex
++ ) {
1154 form
= forms
[ formIndex
];
1156 if ( form
instanceof jQuery
&& form
.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1157 // This is a nested node, may be an explicit plural form like 5=[$2 linktext]
1158 firstChild
= form
.contents().get( 0 );
1159 if ( firstChild
&& firstChild
.nodeType
=== Node
.TEXT_NODE
) {
1160 firstChildText
= firstChild
.textContent
;
1161 if ( /^\d+=/.test( firstChildText
) ) {
1162 explicitPluralFormNumber
= parseInt( firstChildText
.split( /=/ )[ 0 ], 10 );
1163 // Use the digit part as key and rest of first text node and
1164 // rest of child nodes as value.
1165 firstChild
.textContent
= firstChildText
.slice( firstChildText
.indexOf( '=' ) + 1 );
1166 explicitPluralForms
[ explicitPluralFormNumber
] = form
;
1167 forms
[ formIndex
] = undefined;
1170 } else if ( /^\d+=/.test( form
) ) {
1171 // Simple explicit plural forms like 12=a dozen
1172 explicitPluralFormNumber
= parseInt( form
.split( /=/ )[ 0 ], 10 );
1173 explicitPluralForms
[ explicitPluralFormNumber
] = form
.slice( form
.indexOf( '=' ) + 1 );
1174 forms
[ formIndex
] = undefined;
1178 // Remove explicit plural forms from the forms. They were set undefined in the above loop.
1179 forms
= $.map( forms
, function ( form
) {
1183 return this.language
.convertPlural( count
, forms
, explicitPluralForms
);
1187 * Transform parsed structure according to gender.
1189 * Usage: {{gender:[ mw.user object | '' | 'male' | 'female' | 'unknown' ] | masculine form | feminine form | neutral form}}.
1191 * The first node must be one of:
1192 * - the mw.user object (or a compatible one)
1193 * - an empty string - indicating the current user, same effect as passing the mw.user object
1194 * - a gender string ('male', 'female' or 'unknown')
1196 * @param {Array} nodes List of nodes, [ {string|mw.user}, {string}, {string}, {string} ]
1197 * @return {string} Selected gender form according to current language
1199 gender: function ( nodes
) {
1201 maybeUser
= nodes
[ 0 ],
1202 forms
= nodes
.slice( 1 );
1204 if ( maybeUser
=== '' ) {
1205 maybeUser
= mw
.user
;
1208 // If we are passed a mw.user-like object, check their gender.
1209 // Otherwise, assume the gender string itself was passed .
1210 if ( maybeUser
&& maybeUser
.options
instanceof mw
.Map
) {
1211 gender
= maybeUser
.options
.get( 'gender' );
1216 return this.language
.gender( gender
, forms
);
1220 * Transform parsed structure into grammar conversion.
1221 * Invoked by putting `{{grammar:form|word}}` in a message
1223 * @param {Array} nodes List of nodes [{Grammar case eg: genitive}, {string word}]
1224 * @return {string} selected grammatical form according to current language
1226 grammar: function ( nodes
) {
1227 var form
= nodes
[ 0 ],
1229 return word
&& form
&& this.language
.convertGrammar( word
, form
);
1233 * Tranform parsed structure into a int: (interface language) message include
1234 * Invoked by putting `{{int:othermessage}}` into a message
1236 * @param {Array} nodes List of nodes
1237 * @return {string} Other message
1239 'int': function ( nodes
) {
1240 var msg
= nodes
[ 0 ];
1241 return mw
.jqueryMsg
.getMessageFunction()( msg
.charAt( 0 ).toLowerCase() + msg
.slice( 1 ) );
1245 * Get localized namespace name from canonical name or namespace number.
1246 * Invoked by putting `{{ns:foo}}` into a message
1248 * @param {Array} nodes List of nodes
1249 * @return {string} Localized namespace name
1251 ns: function ( nodes
) {
1252 var ns
= $.trim( textify( nodes
[ 0 ] ) );
1253 if ( !/^\d+$/.test( ns
) ) {
1254 ns
= mw
.config
.get( 'wgNamespaceIds' )[ ns
.replace( / /g
, '_' ).toLowerCase() ];
1256 ns
= mw
.config
.get( 'wgFormattedNamespaces' )[ ns
];
1261 * Takes an unformatted number (arab, no group separators and . as decimal separator)
1262 * and outputs it in the localized digit script and formatted with decimal
1263 * separator, according to the current language.
1265 * @param {Array} nodes List of nodes
1266 * @return {number|string} Formatted number
1268 formatnum: function ( nodes
) {
1269 var isInteger
= ( nodes
[ 1 ] && nodes
[ 1 ] === 'R' ) ? true : false,
1270 number
= nodes
[ 0 ];
1272 return this.language
.convertNumber( number
, isInteger
);
1278 * @param {Array} nodes List of nodes
1279 * @return {string} The given text, all in lowercase
1281 lc: function ( nodes
) {
1282 return textify( nodes
[ 0 ] ).toLowerCase();
1288 * @param {Array} nodes List of nodes
1289 * @return {string} The given text, all in uppercase
1291 uc: function ( nodes
) {
1292 return textify( nodes
[ 0 ] ).toUpperCase();
1296 * Lowercase first letter of input, leaving the rest unchanged
1298 * @param {Array} nodes List of nodes
1299 * @return {string} The given text, with the first character in lowercase
1301 lcfirst: function ( nodes
) {
1302 var text
= textify( nodes
[ 0 ] );
1303 return text
.charAt( 0 ).toLowerCase() + text
.slice( 1 );
1307 * Uppercase first letter of input, leaving the rest unchanged
1309 * @param {Array} nodes List of nodes
1310 * @return {string} The given text, with the first character in uppercase
1312 ucfirst: function ( nodes
) {
1313 var text
= textify( nodes
[ 0 ] );
1314 return text
.charAt( 0 ).toUpperCase() + text
.slice( 1 );
1318 // Deprecated! don't rely on gM existing.
1319 // The window.gM ought not to be required - or if required, not required here.
1320 // But moving it to extensions breaks it (?!)
1321 // Need to fix plugin so it could do attributes as well, then will be okay to remove this.
1322 // @deprecated since 1.23
1323 mw
.log
.deprecate( window
, 'gM', mw
.jqueryMsg
.getMessageFunction(), 'Use mw.message( ... ).parse() instead.' );
1328 * @see mw.jqueryMsg#getPlugin
1330 $.fn
.msg
= mw
.jqueryMsg
.getPlugin();
1332 // Replace the default message parser with jqueryMsg
1333 oldParser
= mw
.Message
.prototype.parser
;
1334 mw
.Message
.prototype.parser = function () {
1335 if ( this.format
=== 'plain' || !/\{\{|[\[<>&]/.test( this.map
.get( this.key
) ) ) {
1336 // Fall back to mw.msg's simple parser
1337 return oldParser
.apply( this );
1340 if ( !this.map
.hasOwnProperty( this.format
) ) {
1341 this.map
[ this.format
] = mw
.jqueryMsg
.getMessageFunction( {
1343 // For format 'escaped', escaping part is handled by mediawiki.js
1347 return this.map
[ this.format
]( this.key
, this.parameters
);
1351 * Parse the message to DOM nodes, rather than HTML string like #parse.
1353 * This method is only available when jqueryMsg is loaded.
1356 * @member mw.Message
1359 mw
.Message
.prototype.parseDom
= ( function () {
1360 var reusableParent
= $( '<div>' );
1361 return function () {
1362 return reusableParent
.msg( this.key
, this.parameters
).contents().detach();
1366 }( mediaWiki
, jQuery
) );