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.
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 var parser
= new mw
.jqueryMsg
.parser( options
);
138 return function ( args
) {
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 return $( '<span>' ).text( fallback
);
155 * Initialize parser defaults.
157 * ResourceLoaderJqueryMsgModule calls this to provide default values from
158 * Sanitizer.php for allowed HTML elements. To override this data for individual
159 * parsers, pass the relevant options to mw.jqueryMsg.parser.
162 * @param {Object} data
164 mw
.jqueryMsg
.setParserDefaults = function ( data
) {
165 if ( data
.allowedHtmlElements
) {
166 parserDefaults
.allowedHtmlElements
= data
.allowedHtmlElements
;
171 * Returns a function suitable for use as a global, to construct strings from the message key (and optional replacements).
174 * window.gM = mediaWiki.jqueryMsg.getMessageFunction( options );
175 * $( 'p#headline' ).html( gM( 'hello-user', username ) );
177 * Like the old gM() function this returns only strings, so it destroys any bindings. If you want to preserve bindings use the
178 * jQuery plugin version instead. This is only included for backwards compatibility with gM().
180 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
181 * somefunction( a, b, c, d )
183 * somefunction( a, [b, c, d] )
185 * @param {Object} options parser options
186 * @return {Function} Function suitable for assigning to window.gM
187 * @return {string} return.key Message key.
188 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
189 * @return {string} return.return Rendered HTML.
191 mw
.jqueryMsg
.getMessageFunction = function ( options
) {
192 var failableParserFn
= getFailableParserFn( options
),
195 if ( options
&& options
.format
!== undefined ) {
196 format
= options
.format
;
198 format
= parserDefaults
.format
;
202 var failableResult
= failableParserFn( arguments
);
203 if ( format
=== 'text' || format
=== 'escaped' ) {
204 return failableResult
.text();
206 return failableResult
.html();
212 * Returns a jQuery plugin which parses the message in the message key, doing replacements optionally, and appends the nodes to
213 * the current selector. Bindings to passed-in jquery elements are preserved. Functions become click handlers for [$1 linktext] links.
216 * $.fn.msg = mediaWiki.jqueryMsg.getPlugin( options );
217 * var userlink = $( '<a>' ).click( function () { alert( "hello!!" ) } );
218 * $( 'p#headline' ).msg( 'hello-user', userlink );
220 * N.B. replacements are variadic arguments or an array in second parameter. In other words:
221 * somefunction( a, b, c, d )
223 * somefunction( a, [b, c, d] )
225 * We append to 'this', which in a jQuery plugin context will be the selected elements.
227 * @param {Object} options Parser options
228 * @return {Function} Function suitable for assigning to jQuery plugin, such as jQuery#msg
229 * @return {string} return.key Message key.
230 * @return {Array|Mixed} return.replacements Optional variable replacements (variadically or an array).
231 * @return {jQuery} return.return
233 mw
.jqueryMsg
.getPlugin = function ( options
) {
234 var failableParserFn
= getFailableParserFn( options
);
237 var $target
= this.empty();
238 appendWithoutParsing( $target
, failableParserFn( arguments
) );
245 * Describes an object, whose primary duty is to .parse() message keys.
249 * @param {Object} options
251 mw
.jqueryMsg
.parser = function ( options
) {
252 this.settings
= $.extend( {}, parserDefaults
, options
);
253 this.settings
.onlyCurlyBraceTransform
= ( this.settings
.format
=== 'text' || this.settings
.format
=== 'escaped' );
255 this.emitter
= new mw
.jqueryMsg
.htmlEmitter( this.settings
.language
, this.settings
.magic
);
258 mw
.jqueryMsg
.parser
.prototype = {
260 * Cache mapping MediaWiki message keys and the value onlyCurlyBraceTransform, to the AST of the message.
262 * In most cases, the message is a string so this is identical.
263 * (This is why we would like to move this functionality server-side).
265 * The two parts of the key are separated by colon. For example:
267 * "message-key:true": ast
269 * if they key is "message-key" and onlyCurlyBraceTransform is true.
271 * This cache is shared by all instances of mw.jqueryMsg.parser.
273 * NOTE: We promise, it's static - when you create this empty object
274 * in the prototype, each new instance of the class gets a reference
275 * to the same object.
283 * Where the magic happens.
284 * Parses a message from the key, and swaps in replacements as necessary, wraps in jQuery
285 * If an error is thrown, returns original key, and logs the error
287 * @param {string} key Message key.
288 * @param {Array} replacements Variable replacements for $1, $2... $n
291 parse: function ( key
, replacements
) {
292 return this.emitter
.emit( this.getAst( key
), replacements
);
296 * Fetch the message string associated with a key, return parsed structure. Memoized.
297 * Note that we pass '[' + key + ']' back for a missing message here.
299 * @param {string} key
300 * @return {string|Array} string of '[key]' if message missing, simple string if possible, array of arrays if needs parsing
302 getAst: function ( key
) {
304 cacheKey
= [ key
, this.settings
.onlyCurlyBraceTransform
].join( ':' );
306 if ( this.astCache
[ cacheKey
] === undefined ) {
307 wikiText
= this.settings
.messages
.get( key
);
308 if ( typeof wikiText
!== 'string' ) {
309 wikiText
= '\\[' + key
+ '\\]';
311 this.astCache
[ cacheKey
] = this.wikiTextToAst( wikiText
);
313 return this.astCache
[ cacheKey
];
317 * Parses the input wikiText into an abstract syntax tree, essentially an s-expression.
319 * CAVEAT: This does not parse all wikitext. It could be more efficient, but it's pretty good already.
320 * n.b. We want to move this functionality to the server. Nothing here is required to be on the client.
322 * @param {string} input Message string wikitext
324 * @return {Mixed} abstract syntax tree
326 wikiTextToAst: function ( input
) {
328 regularLiteral
, regularLiteralWithoutBar
, regularLiteralWithoutSpace
, regularLiteralWithSquareBrackets
,
329 doubleQuote
, singleQuote
, backslash
, anyCharacter
, asciiAlphabetLiteral
,
330 escapedOrLiteralWithoutSpace
, escapedOrLiteralWithoutBar
, escapedOrRegularLiteral
,
331 whitespace
, dollar
, digits
, htmlDoubleQuoteAttributeValue
, htmlSingleQuoteAttributeValue
,
332 htmlAttributeEquals
, openHtmlStartTag
, optionalForwardSlash
, openHtmlEndTag
, closeHtmlTag
,
333 openExtlink
, closeExtlink
, wikilinkContents
, openWikilink
, closeWikilink
, templateName
, pipe
, colon
,
334 templateContents
, openTemplate
, closeTemplate
,
335 nonWhitespaceExpression
, paramExpression
, expression
, curlyBraceTransformExpression
, result
,
336 settings
= this.settings
,
337 concat
= Array
.prototype.concat
;
339 // Indicates current position in input as we parse through it.
340 // Shared among all parsing functions below.
343 // =========================================================
344 // parsing combinators - could be a library on its own
345 // =========================================================
348 * Try parsers until one works, if none work return null
351 * @param {Function[]} ps
352 * @return {string|null}
354 function choice( ps
) {
357 for ( i
= 0; i
< ps
.length
; i
++ ) {
359 if ( result
!== null ) {
368 * Try several ps in a row, all must succeed or return null.
369 * This is the only eager one.
372 * @param {Function[]} ps
373 * @return {string|null}
375 function sequence( ps
) {
379 for ( i
= 0; i
< ps
.length
; i
++ ) {
381 if ( res
=== null ) {
391 * Run the same parser over and over until it fails.
392 * Must succeed a minimum of n times or return null.
396 * @param {Function} p
397 * @return {string|null}
399 function nOrMore( n
, p
) {
401 var originalPos
= pos
,
404 while ( parsed
!== null ) {
405 result
.push( parsed
);
408 if ( result
.length
< n
) {
417 * There is a general pattern -- parse a thing, if that worked, apply transform, otherwise return null.
419 * TODO: But using this as a combinator seems to cause problems when combined with #nOrMore().
420 * May be some scoping issue
423 * @param {Function} p
424 * @param {Function} fn
425 * @return {string|null}
427 function transform( p
, fn
) {
430 return result
=== null ? null : fn( result
);
435 * Just make parsers out of simpler JS builtin types
440 * @return {string} return.return
442 function makeStringParser( s
) {
446 if ( input
.substr( pos
, len
) === s
) {
455 * Makes a regex parser, given a RegExp object.
456 * The regex being passed in should start with a ^ to anchor it to the start
460 * @param {RegExp} regex anchored regex
461 * @return {Function} function to parse input based on the regex
463 function makeRegexParser( regex
) {
465 var matches
= input
.slice( pos
).match( regex
);
466 if ( matches
=== null ) {
469 pos
+= matches
[ 0 ].length
;
474 // ===================================================================
475 // General patterns above this line -- wikitext specific parsers below
476 // ===================================================================
478 // Parsing functions follow. All parsing functions work like this:
479 // They don't accept any arguments.
480 // Instead, they just operate non destructively on the string 'input'
481 // As they can consume parts of the string, they advance the shared variable pos,
482 // and return tokens (or whatever else they want to return).
483 // some things are defined as closures and other things as ordinary functions
484 // converting everything to a closure makes it a lot harder to debug... errors pop up
485 // but some debuggers can't tell you exactly where they come from. Also the mutually
486 // recursive functions seem not to work in all browsers then. (Tested IE6-7, Opera, Safari, FF)
487 // This may be because, to save code, memoization was removed
489 regularLiteral
= makeRegexParser( /^[^{}\[\]$<\\]/ );
490 regularLiteralWithoutBar
= makeRegexParser( /^[^{}\[\]$\\|]/ );
491 regularLiteralWithoutSpace
= makeRegexParser( /^[^{}\[\]$\s]/ );
492 regularLiteralWithSquareBrackets
= makeRegexParser( /^[^{}$\\]/ );
494 backslash
= makeStringParser( '\\' );
495 doubleQuote
= makeStringParser( '"' );
496 singleQuote
= makeStringParser( '\'' );
497 anyCharacter
= makeRegexParser( /^./ );
499 openHtmlStartTag
= makeStringParser( '<' );
500 optionalForwardSlash
= makeRegexParser( /^\/?/ );
501 openHtmlEndTag
= makeStringParser( '</' );
502 htmlAttributeEquals
= makeRegexParser( /^\s*=\s*/ );
503 closeHtmlTag
= makeRegexParser( /^\s*>/ );
505 function escapedLiteral() {
506 var result
= sequence( [
510 return result
=== null ? null : result
[ 1 ];
512 escapedOrLiteralWithoutSpace
= choice( [
514 regularLiteralWithoutSpace
516 escapedOrLiteralWithoutBar
= choice( [
518 regularLiteralWithoutBar
520 escapedOrRegularLiteral
= choice( [
524 // Used to define "literals" without spaces, in space-delimited situations
525 function literalWithoutSpace() {
526 var result
= nOrMore( 1, escapedOrLiteralWithoutSpace
)();
527 return result
=== null ? null : result
.join( '' );
529 // Used to define "literals" within template parameters. The pipe character is the parameter delimeter, so by default
530 // it is not a literal in the parameter
531 function literalWithoutBar() {
532 var result
= nOrMore( 1, escapedOrLiteralWithoutBar
)();
533 return result
=== null ? null : result
.join( '' );
537 var result
= nOrMore( 1, escapedOrRegularLiteral
)();
538 return result
=== null ? null : result
.join( '' );
541 function curlyBraceTransformExpressionLiteral() {
542 var result
= nOrMore( 1, regularLiteralWithSquareBrackets
)();
543 return result
=== null ? null : result
.join( '' );
546 asciiAlphabetLiteral
= makeRegexParser( /[A-Za-z]+/ );
547 htmlDoubleQuoteAttributeValue
= makeRegexParser( /^[^"]*/ );
548 htmlSingleQuoteAttributeValue
= makeRegexParser( /^[^']*/ );
550 whitespace
= makeRegexParser( /^\s+/ );
551 dollar
= makeStringParser( '$' );
552 digits
= makeRegexParser( /^\d+/ );
554 function replacement() {
555 var result
= sequence( [
559 if ( result
=== null ) {
562 return [ 'REPLACE', parseInt( result
[ 1 ], 10 ) - 1 ];
564 openExtlink
= makeStringParser( '[' );
565 closeExtlink
= makeStringParser( ']' );
566 // this extlink MUST have inner contents, e.g. [foo] not allowed; [foo bar] [foo <i>bar</i>], etc. are allowed
568 var result
, parsedResult
, target
;
570 parsedResult
= sequence( [
572 nOrMore( 1, nonWhitespaceExpression
),
574 nOrMore( 1, expression
),
577 if ( parsedResult
!== null ) {
578 // When the entire link target is a single parameter, we can't use CONCAT, as we allow
579 // passing fancy parameters (like a whole jQuery object or a function) to use for the
580 // link. Check only if it's a single match, since we can either do CONCAT or not for
581 // singles with the same effect.
582 target
= parsedResult
[ 1 ].length
=== 1 ?
583 parsedResult
[ 1 ][ 0 ] :
584 [ 'CONCAT' ].concat( parsedResult
[ 1 ] );
588 [ 'CONCAT' ].concat( parsedResult
[ 3 ] )
593 openWikilink
= makeStringParser( '[[' );
594 closeWikilink
= makeStringParser( ']]' );
595 pipe
= makeStringParser( '|' );
597 function template() {
598 var result
= sequence( [
603 return result
=== null ? null : result
[ 1 ];
606 function pipedWikilink() {
607 var result
= sequence( [
608 nOrMore( 1, paramExpression
),
610 nOrMore( 1, expression
)
612 return result
=== null ? null : [
613 [ 'CONCAT' ].concat( result
[ 0 ] ),
614 [ 'CONCAT' ].concat( result
[ 2 ] )
618 function unpipedWikilink() {
619 var result
= sequence( [
620 nOrMore( 1, paramExpression
)
622 return result
=== null ? null : [
623 [ 'CONCAT' ].concat( result
[ 0 ] )
627 wikilinkContents
= choice( [
632 function wikilink() {
633 var result
, parsedResult
, parsedLinkContents
;
636 parsedResult
= sequence( [
641 if ( parsedResult
!== null ) {
642 parsedLinkContents
= parsedResult
[ 1 ];
643 result
= [ 'WIKILINK' ].concat( parsedLinkContents
);
648 // TODO: Support data- if appropriate
649 function doubleQuotedHtmlAttributeValue() {
650 var parsedResult
= sequence( [
652 htmlDoubleQuoteAttributeValue
,
655 return parsedResult
=== null ? null : parsedResult
[ 1 ];
658 function singleQuotedHtmlAttributeValue() {
659 var parsedResult
= sequence( [
661 htmlSingleQuoteAttributeValue
,
664 return parsedResult
=== null ? null : parsedResult
[ 1 ];
667 function htmlAttribute() {
668 var parsedResult
= sequence( [
670 asciiAlphabetLiteral
,
673 doubleQuotedHtmlAttributeValue
,
674 singleQuotedHtmlAttributeValue
677 return parsedResult
=== null ? null : [ parsedResult
[ 1 ], parsedResult
[ 3 ] ];
681 * Checks if HTML is allowed
683 * @param {string} startTagName HTML start tag name
684 * @param {string} endTagName HTML start tag name
685 * @param {Object} attributes array of consecutive key value pairs,
686 * with index 2 * n being a name and 2 * n + 1 the associated value
687 * @return {boolean} true if this is HTML is allowed, false otherwise
689 function isAllowedHtml( startTagName
, endTagName
, attributes
) {
690 var i
, len
, attributeName
;
692 startTagName
= startTagName
.toLowerCase();
693 endTagName
= endTagName
.toLowerCase();
694 if ( startTagName
!== endTagName
|| $.inArray( startTagName
, settings
.allowedHtmlElements
) === -1 ) {
698 for ( i
= 0, len
= attributes
.length
; i
< len
; i
+= 2 ) {
699 attributeName
= attributes
[ i
];
700 if ( $.inArray( attributeName
, settings
.allowedHtmlCommonAttributes
) === -1 &&
701 $.inArray( attributeName
, settings
.allowedHtmlAttributesByElement
[ startTagName
] || [] ) === -1 ) {
709 function htmlAttributes() {
710 var parsedResult
= nOrMore( 0, htmlAttribute
)();
711 // Un-nest attributes array due to structure of jQueryMsg operations (see emit).
712 return concat
.apply( [ 'HTMLATTRIBUTES' ], parsedResult
);
715 // Subset of allowed HTML markup.
716 // Most elements and many attributes allowed on the server are not supported yet.
718 var parsedOpenTagResult
, parsedHtmlContents
, parsedCloseTagResult
,
719 wrappedAttributes
, attributes
, startTagName
, endTagName
, startOpenTagPos
,
720 startCloseTagPos
, endOpenTagPos
, endCloseTagPos
,
723 // Break into three sequence calls. That should allow accurate reconstruction of the original HTML, and requiring an exact tag name match.
724 // 1. open through closeHtmlTag
726 // 3. openHtmlEnd through close
727 // This will allow recording the positions to reconstruct if HTML is to be treated as text.
729 startOpenTagPos
= pos
;
730 parsedOpenTagResult
= sequence( [
732 asciiAlphabetLiteral
,
734 optionalForwardSlash
,
738 if ( parsedOpenTagResult
=== null ) {
743 startTagName
= parsedOpenTagResult
[ 1 ];
745 parsedHtmlContents
= nOrMore( 0, expression
)();
747 startCloseTagPos
= pos
;
748 parsedCloseTagResult
= sequence( [
750 asciiAlphabetLiteral
,
754 if ( parsedCloseTagResult
=== null ) {
755 // Closing tag failed. Return the start tag and contents.
756 return [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
757 .concat( parsedHtmlContents
);
760 endCloseTagPos
= pos
;
761 endTagName
= parsedCloseTagResult
[ 1 ];
762 wrappedAttributes
= parsedOpenTagResult
[ 2 ];
763 attributes
= wrappedAttributes
.slice( 1 );
764 if ( isAllowedHtml( startTagName
, endTagName
, attributes
) ) {
765 result
= [ 'HTMLELEMENT', startTagName
, wrappedAttributes
]
766 .concat( parsedHtmlContents
);
768 // HTML is not allowed, so contents will remain how
769 // it was, while HTML markup at this level will be
771 // E.g. assuming script tags are not allowed:
773 // <script>[[Foo|bar]]</script>
775 // results in '<script>' and '</script>'
776 // (not treated as an HTML tag), surrounding a fully
779 // Concatenate everything from the tag, flattening the contents.
780 result
= [ 'CONCAT', input
.slice( startOpenTagPos
, endOpenTagPos
) ]
781 .concat( parsedHtmlContents
, input
.slice( startCloseTagPos
, endCloseTagPos
) );
787 templateName
= transform(
788 // see $wgLegalTitleChars
789 // not allowing : due to the need to catch "PLURAL:$1"
790 makeRegexParser( /^[ !"$&'()*,.\/0-9;=?@A-Z\^_`a-z~\x80-\xFF+\-]+/ ),
791 function ( result
) { return result
.toString(); }
793 function templateParam() {
797 nOrMore( 0, paramExpression
)
799 if ( result
=== null ) {
803 // use a CONCAT operator if there are multiple nodes, otherwise return the first node, raw.
804 return expr
.length
> 1 ? [ 'CONCAT' ].concat( expr
) : expr
[ 0 ];
807 function templateWithReplacement() {
808 var result
= sequence( [
813 return result
=== null ? null : [ result
[ 0 ], result
[ 2 ] ];
815 function templateWithOutReplacement() {
816 var result
= sequence( [
821 return result
=== null ? null : [ result
[ 0 ], result
[ 2 ] ];
823 function templateWithOutFirstParameter() {
824 var result
= sequence( [
828 return result
=== null ? null : [ result
[ 0 ], '' ];
830 colon
= makeStringParser( ':' );
831 templateContents
= choice( [
833 var res
= sequence( [
834 // templates can have placeholders for dynamic replacement eg: {{PLURAL:$1|one car|$1 cars}}
835 // or no placeholders eg: {{GRAMMAR:genitive|{{SITENAME}}}
836 choice( [ templateWithReplacement
, templateWithOutReplacement
, templateWithOutFirstParameter
] ),
837 nOrMore( 0, templateParam
)
839 return res
=== null ? null : res
[ 0 ].concat( res
[ 1 ] );
842 var res
= sequence( [
844 nOrMore( 0, templateParam
)
846 if ( res
=== null ) {
849 return [ res
[ 0 ] ].concat( res
[ 1 ] );
852 openTemplate
= makeStringParser( '{{' );
853 closeTemplate
= makeStringParser( '}}' );
854 nonWhitespaceExpression
= choice( [
861 paramExpression
= choice( [
869 expression
= choice( [
878 // Used when only {{-transformation is wanted, for 'text'
879 // or 'escaped' formats
880 curlyBraceTransformExpression
= choice( [
883 curlyBraceTransformExpressionLiteral
889 * @param {Function} rootExpression root parse function
891 function start( rootExpression
) {
892 var result
= nOrMore( 0, rootExpression
)();
893 if ( result
=== null ) {
896 return [ 'CONCAT' ].concat( result
);
898 // everything above this point is supposed to be stateless/static, but
899 // I am deferring the work of turning it into prototypes & objects. It's quite fast enough
900 // finally let's do some actual work...
902 // If you add another possible rootExpression, you must update the astCache key scheme.
903 result
= start( this.settings
.onlyCurlyBraceTransform
? curlyBraceTransformExpression
: expression
);
906 * For success, the p must have gotten to the end of the input
907 * and returned a non-null.
908 * n.b. This is part of language infrastructure, so we do not throw an internationalizable message.
910 if ( result
=== null || pos
!== input
.length
) {
911 throw new Error( 'Parse error at position ' + pos
.toString() + ' in input: ' + input
);
919 * htmlEmitter - object which primarily exists to emit HTML from parser ASTs
921 mw
.jqueryMsg
.htmlEmitter = function ( language
, magic
) {
922 this.language
= language
;
924 $.each( magic
, function ( key
, val
) {
925 jmsg
[ key
.toLowerCase() ] = function () {
931 * (We put this method definition here, and not in prototype, to make sure it's not overwritten by any magic.)
932 * Walk entire node structure, applying replacements and template functions when appropriate
934 * @param {Mixed} node Abstract syntax tree (top node or subnode)
935 * @param {Array} replacements for $1, $2, ... $n
936 * @return {Mixed} single-string node or array of nodes suitable for jQuery appending
938 this.emit = function ( node
, replacements
) {
939 var ret
, subnodes
, operation
,
941 switch ( typeof node
) {
946 // typeof returns object for arrays
948 // node is an array of nodes
949 subnodes
= $.map( node
.slice( 1 ), function ( n
) {
950 return jmsg
.emit( n
, replacements
);
952 operation
= node
[ 0 ].toLowerCase();
953 if ( typeof jmsg
[ operation
] === 'function' ) {
954 ret
= jmsg
[ operation
]( subnodes
, replacements
);
956 throw new Error( 'Unknown operation "' + operation
+ '"' );
960 // Parsing the empty string (as an entire expression, or as a paramExpression in a template) results in undefined
961 // Perhaps a more clever parser can detect this, and return the empty string? Or is that useful information?
962 // The logical thing is probably to return the empty string here when we encounter undefined.
966 throw new Error( 'Unexpected type in AST: ' + typeof node
);
972 // For everything in input that follows double-open-curly braces, there should be an equivalent parser
973 // function. For instance {{PLURAL ... }} will be processed by 'plural'.
974 // If you have 'magic words' then configure the parser to have them upon creation.
976 // An emitter method takes the parent node, the array of subnodes and the array of replacements (the values that $1, $2... should translate to).
977 // Note: all such functions must be pure, with the exception of referring to other pure functions via this.language (convertPlural and so on)
978 mw
.jqueryMsg
.htmlEmitter
.prototype = {
980 * Parsing has been applied depth-first we can assume that all nodes here are single nodes
981 * Must return a single node to parents -- a jQuery with synthetic span
982 * However, unwrap any other synthetic spans in our children and pass them upwards
984 * @param {Mixed[]} nodes Some single nodes, some arrays of nodes
987 concat: function ( nodes
) {
988 var $span
= $( '<span>' ).addClass( 'mediaWiki_htmlEmitter' );
989 $.each( nodes
, function ( i
, node
) {
990 // Let jQuery append nodes, arrays of nodes and jQuery objects
991 // other things (strings, numbers, ..) are appended as text nodes (not as HTML strings)
992 appendWithoutParsing( $span
, node
);
998 * Return escaped replacement of correct index, or string if unavailable.
999 * Note that we expect the parsed parameter to be zero-based. i.e. $1 should have become [ 0 ].
1000 * if the specified parameter is not found return the same string
1001 * (e.g. "$99" -> parameter 98 -> not found -> return "$99" )
1003 * TODO: Throw error if nodes.length > 1 ?
1005 * @param {Array} nodes List of one element, integer, n >= 0
1006 * @param {Array} replacements List of at least n strings
1007 * @return {string} replacement
1009 replace: function ( nodes
, replacements
) {
1010 var index
= parseInt( nodes
[ 0 ], 10 );
1012 if ( index
< replacements
.length
) {
1013 return replacements
[ index
];
1015 // index not found, fallback to displaying variable
1016 return '$' + ( index
+ 1 );
1021 * Transform wiki-link
1024 * It only handles basic cases, either no pipe, or a pipe with an explicit
1027 * It does not attempt to handle features like the pipe trick.
1028 * However, the pipe trick should usually not be present in wikitext retrieved
1029 * from the server, since the replacement is done at save time.
1030 * It may, though, if the wikitext appears in extension-controlled content.
1032 * @param {string[]} nodes
1034 wikilink: function ( nodes
) {
1035 var page
, anchor
, url
, $el
;
1037 page
= textify( nodes
[ 0 ] );
1038 url
= mw
.util
.getUrl( page
);
1040 if ( nodes
.length
=== 1 ) {
1041 // [[Some Page]] or [[Namespace:Some Page]]
1044 // [[Some Page|anchor text]] or [[Namespace:Some Page|anchor]]
1045 anchor
= nodes
[ 1 ];
1048 $el
= $( '<a>' ).attr( {
1052 return appendWithoutParsing( $el
, anchor
);
1056 * Converts array of HTML element key value pairs to object
1058 * @param {Array} nodes Array of consecutive key value pairs, with index 2 * n being a
1059 * name and 2 * n + 1 the associated value
1060 * @return {Object} Object mapping attribute name to attribute value
1062 htmlattributes: function ( nodes
) {
1063 var i
, len
, mapping
= {};
1064 for ( i
= 0, len
= nodes
.length
; i
< len
; i
+= 2 ) {
1065 mapping
[ nodes
[ i
] ] = decodePrimaryHtmlEntities( nodes
[ i
+ 1 ] );
1071 * Handles an (already-validated) HTML element.
1073 * @param {Array} nodes Nodes to process when creating element
1074 * @return {jQuery|Array} jQuery node for valid HTML or array for disallowed element
1076 htmlelement: function ( nodes
) {
1077 var tagName
, attributes
, contents
, $element
;
1079 tagName
= nodes
.shift();
1080 attributes
= nodes
.shift();
1082 $element
= $( document
.createElement( tagName
) ).attr( attributes
);
1083 return appendWithoutParsing( $element
, contents
);
1087 * Transform parsed structure into external link.
1089 * The "href" can be:
1090 * - a jQuery object, treat it as "enclosing" the link text.
1091 * - a function, treat it as the click handler.
1092 * - a string, or our htmlEmitter jQuery object, treat it as a URI after stringifying.
1094 * TODO: throw an error if nodes.length > 2 ?
1096 * @param {Array} nodes List of two elements, {jQuery|Function|String} and {string}
1099 extlink: function ( nodes
) {
1102 contents
= nodes
[ 1 ];
1103 if ( arg
instanceof jQuery
&& !arg
.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1107 if ( typeof arg
=== 'function' ) {
1108 $el
.attr( 'href', '#' )
1109 .click( function ( e
) {
1114 $el
.attr( 'href', textify( arg
) );
1117 return appendWithoutParsing( $el
, contents
);
1121 * Transform parsed structure into pluralization
1122 * n.b. The first node may be a non-integer (for instance, a string representing an Arabic number).
1123 * So convert it back with the current language's convertNumber.
1125 * @param {Array} nodes List of nodes, [ {string|number}, {string}, {string} ... ]
1126 * @return {string} selected pluralized form according to current language
1128 plural: function ( nodes
) {
1129 var forms
, firstChild
, firstChildText
, explicitPluralFormNumber
, formIndex
, form
, count
,
1130 explicitPluralForms
= {};
1132 count
= parseFloat( this.language
.convertNumber( nodes
[ 0 ], true ) );
1133 forms
= nodes
.slice( 1 );
1134 for ( formIndex
= 0; formIndex
< forms
.length
; formIndex
++ ) {
1135 form
= forms
[ formIndex
];
1137 if ( form
instanceof jQuery
&& form
.hasClass( 'mediaWiki_htmlEmitter' ) ) {
1138 // This is a nested node, may be an explicit plural form like 5=[$2 linktext]
1139 firstChild
= form
.contents().get( 0 );
1140 if ( firstChild
&& firstChild
.nodeType
=== Node
.TEXT_NODE
) {
1141 firstChildText
= firstChild
.textContent
;
1142 if ( /^\d+=/.test( firstChildText
) ) {
1143 explicitPluralFormNumber
= parseInt( firstChildText
.split( /=/ )[ 0 ], 10 );
1144 // Use the digit part as key and rest of first text node and
1145 // rest of child nodes as value.
1146 firstChild
.textContent
= firstChildText
.slice( firstChildText
.indexOf( '=' ) + 1 );
1147 explicitPluralForms
[ explicitPluralFormNumber
] = form
;
1148 forms
[ formIndex
] = undefined;
1151 } else if ( /^\d+=/.test( form
) ) {
1152 // Simple explicit plural forms like 12=a dozen
1153 explicitPluralFormNumber
= parseInt( form
.split( /=/ )[ 0 ], 10 );
1154 explicitPluralForms
[ explicitPluralFormNumber
] = form
.slice( form
.indexOf( '=' ) + 1 );
1155 forms
[ formIndex
] = undefined;
1159 // Remove explicit plural forms from the forms. They were set undefined in the above loop.
1160 forms
= $.map( forms
, function ( form
) {
1164 return this.language
.convertPlural( count
, forms
, explicitPluralForms
);
1168 * Transform parsed structure according to gender.
1170 * Usage: {{gender:[ mw.user object | '' | 'male' | 'female' | 'unknown' ] | masculine form | feminine form | neutral form}}.
1172 * The first node must be one of:
1173 * - the mw.user object (or a compatible one)
1174 * - an empty string - indicating the current user, same effect as passing the mw.user object
1175 * - a gender string ('male', 'female' or 'unknown')
1177 * @param {Array} nodes List of nodes, [ {string|mw.user}, {string}, {string}, {string} ]
1178 * @return {string} Selected gender form according to current language
1180 gender: function ( nodes
) {
1182 maybeUser
= nodes
[ 0 ],
1183 forms
= nodes
.slice( 1 );
1185 if ( maybeUser
=== '' ) {
1186 maybeUser
= mw
.user
;
1189 // If we are passed a mw.user-like object, check their gender.
1190 // Otherwise, assume the gender string itself was passed .
1191 if ( maybeUser
&& maybeUser
.options
instanceof mw
.Map
) {
1192 gender
= maybeUser
.options
.get( 'gender' );
1197 return this.language
.gender( gender
, forms
);
1201 * Transform parsed structure into grammar conversion.
1202 * Invoked by putting `{{grammar:form|word}}` in a message
1204 * @param {Array} nodes List of nodes [{Grammar case eg: genitive}, {string word}]
1205 * @return {string} selected grammatical form according to current language
1207 grammar: function ( nodes
) {
1208 var form
= nodes
[ 0 ],
1210 return word
&& form
&& this.language
.convertGrammar( word
, form
);
1214 * Tranform parsed structure into a int: (interface language) message include
1215 * Invoked by putting `{{int:othermessage}}` into a message
1217 * @param {Array} nodes List of nodes
1218 * @return {string} Other message
1220 'int': function ( nodes
) {
1221 var msg
= nodes
[ 0 ];
1222 return mw
.jqueryMsg
.getMessageFunction()( msg
.charAt( 0 ).toLowerCase() + msg
.slice( 1 ) );
1226 * Takes an unformatted number (arab, no group separators and . as decimal separator)
1227 * and outputs it in the localized digit script and formatted with decimal
1228 * separator, according to the current language.
1230 * @param {Array} nodes List of nodes
1231 * @return {number|string} Formatted number
1233 formatnum: function ( nodes
) {
1234 var isInteger
= ( nodes
[ 1 ] && nodes
[ 1 ] === 'R' ) ? true : false,
1235 number
= nodes
[ 0 ];
1237 return this.language
.convertNumber( number
, isInteger
);
1241 // Deprecated! don't rely on gM existing.
1242 // The window.gM ought not to be required - or if required, not required here.
1243 // But moving it to extensions breaks it (?!)
1244 // Need to fix plugin so it could do attributes as well, then will be okay to remove this.
1245 // @deprecated since 1.23
1246 mw
.log
.deprecate( window
, 'gM', mw
.jqueryMsg
.getMessageFunction(), 'Use mw.message( ... ).parse() instead.' );
1251 * @see mw.jqueryMsg#getPlugin
1253 $.fn
.msg
= mw
.jqueryMsg
.getPlugin();
1255 // Replace the default message parser with jqueryMsg
1256 oldParser
= mw
.Message
.prototype.parser
;
1257 mw
.Message
.prototype.parser = function () {
1258 var messageFunction
;
1260 // TODO: should we cache the message function so we don't create a new one every time? Benchmark this maybe?
1261 // Caching is somewhat problematic, because we do need different message functions for different maps, so
1262 // we'd have to cache the parser as a member of this.map, which sounds a bit ugly.
1263 // Do not use mw.jqueryMsg unless required
1264 if ( this.format
=== 'plain' || !/\{\{|[\[<>&]/.test( this.map
.get( this.key
) ) ) {
1265 // Fall back to mw.msg's simple parser
1266 return oldParser
.apply( this );
1269 messageFunction
= mw
.jqueryMsg
.getMessageFunction( {
1271 // For format 'escaped', escaping part is handled by mediawiki.js
1274 return messageFunction( this.key
, this.parameters
);
1277 }( mediaWiki
, jQuery
) );