1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2024-12-11 18:50:28 +00:00
TiddlyWiki5/core/modules/parsers/wikiparser/wikiparser.js

500 lines
17 KiB
JavaScript
Raw Normal View History

/*\
title: $:/core/modules/parsers/wikiparser/wikiparser.js
type: application/javascript
module-type: parser
The wiki text parser processes blocks of source text into a parse tree.
The parse tree is made up of nested arrays of these JavaScript objects:
{type: "element", tag: <string>, attributes: {}, children: []} - an HTML element
{type: "text", text: <string>} - a text node
{type: "entity", value: <string>} - an entity
{type: "raw", html: <string>} - raw HTML
Attributes are stored as hashmaps of the following objects:
{type: "string", value: <string>} - literal string
{type: "indirect", textReference: <textReference>} - indirect through a text reference
2016-02-15 11:33:47 +00:00
{type: "macro", macro: <TBD>} - indirect through a macro invocation
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
type: content type of text
text: text to be parsed
options: see below:
parseAsInline: true to parse text as inline instead of block
wiki: reference to wiki to use
_canonical_uri: optional URI of content if text is missing or empty
Parameterised transclusions (#6666) * Initial commit Everything is draft. * Fix test execution * Fix and test missing target handling * Use the ubertransclude widget for the wikitext transclusion syntax * Changed transclude widget in binary parser to ubertransclude * Add a test for custom action widgets * Don't worry about ordered attributes The changes in 0bffae21088aafc0cdebafe6a5de7907d7c52a3a mean that we don't need to explicitly maintain the ordered attributes * Remove need to explicitly clear widget mapping variable when invoking overridden widget * Use ts- prefix for system slot names * Add a definition for the value widget just so that it doesn't cause errors Of course, it doesn't actually need to be a JS widget, it could be a wikitext widget... * Add support for positional parameters * Ubertransclusion positional parameters should be based on name, not position * Add support for shortcut syntax for positional transclusion parameters * Importvariables should skip parameters widgets * Refactor transclude widget before uberfying it * Refactor ubertransclude functionality into transclude widget * Replace ubertransclude widget with transclude widget * Add wikitext shortcut for new-style function definitions * Allow brackets to be omitted for function definitions with no parameters * Add pragma rule for parameters declarations * Remove erroneous "tag" property * Add support for accessing function parameters as name/value pairs * Be as permissive as possible with parameter names Previously restricted to upper and lower case, digits and dash and underscore * Rewrite some tests to use the shortcut syntaxes * Mustn't allow commas in parameter names * Fix crash when transcluding an undefined variable Thanks @pmario See https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1114692359 * Unquoted parameters should not eat a succeeding comma Fixes #6672 * Remove extraneous code * Allow the let widget to create variables starting with $ * Fix addAttributeToParseTreeNode handling of ordered attributes * Reuse attribute objects when executing custom widgets * Fix importing of function definitions * Fix parameter handling * Introduce genesis widget for dynamically creating widgets See the "RedefineLet" test for a contrived example of usage * Change tiddler separator used in wikitext tests Underscore looked ambiguous; I kept typing dashes by accident * Cache parse trees when transcluding variables * Fix bug with empty strings ignored in $tw.utils.stringifyList/parseStringArray I will pull this out into a separate PR. Fixing it doesn't cause problems for the core but I imagine it might cause issues for 3rd party code. * Fixes to enable the transclude widget itself to be overridden There are two big changes here: Replace the previous "ts-wrapper" mechanism, which we had been using to redefine custom widgets inside their definitions to prevent recursive calls. Now we've got the genesis widget we can instead control recursion through a new "$remappable" attribute that allows the custom widget mechanism to be skipped. We also extend the slot widget to allow a depth to be specified; it then reaches up by the indicated number of transclusion widgets to find the one from which it should retrieve the slot value. * Fix genesis widget example * Use enlist:raw to preserve duplicates * Don't create variables with value undefined for missing parameters * Fix variable retrieval bug with test harness * Improve recursion detection While retaining backwards compatibility * Experimental support for custom filter operators Just as we can define custom widgets we can also define custom parameterised filter operators * Add visible transclusions component and demo Very useful to see transclusions explicitly Makes a good demo of a super-complicated widget override. * Genesis widget should pass raw attributes onto child widget... ...so that it can more efficiently handle refreshing itself. * Use consistent parse tree node property for params * Extend transclude widget to work with old-style macros and use it for the macrocall shortcut syntax * Clarify that the recent changes allow functions to be invoked with the double bracket syntax In other words, the transclude widget distinguishes between functions and macros and handles the parameters appropriately * Make the macrocall widget delegate to the transclude widget * Switch to using \procedure to define new-style macros, and \function for custom filter operator functions I now need to update the OP! * Fix visible transclusion example * Remove obsolete code Left over after refactoring * Better backwards compatibility for legacy recursion marker Fixes the problem with tag dropdowns @btheado * Fix stringifying/parsing string arrays containing newlines A very old bug. Fixes the ActionListOpsWidget problem @btheado * Transclude: replace paramNames/paramValues with more robust JSON payload More details at https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1123719153 * Rename internal "unknown" filter operator so that users cannot invoke it * Detect recursion by tracking widget tree depth The old recursion marker approach was very slow, and didn't catch test cases like editions/test/tiddlers/tests/data/transclude/Recursion.tid * Use \widget for custom widget definitions, and remove need for angle brackets Need to do some refactoring of all those isFunctionDefinition/isProcedureDefinition/isWidgetDefinition flags into a single property * Rename <$value> widget to <$fill> * Require $$ for custom widgets, and that overridden JS widgets must exist See https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1133637763 * Fix invocation of JS macros * Experimental update of the parse-tree preview visualisation An experiment to try out using the new JSON operators for rendering the JSON parse tree that we get back from the wikify widget. As usual with these experiments, this one is going to require quite a lot more work to finish up: * The formatting is via direct styles rather than classes * The formatting for attributes and properties is not yet completed * The same thing needs to also be done to the widget tree preview * Procedures and widgets inherit whitespace trim setting from their definition * Missed off 22e7ec23811b137a119295b5ce72bccdc18a697a * Require period prefix for custom filter operator functions To ensure that custom filter operators cannot clash with future core operators. * Allow custom functions to be invoked as attributes * WIP * Remove unneeded test tiddler * Make is[variable] and variables[] operators resilient to fake widgets * Fix importvariables to work with setvariables as well as set (they are aliases) * Add support for $:/tags/Global * Remove accidental commit 6cc99fcbe33da47cfcb1335d0742b16ea1b9ce03 * Add utility function for parsing macro parameter definitions * Introduce true global variables The basic idea is that if we don't find a variable `foo` then we fallback to retrieving the value from the tiddler `$:/global/foo`, if it exists. This allows us to replace the usual importvariables-based mechanism for global definitions, avoiding cluttering up the variable namespace with every macro. In order to permit subprocedures to be overridden, we also introduce a mechanism for conditional definitions: preceding the word definition|procedure|function|widget with a + causes the definition only to occur if the specified variable doesn't already exist. In the next commit we'll apply this mechanism to the tabs macro * Convert the tabs macro into a global So far it appears to be totally backwards compatible... In practice, I think maybe this and the conversion of the other macros should go into a separate subsequent PR. * Change to `?` for conditional definitions * Fix tabs global so it doesn't crash when viewed directly * Test showing how to un-override a core widget * Cleaning up after f63634900724eda937286d946b2e6f65fcf6d503 * Minor cleanups * Clean up unknown filter * Introduce function operator for calling functions Can invoke any functions, not just those start with a period. And can pass zero parameters (in contrast when invoked as a custom filter operator there's no way to omit the first parameter). * Use underscores for new system fields for global variable tiddlers For consistency with `_canonical_uri`; unlike many system fields, the behaviour of these fields is baked into the core JS code. * Refactor $parameters widget The objective is to add a $depth attribute so that it is possible to reach up to retrieve the parameters of ancestor transclusions. However, doing so requires changing the encoding of parameter names so that it is not possible for a user parameter to clash with an attribute like $depth. So now we have to double up dollars on any attribute names seen by the parameters widget, just like with the transclude widget itself. * Fix refreshing of global variables Global variables access within attributes will automatically trigger a refresh if the attribute text changes, but that wasn't happening for transclusions. * Remove support for $:/tags/Global It is not needed now that we have true global variables * Typo from f513b403fe911442bcbaf0628fa47d3d2ed3cf93 * Make slot fill data available to transclusions Allows transcluded content to dynamically process <$fill> widgets within the calling transclusion * Mark docs as v5.3.0 * Simplify metaparameters implementation * Fix typo * Adjust naming of transclusion metaparameter * Fix up handling of slot/fill for custom widgets Previously we were wrapping the body in an implicit `<$fill $name="ts-body">` widget * Add format:json operator I've been finding this useful for debugging, and it kind of goes with the JSON operators * Docs: JSON operators and tweaks to genesis widget * Docs: format:json Also tweak to the behaviour of format:json if the input string is not valid JSON * Fix #6721 * Revert "Fix #6721" This reverts commit b216579255d6e6214f3cf71ab771fcc57240aa74 which was committed to the wrong branch * Fix new selection tracker to return relative coordinates * Make use of type attribute consistent * Docs: Transclude widget * Simplify the fill widget We can rely on the default processing in the base class * Slot widget: be more defensive about negative depth values * Parameters widget: Be defensive about negative depths * Protect against excessively recursive functions * FIx transcluding of functions This first implementation concatenates the results of the filter (with no separator) and then wikifies the result. The test in this commit is quite interesting... * Tweak semantics of JSON operators to match #6932 This allows us to later bring in the optimisations without breaking backwards compatibility. * Revert obsolete changes to boot.js * Fix inadvertent whitespace change * Remove tests related to obsolete changes to boot.js Should have been part of 2f494ba15246edd356bfc591b0115d30592e7eb8 * Revert changes to parse tree preview This implementation requires #6666 * Add test to show that global widgets need not use the _parameters field * Disable overriding core widgets in safe mode * Coding style tweak * More comments * Fix caching of parse variables/macros/procedures * Transcluded functions should operate on the entire store * Refactor filter recursion detection to avoid an unneeded wrapper function * Fix error in 25312b3e3218c1002c483a1fc995d2b65509b993 * WIP * Revert "WIP" This reverts commit 8654dfc679ea12d30ffd8b14a30165d826be06b7. * When transcluding functions, pass an empty item list to the filter, and just return the first item * Rejig genesis widget to be easier to use * Parameters widget: protect against negative $depth * Docs updates * Docs updates * Tweak comments * Add custom view template body for globals, and a new sidebar tab under "more" And also a custom view template title that greys out the $:/global/ part of the title * Update function operator to return the input list if the function is missing * Remove negation from function operator This implementation was not useful. * Tests and docs for function operator * Docs tweaks * Improve indentation See https://github.com/Jermolene/TiddlyWiki5/pull/6666#discussion_r967655251 * Missing tests for parameters widget * Fix visible transclude * Docs update * Docs typo * Huge Documentation Update Not quite finished, but definitely on the home stretch * Slight optimisation to user defined widgets * Remove implementation of $:/globals/ Performance with this implementation is inherently poor because of the need to perform a wiki lookup for each child widget created. * Docs clarification * Docs update * Some widget.js cleanups * Remove support for conditional definitions It was introduced for use cases associated with the global mechanism that was dropped in e3d13696c887ba849958c8980623d8ff45bb8a36 * Docs updates * Revert change to setwidget docs * Docs update * Docs updates * Clarify/simplify some tests * More docs updates * Fix doc file locations * Docs updates * Revert modified date of docs that have only had minor tweaks * Docs typo https://github.com/Jermolene/TiddlyWiki5/pull/6666#discussion_r990811220 Thanks @btheado * Transcluding functions: fix missing parameters passed as undefined Thanks @btheado – see https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1276187372 * Parameter parenthesis should be mandatory in function/procedure/widget definitions See https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1280404387 * Attempt to build this branch with CI * Add release note etc for 5.3.0 * Temporary new release banner for v5.3.0 * New New Release Banner * New test for undefined parameters * Adjust modified times of docs tiddlers to make them easier to find * Update release note * Add parenthesis to the visible transclusion definition Parenthesis were made mandatory in 5194b24108efda6da95daf4261ffd80473073a65 Fixes #6998 * Fix macrocall refresh issue It turns out that this.transcludeTitle is always truthy, even if we are transcluding a variable Fixes #7001 * Filter run prefixes should use widget.makeFakeWidgetWithVariables * Docs typo Thanks @twMat * Docs: clarify function operator invocation See discussion at https://github.com/Jermolene/TiddlyWiki5/issues/6991#issuecomment-1301703599 * Docs: Update \define pragma to cover named ends * Docs: move tiddlers to correct directory * Add support for named end markers for procedures, functions and widgets * Docs note about nested macro definitions * Rename test * Fix detection of empty transclusions See https://talk.tiddlywiki.org/t/exploring-default-tiddler-links-hackability-in-v5-3-0/5745/25?u=jeremyruston * New test missed off a45349cc996390192114fed486bfa6900da641d7 * Refactor wikified function tests * Refactor function invocation * Introduce new widget helper function to evaluate variables.Functions are evaluated as parameterised filter strings, macros as text with textual substitution of parameters and variables, and procedures and widgets as plain text * Refactor the function operator and unknown operator to use the new helper * Use the new helper to evaluate variables within filter strings, thus fixing a bug whereby functions called in such a way were being returned as plain text instead of being evaluated * Refactor the transclude widget to use the new helper * Update tests * Fix positional parameters in widget.evaluateVariable() This should clear up the remaining anomalies in #7009, let me know how you get on @btheado * Remove 5.2.8 release note * Fix nonstandard initialisation code for fill/parameter/slot widgets * Update modification times of doc tiddlers So that they are at the top of the recent tab * Update 5.3.0 release note * Remove custom CI step for this branch * Restore standard sitetitle
2023-04-19 10:55:25 +00:00
configTrimWhiteSpace: true to trim whitespace
*/
2012-12-26 22:02:59 +00:00
var WikiParser = function(type,text,options) {
this.wiki = options.wiki;
var self = this;
// Check for an externally linked tiddler
if($tw.browser && (text || "") === "" && options._canonical_uri) {
this.loadRemoteTiddler(options._canonical_uri);
text = $tw.language.getRawString("LazyLoadingWarning");
}
// Save the parse text
this.type = type || "text/vnd.tiddlywiki";
this.source = text || "";
this.sourceLength = this.source.length;
// Flag for ignoring whitespace
Parameterised transclusions (#6666) * Initial commit Everything is draft. * Fix test execution * Fix and test missing target handling * Use the ubertransclude widget for the wikitext transclusion syntax * Changed transclude widget in binary parser to ubertransclude * Add a test for custom action widgets * Don't worry about ordered attributes The changes in 0bffae21088aafc0cdebafe6a5de7907d7c52a3a mean that we don't need to explicitly maintain the ordered attributes * Remove need to explicitly clear widget mapping variable when invoking overridden widget * Use ts- prefix for system slot names * Add a definition for the value widget just so that it doesn't cause errors Of course, it doesn't actually need to be a JS widget, it could be a wikitext widget... * Add support for positional parameters * Ubertransclusion positional parameters should be based on name, not position * Add support for shortcut syntax for positional transclusion parameters * Importvariables should skip parameters widgets * Refactor transclude widget before uberfying it * Refactor ubertransclude functionality into transclude widget * Replace ubertransclude widget with transclude widget * Add wikitext shortcut for new-style function definitions * Allow brackets to be omitted for function definitions with no parameters * Add pragma rule for parameters declarations * Remove erroneous "tag" property * Add support for accessing function parameters as name/value pairs * Be as permissive as possible with parameter names Previously restricted to upper and lower case, digits and dash and underscore * Rewrite some tests to use the shortcut syntaxes * Mustn't allow commas in parameter names * Fix crash when transcluding an undefined variable Thanks @pmario See https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1114692359 * Unquoted parameters should not eat a succeeding comma Fixes #6672 * Remove extraneous code * Allow the let widget to create variables starting with $ * Fix addAttributeToParseTreeNode handling of ordered attributes * Reuse attribute objects when executing custom widgets * Fix importing of function definitions * Fix parameter handling * Introduce genesis widget for dynamically creating widgets See the "RedefineLet" test for a contrived example of usage * Change tiddler separator used in wikitext tests Underscore looked ambiguous; I kept typing dashes by accident * Cache parse trees when transcluding variables * Fix bug with empty strings ignored in $tw.utils.stringifyList/parseStringArray I will pull this out into a separate PR. Fixing it doesn't cause problems for the core but I imagine it might cause issues for 3rd party code. * Fixes to enable the transclude widget itself to be overridden There are two big changes here: Replace the previous "ts-wrapper" mechanism, which we had been using to redefine custom widgets inside their definitions to prevent recursive calls. Now we've got the genesis widget we can instead control recursion through a new "$remappable" attribute that allows the custom widget mechanism to be skipped. We also extend the slot widget to allow a depth to be specified; it then reaches up by the indicated number of transclusion widgets to find the one from which it should retrieve the slot value. * Fix genesis widget example * Use enlist:raw to preserve duplicates * Don't create variables with value undefined for missing parameters * Fix variable retrieval bug with test harness * Improve recursion detection While retaining backwards compatibility * Experimental support for custom filter operators Just as we can define custom widgets we can also define custom parameterised filter operators * Add visible transclusions component and demo Very useful to see transclusions explicitly Makes a good demo of a super-complicated widget override. * Genesis widget should pass raw attributes onto child widget... ...so that it can more efficiently handle refreshing itself. * Use consistent parse tree node property for params * Extend transclude widget to work with old-style macros and use it for the macrocall shortcut syntax * Clarify that the recent changes allow functions to be invoked with the double bracket syntax In other words, the transclude widget distinguishes between functions and macros and handles the parameters appropriately * Make the macrocall widget delegate to the transclude widget * Switch to using \procedure to define new-style macros, and \function for custom filter operator functions I now need to update the OP! * Fix visible transclusion example * Remove obsolete code Left over after refactoring * Better backwards compatibility for legacy recursion marker Fixes the problem with tag dropdowns @btheado * Fix stringifying/parsing string arrays containing newlines A very old bug. Fixes the ActionListOpsWidget problem @btheado * Transclude: replace paramNames/paramValues with more robust JSON payload More details at https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1123719153 * Rename internal "unknown" filter operator so that users cannot invoke it * Detect recursion by tracking widget tree depth The old recursion marker approach was very slow, and didn't catch test cases like editions/test/tiddlers/tests/data/transclude/Recursion.tid * Use \widget for custom widget definitions, and remove need for angle brackets Need to do some refactoring of all those isFunctionDefinition/isProcedureDefinition/isWidgetDefinition flags into a single property * Rename <$value> widget to <$fill> * Require $$ for custom widgets, and that overridden JS widgets must exist See https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1133637763 * Fix invocation of JS macros * Experimental update of the parse-tree preview visualisation An experiment to try out using the new JSON operators for rendering the JSON parse tree that we get back from the wikify widget. As usual with these experiments, this one is going to require quite a lot more work to finish up: * The formatting is via direct styles rather than classes * The formatting for attributes and properties is not yet completed * The same thing needs to also be done to the widget tree preview * Procedures and widgets inherit whitespace trim setting from their definition * Missed off 22e7ec23811b137a119295b5ce72bccdc18a697a * Require period prefix for custom filter operator functions To ensure that custom filter operators cannot clash with future core operators. * Allow custom functions to be invoked as attributes * WIP * Remove unneeded test tiddler * Make is[variable] and variables[] operators resilient to fake widgets * Fix importvariables to work with setvariables as well as set (they are aliases) * Add support for $:/tags/Global * Remove accidental commit 6cc99fcbe33da47cfcb1335d0742b16ea1b9ce03 * Add utility function for parsing macro parameter definitions * Introduce true global variables The basic idea is that if we don't find a variable `foo` then we fallback to retrieving the value from the tiddler `$:/global/foo`, if it exists. This allows us to replace the usual importvariables-based mechanism for global definitions, avoiding cluttering up the variable namespace with every macro. In order to permit subprocedures to be overridden, we also introduce a mechanism for conditional definitions: preceding the word definition|procedure|function|widget with a + causes the definition only to occur if the specified variable doesn't already exist. In the next commit we'll apply this mechanism to the tabs macro * Convert the tabs macro into a global So far it appears to be totally backwards compatible... In practice, I think maybe this and the conversion of the other macros should go into a separate subsequent PR. * Change to `?` for conditional definitions * Fix tabs global so it doesn't crash when viewed directly * Test showing how to un-override a core widget * Cleaning up after f63634900724eda937286d946b2e6f65fcf6d503 * Minor cleanups * Clean up unknown filter * Introduce function operator for calling functions Can invoke any functions, not just those start with a period. And can pass zero parameters (in contrast when invoked as a custom filter operator there's no way to omit the first parameter). * Use underscores for new system fields for global variable tiddlers For consistency with `_canonical_uri`; unlike many system fields, the behaviour of these fields is baked into the core JS code. * Refactor $parameters widget The objective is to add a $depth attribute so that it is possible to reach up to retrieve the parameters of ancestor transclusions. However, doing so requires changing the encoding of parameter names so that it is not possible for a user parameter to clash with an attribute like $depth. So now we have to double up dollars on any attribute names seen by the parameters widget, just like with the transclude widget itself. * Fix refreshing of global variables Global variables access within attributes will automatically trigger a refresh if the attribute text changes, but that wasn't happening for transclusions. * Remove support for $:/tags/Global It is not needed now that we have true global variables * Typo from f513b403fe911442bcbaf0628fa47d3d2ed3cf93 * Make slot fill data available to transclusions Allows transcluded content to dynamically process <$fill> widgets within the calling transclusion * Mark docs as v5.3.0 * Simplify metaparameters implementation * Fix typo * Adjust naming of transclusion metaparameter * Fix up handling of slot/fill for custom widgets Previously we were wrapping the body in an implicit `<$fill $name="ts-body">` widget * Add format:json operator I've been finding this useful for debugging, and it kind of goes with the JSON operators * Docs: JSON operators and tweaks to genesis widget * Docs: format:json Also tweak to the behaviour of format:json if the input string is not valid JSON * Fix #6721 * Revert "Fix #6721" This reverts commit b216579255d6e6214f3cf71ab771fcc57240aa74 which was committed to the wrong branch * Fix new selection tracker to return relative coordinates * Make use of type attribute consistent * Docs: Transclude widget * Simplify the fill widget We can rely on the default processing in the base class * Slot widget: be more defensive about negative depth values * Parameters widget: Be defensive about negative depths * Protect against excessively recursive functions * FIx transcluding of functions This first implementation concatenates the results of the filter (with no separator) and then wikifies the result. The test in this commit is quite interesting... * Tweak semantics of JSON operators to match #6932 This allows us to later bring in the optimisations without breaking backwards compatibility. * Revert obsolete changes to boot.js * Fix inadvertent whitespace change * Remove tests related to obsolete changes to boot.js Should have been part of 2f494ba15246edd356bfc591b0115d30592e7eb8 * Revert changes to parse tree preview This implementation requires #6666 * Add test to show that global widgets need not use the _parameters field * Disable overriding core widgets in safe mode * Coding style tweak * More comments * Fix caching of parse variables/macros/procedures * Transcluded functions should operate on the entire store * Refactor filter recursion detection to avoid an unneeded wrapper function * Fix error in 25312b3e3218c1002c483a1fc995d2b65509b993 * WIP * Revert "WIP" This reverts commit 8654dfc679ea12d30ffd8b14a30165d826be06b7. * When transcluding functions, pass an empty item list to the filter, and just return the first item * Rejig genesis widget to be easier to use * Parameters widget: protect against negative $depth * Docs updates * Docs updates * Tweak comments * Add custom view template body for globals, and a new sidebar tab under "more" And also a custom view template title that greys out the $:/global/ part of the title * Update function operator to return the input list if the function is missing * Remove negation from function operator This implementation was not useful. * Tests and docs for function operator * Docs tweaks * Improve indentation See https://github.com/Jermolene/TiddlyWiki5/pull/6666#discussion_r967655251 * Missing tests for parameters widget * Fix visible transclude * Docs update * Docs typo * Huge Documentation Update Not quite finished, but definitely on the home stretch * Slight optimisation to user defined widgets * Remove implementation of $:/globals/ Performance with this implementation is inherently poor because of the need to perform a wiki lookup for each child widget created. * Docs clarification * Docs update * Some widget.js cleanups * Remove support for conditional definitions It was introduced for use cases associated with the global mechanism that was dropped in e3d13696c887ba849958c8980623d8ff45bb8a36 * Docs updates * Revert change to setwidget docs * Docs update * Docs updates * Clarify/simplify some tests * More docs updates * Fix doc file locations * Docs updates * Revert modified date of docs that have only had minor tweaks * Docs typo https://github.com/Jermolene/TiddlyWiki5/pull/6666#discussion_r990811220 Thanks @btheado * Transcluding functions: fix missing parameters passed as undefined Thanks @btheado – see https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1276187372 * Parameter parenthesis should be mandatory in function/procedure/widget definitions See https://github.com/Jermolene/TiddlyWiki5/pull/6666#issuecomment-1280404387 * Attempt to build this branch with CI * Add release note etc for 5.3.0 * Temporary new release banner for v5.3.0 * New New Release Banner * New test for undefined parameters * Adjust modified times of docs tiddlers to make them easier to find * Update release note * Add parenthesis to the visible transclusion definition Parenthesis were made mandatory in 5194b24108efda6da95daf4261ffd80473073a65 Fixes #6998 * Fix macrocall refresh issue It turns out that this.transcludeTitle is always truthy, even if we are transcluding a variable Fixes #7001 * Filter run prefixes should use widget.makeFakeWidgetWithVariables * Docs typo Thanks @twMat * Docs: clarify function operator invocation See discussion at https://github.com/Jermolene/TiddlyWiki5/issues/6991#issuecomment-1301703599 * Docs: Update \define pragma to cover named ends * Docs: move tiddlers to correct directory * Add support for named end markers for procedures, functions and widgets * Docs note about nested macro definitions * Rename test * Fix detection of empty transclusions See https://talk.tiddlywiki.org/t/exploring-default-tiddler-links-hackability-in-v5-3-0/5745/25?u=jeremyruston * New test missed off a45349cc996390192114fed486bfa6900da641d7 * Refactor wikified function tests * Refactor function invocation * Introduce new widget helper function to evaluate variables.Functions are evaluated as parameterised filter strings, macros as text with textual substitution of parameters and variables, and procedures and widgets as plain text * Refactor the function operator and unknown operator to use the new helper * Use the new helper to evaluate variables within filter strings, thus fixing a bug whereby functions called in such a way were being returned as plain text instead of being evaluated * Refactor the transclude widget to use the new helper * Update tests * Fix positional parameters in widget.evaluateVariable() This should clear up the remaining anomalies in #7009, let me know how you get on @btheado * Remove 5.2.8 release note * Fix nonstandard initialisation code for fill/parameter/slot widgets * Update modification times of doc tiddlers So that they are at the top of the recent tab * Update 5.3.0 release note * Remove custom CI step for this branch * Restore standard sitetitle
2023-04-19 10:55:25 +00:00
this.configTrimWhiteSpace = options.configTrimWhiteSpace !== undefined ? options.configTrimWhiteSpace : false;
2022-11-23 22:35:32 +00:00
// Parser mode
this.parseAsInline = options.parseAsInline;
// Set current parse position
this.pos = 0;
// Start with empty output
this.tree = [];
// Assemble the rule classes we're going to use
var pragmaRuleClasses, blockRuleClasses, inlineRuleClasses;
if(options.rules) {
pragmaRuleClasses = options.rules.pragma;
blockRuleClasses = options.rules.block;
inlineRuleClasses = options.rules.inline;
} else {
// Setup the rule classes if we don't have them already
if(!this.pragmaRuleClasses) {
WikiParser.prototype.pragmaRuleClasses = $tw.modules.createClassesFromModules("wikirule","pragma",$tw.WikiRuleBase);
this.setupRules(WikiParser.prototype.pragmaRuleClasses,"$:/config/WikiParserRules/Pragmas/");
}
pragmaRuleClasses = this.pragmaRuleClasses;
if(!this.blockRuleClasses) {
WikiParser.prototype.blockRuleClasses = $tw.modules.createClassesFromModules("wikirule","block",$tw.WikiRuleBase);
this.setupRules(WikiParser.prototype.blockRuleClasses,"$:/config/WikiParserRules/Block/");
}
blockRuleClasses = this.blockRuleClasses;
if(!this.inlineRuleClasses) {
WikiParser.prototype.inlineRuleClasses = $tw.modules.createClassesFromModules("wikirule","inline",$tw.WikiRuleBase);
this.setupRules(WikiParser.prototype.inlineRuleClasses,"$:/config/WikiParserRules/Inline/");
}
inlineRuleClasses = this.inlineRuleClasses;
}
// Instantiate the pragma parse rules
this.pragmaRules = this.instantiateRules(pragmaRuleClasses,"pragma",0);
// Instantiate the parser block and inline rules
this.blockRules = this.instantiateRules(blockRuleClasses,"block",0);
this.inlineRules = this.instantiateRules(inlineRuleClasses,"inline",0);
// Parse any pragmas
var topBranch = this.parsePragmas();
// Parse the text into inline runs or blocks
2022-11-23 22:35:32 +00:00
if(this.parseAsInline) {
topBranch.push.apply(topBranch,this.parseInlineRun());
} else {
topBranch.push.apply(topBranch,this.parseBlocks());
}
// Build rules' name map
this.usingRuleMap = {};
$tw.utils.each(this.pragmaRules, function (ruleInfo) { self.usingRuleMap[ruleInfo.rule.name] = Object.getPrototypeOf(ruleInfo.rule); });
$tw.utils.each(this.blockRules, function (ruleInfo) { self.usingRuleMap[ruleInfo.rule.name] = Object.getPrototypeOf(ruleInfo.rule); });
$tw.utils.each(this.inlineRules, function (ruleInfo) { self.usingRuleMap[ruleInfo.rule.name] = Object.getPrototypeOf(ruleInfo.rule); });
// Return the parse tree
};
/*
*/
WikiParser.prototype.loadRemoteTiddler = function(url) {
var self = this;
$tw.utils.httpRequest({
url: url,
type: "GET",
callback: function(err,data) {
if(!err) {
var tiddlers = self.wiki.deserializeTiddlers(".tid",data,self.wiki.getCreationFields());
$tw.utils.each(tiddlers,function(tiddler) {
tiddler["_canonical_uri"] = url;
});
if(tiddlers) {
self.wiki.addTiddlers(tiddlers);
}
}
}
});
};
/*
*/
WikiParser.prototype.setupRules = function(proto,configPrefix) {
var self = this;
if(!$tw.safeMode) {
$tw.utils.each(proto,function(object,name) {
if(self.wiki.getTiddlerText(configPrefix + name,"enable") !== "enable") {
delete proto[name];
}
});
}
};
/*
Instantiate an array of parse rules
*/
WikiParser.prototype.instantiateRules = function(classes,type,startPos) {
var rulesInfo = [],
self = this;
$tw.utils.each(classes,function(RuleClass) {
// Instantiate the rule
var rule = new RuleClass(self);
rule.is = {};
rule.is[type] = true;
rule.init(self);
var matchIndex = rule.findNextMatch(startPos);
if(matchIndex !== undefined) {
rulesInfo.push({
rule: rule,
matchIndex: matchIndex
});
}
});
return rulesInfo;
};
/*
Skip any whitespace at the current position. Options are:
treatNewlinesAsNonWhitespace: true if newlines are NOT to be treated as whitespace
*/
WikiParser.prototype.skipWhitespace = function(options) {
options = options || {};
var whitespaceRegExp = options.treatNewlinesAsNonWhitespace ? /([^\S\n]+)/mg : /(\s+)/mg;
whitespaceRegExp.lastIndex = this.pos;
var whitespaceMatch = whitespaceRegExp.exec(this.source);
if(whitespaceMatch && whitespaceMatch.index === this.pos) {
this.pos = whitespaceRegExp.lastIndex;
}
};
/*
Get the next match out of an array of parse rule instances
*/
WikiParser.prototype.findNextMatch = function(rules,startPos) {
// Find the best matching rule by finding the closest match position
var matchingRule,
matchingRulePos = this.sourceLength;
// Step through each rule
for(var t=0; t<rules.length; t++) {
var ruleInfo = rules[t];
// Ask the rule to get the next match if we've moved past the current one
if(ruleInfo.matchIndex !== undefined && ruleInfo.matchIndex < startPos) {
ruleInfo.matchIndex = ruleInfo.rule.findNextMatch(startPos);
}
// Adopt this match if it's closer than the current best match
if(ruleInfo.matchIndex !== undefined && ruleInfo.matchIndex <= matchingRulePos) {
matchingRule = ruleInfo;
matchingRulePos = ruleInfo.matchIndex;
}
}
return matchingRule;
};
/*
Parse any pragmas at the beginning of a block of parse text
*/
WikiParser.prototype.parsePragmas = function() {
var currentTreeBranch = this.tree;
while(true) {
var savedPos = this.pos;
// Skip whitespace
this.skipWhitespace();
// Check for the end of the text
if(this.pos >= this.sourceLength) {
break;
}
// Check if we've arrived at a pragma rule match
var nextMatch = this.findNextMatch(this.pragmaRules,this.pos);
// If not, just exit
if(!nextMatch || nextMatch.matchIndex !== this.pos) {
this.pos = savedPos;
break;
}
// Process the pragma rule
var start = this.pos;
2021-05-29 18:30:04 +00:00
var subTree = nextMatch.rule.parse();
if(subTree.length > 0) {
// Set the start and end positions of the pragma rule if
if (subTree[0].start === undefined) subTree[0].start = start;
if (subTree[subTree.length - 1].end === undefined) subTree[subTree.length - 1].end = this.pos;
$tw.utils.each(subTree, function (node) { node.rule = nextMatch.rule.name; });
// Quick hack; we only cope with a single parse tree node being returned, which is true at the moment
currentTreeBranch.push.apply(currentTreeBranch,subTree);
subTree[0].children = [];
currentTreeBranch = subTree[0].children;
}
// Skip whitespace after the pragma
this.skipWhitespace();
}
return currentTreeBranch;
};
/*
Parse a block from the current position
terminatorRegExpString: optional regular expression string that identifies the end of plain paragraphs. Must not include capturing parenthesis
*/
WikiParser.prototype.parseBlock = function(terminatorRegExpString) {
var terminatorRegExp = terminatorRegExpString ? new RegExp(terminatorRegExpString + "|\\r?\\n\\r?\\n","mg") : /(\r?\n\r?\n)/mg;
this.skipWhitespace();
if(this.pos >= this.sourceLength) {
return [];
}
// Look for a block rule that applies at the current position
var nextMatch = this.findNextMatch(this.blockRules,this.pos);
if(nextMatch && nextMatch.matchIndex === this.pos) {
var start = this.pos;
var subTree = nextMatch.rule.parse();
// Set the start and end positions of the first and last blocks if they're not already set
if (subTree.length > 0) {
if (subTree[0].start === undefined) subTree[0].start = start;
if (subTree[subTree.length - 1].end === undefined) subTree[subTree.length - 1].end = this.pos;
}
$tw.utils.each(subTree, function (node) { node.rule = nextMatch.rule.name; });
return subTree;
}
// Treat it as a paragraph if we didn't find a block rule
2020-11-04 20:02:17 +00:00
var start = this.pos;
var children = this.parseInlineRun(terminatorRegExp);
var end = this.pos;
return [{type: "element", tag: "p", children: children, start: start, end: end }];
};
/*
Parse a series of blocks of text until a terminating regexp is encountered or the end of the text
terminatorRegExpString: terminating regular expression
*/
WikiParser.prototype.parseBlocks = function(terminatorRegExpString) {
if(terminatorRegExpString) {
return this.parseBlocksTerminated(terminatorRegExpString);
} else {
return this.parseBlocksUnterminated();
}
};
/*
Parse a block from the current position to the end of the text
*/
WikiParser.prototype.parseBlocksUnterminated = function() {
var tree = [];
while(this.pos < this.sourceLength) {
tree.push.apply(tree,this.parseBlock());
}
return tree;
};
/*
Parse blocks of text until a terminating regexp is encountered. Wrapper for parseBlocksTerminatedExtended that just returns the parse tree
*/
WikiParser.prototype.parseBlocksTerminated = function(terminatorRegExpString) {
var ex = this.parseBlocksTerminatedExtended(terminatorRegExpString);
return ex.tree;
};
/*
Parse blocks of text until a terminating regexp is encountered
*/
WikiParser.prototype.parseBlocksTerminatedExtended = function(terminatorRegExpString) {
var terminatorRegExp = new RegExp(terminatorRegExpString,"mg"),
result = {
tree: []
};
// Skip any whitespace
this.skipWhitespace();
// Check if we've got the end marker
terminatorRegExp.lastIndex = this.pos;
var match = terminatorRegExp.exec(this.source);
// Parse the text into blocks
while(this.pos < this.sourceLength && !(match && match.index === this.pos)) {
var blocks = this.parseBlock(terminatorRegExpString);
result.tree.push.apply(result.tree,blocks);
// Skip any whitespace
this.skipWhitespace();
// Check if we've got the end marker
terminatorRegExp.lastIndex = this.pos;
match = terminatorRegExp.exec(this.source);
}
if(match && match.index === this.pos) {
this.pos = match.index + match[0].length;
result.match = match;
}
return result;
};
/*
Parse a run of text at the current position
terminatorRegExp: a regexp at which to stop the run
options: see below
Options available:
eatTerminator: move the parse position past any encountered terminator (default false)
*/
WikiParser.prototype.parseInlineRun = function(terminatorRegExp,options) {
if(terminatorRegExp) {
return this.parseInlineRunTerminated(terminatorRegExp,options);
} else {
return this.parseInlineRunUnterminated(options);
}
};
WikiParser.prototype.parseInlineRunUnterminated = function(options) {
var tree = [];
// Find the next occurrence of an inline rule
var nextMatch = this.findNextMatch(this.inlineRules,this.pos);
// Loop around the matches until we've reached the end of the text
while(this.pos < this.sourceLength && nextMatch) {
// Process the text preceding the run rule
if(nextMatch.matchIndex > this.pos) {
2020-11-04 20:02:17 +00:00
this.pushTextWidget(tree,this.source.substring(this.pos,nextMatch.matchIndex),this.pos,nextMatch.matchIndex);
this.pos = nextMatch.matchIndex;
}
// Process the run rule
var start = this.pos;
var subTree = nextMatch.rule.parse();
// Set the start and end positions of the first and last child if they're not already set
if (subTree.length > 0) {
// Set the start and end positions of the first and last child if they're not already set
if (subTree[0].start === undefined) subTree[0].start = start;
if (subTree[subTree.length - 1].end === undefined) subTree[subTree.length - 1].end = this.pos;
}
$tw.utils.each(subTree, function (node) { node.rule = nextMatch.rule.name; });
tree.push.apply(tree,subTree);
// Look for the next run rule
nextMatch = this.findNextMatch(this.inlineRules,this.pos);
}
// Process the remaining text
if(this.pos < this.sourceLength) {
2020-11-04 20:02:17 +00:00
this.pushTextWidget(tree,this.source.substr(this.pos),this.pos,this.sourceLength);
}
this.pos = this.sourceLength;
return tree;
};
WikiParser.prototype.parseInlineRunTerminated = function(terminatorRegExp,options) {
var ex = this.parseInlineRunTerminatedExtended(terminatorRegExp,options);
return ex.tree;
};
WikiParser.prototype.parseInlineRunTerminatedExtended = function(terminatorRegExp,options) {
options = options || {};
var tree = [];
// Find the next occurrence of the terminator
terminatorRegExp.lastIndex = this.pos;
var terminatorMatch = terminatorRegExp.exec(this.source);
// Find the next occurrence of a inlinerule
var inlineRuleMatch = this.findNextMatch(this.inlineRules,this.pos);
// Loop around until we've reached the end of the text
while(this.pos < this.sourceLength && (terminatorMatch || inlineRuleMatch)) {
// Return if we've found the terminator, and it precedes any inline rule match
if(terminatorMatch) {
if(!inlineRuleMatch || inlineRuleMatch.matchIndex >= terminatorMatch.index) {
if(terminatorMatch.index > this.pos) {
2020-11-04 20:02:17 +00:00
this.pushTextWidget(tree,this.source.substring(this.pos,terminatorMatch.index),this.pos,terminatorMatch.index);
}
this.pos = terminatorMatch.index;
if(options.eatTerminator) {
this.pos += terminatorMatch[0].length;
}
return {
match: terminatorMatch,
tree: tree
};
}
}
// Process any inline rule, along with the text preceding it
if(inlineRuleMatch) {
// Preceding text
if(inlineRuleMatch.matchIndex > this.pos) {
2020-11-04 20:02:17 +00:00
this.pushTextWidget(tree,this.source.substring(this.pos,inlineRuleMatch.matchIndex),this.pos,inlineRuleMatch.matchIndex);
this.pos = inlineRuleMatch.matchIndex;
}
// Process the inline rule
var start = this.pos;
var subTree = inlineRuleMatch.rule.parse();
// Set the start and end positions of the first and last child if they're not already set
if (subTree.length > 0) {
if (subTree[0].start === undefined) subTree[0].start = start;
if (subTree[subTree.length - 1].end === undefined) subTree[subTree.length - 1].end = this.pos;
}
$tw.utils.each(subTree, function (node) { node.rule = inlineRuleMatch.rule.name; });
tree.push.apply(tree,subTree);
// Look for the next inline rule
inlineRuleMatch = this.findNextMatch(this.inlineRules,this.pos);
// Look for the next terminator match
terminatorRegExp.lastIndex = this.pos;
terminatorMatch = terminatorRegExp.exec(this.source);
}
}
// Process the remaining text
if(this.pos < this.sourceLength) {
2020-11-04 20:02:17 +00:00
this.pushTextWidget(tree,this.source.substr(this.pos),this.pos,this.sourceLength);
}
this.pos = this.sourceLength;
return {
tree: tree
};
};
/*
Push a text widget onto an array, respecting the configTrimWhiteSpace setting
*/
2020-11-04 20:02:17 +00:00
WikiParser.prototype.pushTextWidget = function(array,text,start,end) {
if(this.configTrimWhiteSpace) {
text = $tw.utils.trim(text);
}
if(text) {
array.push({type: "text", text: text, start: start, end: end});
}
};
/*
2012-12-15 17:35:16 +00:00
Parse zero or more class specifiers `.classname`
*/
2012-12-15 17:35:16 +00:00
WikiParser.prototype.parseClasses = function() {
var classRegExp = /\.([^\s\.]+)/mg,
classNames = [];
classRegExp.lastIndex = this.pos;
var match = classRegExp.exec(this.source);
while(match && match.index === this.pos) {
this.pos = match.index + match[0].length;
classNames.push(match[1]);
match = classRegExp.exec(this.source);
}
2012-12-15 17:35:16 +00:00
return classNames;
};
/*
Amend the rules used by this instance of the parser
type: `only` keeps just the named rules, `except` keeps all but the named rules
names: array of rule names
*/
WikiParser.prototype.amendRules = function(type,names) {
names = names || [];
// Define the filter function
var target;
if(type === "only") {
target = true;
} else if(type === "except") {
target = false;
} else {
return;
}
// Define a function to process each of our rule arrays
var processRuleArray = function(ruleArray) {
for(var t=ruleArray.length-1; t>=0; t--) {
if((names.indexOf(ruleArray[t].rule.name) === -1) === target) {
ruleArray.splice(t,1);
}
}
};
// Process each rule array
processRuleArray(this.pragmaRules);
processRuleArray(this.blockRules);
processRuleArray(this.inlineRules);
};
exports["text/vnd.tiddlywiki"] = WikiParser;
})();