TiddlyWiki incorporates code from these fine OpenSource projects:
* [[The Stanford Javascript Crypto Library|http://bitwiseshiftleft.github.io/sjcl/]]
* [[The Jasmine JavaScript Test Framework|http://pivotal.github.io/jasmine/]]
* [[Normalize.css by Nicolas Gallagher|http://necolas.github.io/normalize.css/]]
And media from these projects:
* World flag icons from [[Wikipedia|http://commons.wikimedia.org/wiki/Category:SVG_flags_by_country]]
<div class="tc-advanced-search">
<<tabs "[all[shadows+tiddlers]tag[$:/tags/AdvancedSearch]!has[draft.of]]" "$:/core/ui/AdvancedSearch/System">>
</div>
/*\
title: $:/bj/modules/widgets/click.js
type: application/javascript
module-type: widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var clickWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
clickWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
clickWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
};
/*
Compute the internal state of the widget
*/
clickWidget.prototype.execute = function() {
this.stateTitle = this.getAttribute("state");
this.text = this.getAttribute("text");
};
clickWidget.prototype.readState = function() {
// Read the information from the state tiddler
if(this.stateTitle) {
var state = this.wiki.getTextReference(this.stateTitle,this["default"],this.getVariable("currentTiddler"));
if (state === this.text) {
this.parentDomNode.click();
return false;
}
}
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
clickWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
// Completely rerender if any of our attributes have changed
if(changedAttributes.text || changedAttributes.state) {
this.refreshSelf();
return true;
} else if(this.stateTitle && changedTiddlers[this.stateTitle]) {
this.readState();
return true;
}
return false;
};
exports["click"] = clickWidget;
})();
/*\
title: $:/bj/modules/widgets/mangletagsextra.js
type: application/javascript
module-type: widget
MangleTagsExtaWidget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MangleTagsExtraWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
MangleTagsExtraWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MangleTagsExtraWidget.prototype.render = function(parent,nextSibling) {
this.computeAttributes();
this.execute();
};
/*
Compute the internal state of the widget
*/
MangleTagsExtraWidget.prototype.execute = function() {
// Get our parameters
if (this.getAttribute("removeAll")) this.removelist = this.wiki.filterTiddlers(this.getAttribute("removeAll"),this);
if (this.getAttribute("addAll")) this.addlist = this.wiki.filterTiddlers(this.getAttribute("addAll"),this);
// Construct the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
MangleTagsExtraWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes["removeAll"] || changedAttributes["addAll"]) {
this.refreshSelf();
return true;
}
else {
return false;
}
};
MangleTagsExtraWidget.prototype.invokeMsgAction = function(param) {
// Set defaults
var self = this;
this.mangleTitle = this.getVariable("currentTiddler");
if(param.event.param) {
this.mangleTitle = param.event.param;
this.sendParam = param.event.param;
}
if(this.catchTiddler) {
this.mangleTitle = this.catchTiddler;
}
// Get the target tiddler
var tiddler = this.wiki.getTiddler(this.mangleTitle);
// If there is a find= attribute -- find the tag and remove it
if(tiddler) {
var modification;
if (this.removelist) {
if (!modification) {
modification = this.wiki.getModificationFields();
modification.tags = (tiddler.fields.tags || []).slice(0);
}
modification.tags = modification.tags.filter(function(i) {return self.removelist.indexOf(i) < 0;});
}
if(this.addlist) {
if (!modification) {
modification = this.wiki.getModificationFields();
modification.tags = (tiddler.fields.tags || []).slice(0);
}
$tw.utils.pushTop(modification.tags,this.addlist);
}
// Save the modified tiddler
if (modification) {
this.wiki.addTiddler(new $tw.Tiddler(tiddler,modification));
}
}
return param;
};
exports.mangletagsextra = MangleTagsExtraWidget;
})();
/*\
title: $:/bj/modules/widgets/msgcatcher.js
type: application/javascript
module-type: widget
MsgCatcherWiget - root of msg action widget - 1
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MsgCatcherWiget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
MsgCatcherWiget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MsgCatcherWiget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
MsgCatcherWiget.prototype.execute = function() {
// Get our parameters
this.msg=this.getAttribute("msg");
if (this.msg) {
this.eventListeners = {};
this.addEventListeners([
{type: this.msg, handler: "handleEvent"}
]);
}
// Construct the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
MsgCatcherWiget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes["msg"] ) {
this.refreshSelf();
return true;
}
else {
return this.refreshChildren(changedTiddlers);
}
};
MsgCatcherWiget.prototype.handleEvent = function(event) {
this.invokeMsgActions(event);
return false;//always consume event
};
/*Invoke any action widgets that are immediate children of this widget
*/
MsgCatcherWiget.prototype.invokeMsgActions = function(event) {
for(var t=0; t<this.children.length; t++) {
var child = this.children[t];
var params = {event:event,continue:false};
if(child.invokeMsgAction) params = child.invokeMsgAction(params);
}
if(params.continue && this.parentWidget) {
this.parentWidget.dispatchEvent(params.event);
}
};
exports.msgcatcher = MsgCatcherWiget;
})();
/*\
title: $:/bj/modules/widgets/plylist.js
type: application/javascript
module-type: widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MPlayListWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
this.addEventListeners([
{type: "tm-ply-next", handler: "handleNextEvent"},
{type: "tm-ply-move", handler: "handleMoveEvent"},
{type: "tm-ply-prev", handler: "handlePrevEvent"}]);
};
/*
Inherit from the base widget class
*/
MPlayListWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MPlayListWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
MPlayListWidget.prototype.execute = function() {
// Compose the list elements
this.list = this.getTiddlerList();
this.n =-1;
this.syntid = this.getAttribute("syntid");
this.mode = this.getAttribute("mode");
// Construct the child widgets
this.makeChildWidgets();
};
MPlayListWidget.prototype.getTiddlerList = function() {
var defaultFilter = "[tag["+this.getVariable("currentTiddler")+"]]";
return this.wiki.filterTiddlers(this.getAttribute("filter",defaultFilter),this);
};
/*
Refresh the widget by ensuring our attributes are up to date
*/
MPlayListWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
//alert(this.attributes.filter);
if(changedAttributes.filter || changedAttributes["$tiddler"]) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
/*
Invoke the action associated with this widget
*/
MPlayListWidget.prototype.invokeMsgAction = function(param) {
this.doNext();
return param;
};
MPlayListWidget.prototype.updatelist = function() {
var list,n,i,curr = this.list[this.n];
list = this.getTiddlerList();
for ( i = 0; i < list.length; i++) {
if (list[i] === curr) break;
}
if (i === list.length) i = 0;
this.n = i;
this.list = list;
}
MPlayListWidget.prototype.doMove = function(loc) {
if (this.mode == "dynamic") this.updatelist();
if(this.list.length === 0) {
//do nothing
} else {
var tid,uri,i;
for (i = 0; i < this.list.length; i++) {
if ((loc == this.list[i])) {
this.wiki.setTextReference(this.syntid,this.list[i],this.getVariable("currentTiddler"));
break;
}
}
this.n = (i == this.list.length ? this.list.length - 1 : i);
}
}
MPlayListWidget.prototype.doStart = function() {
if (this.mode == "dynamic") this.updatelist();
this.n = -1;
if(this.list.length === 0) {
//do nothing
} else {
var tid,uri,i;
if (this.n == this.list.length -1) {
this.invokeActions();
return;
};
for (i = this.n + 1; i < this.list.length; i++) {
if ((tid = this.wiki.getTiddler(this.list[i])) ) {
this.wiki.setTextReference(this.syntid,this.list[i],this.getVariable("currentTiddler"));
break;
}
}
this.n = (i == this.list.length ? this.list.length - 1 : i);
}
}
MPlayListWidget.prototype.doNext = function() {
if (this.mode == "dynamic") this.updatelist();
if(this.list.length === 0) {
//do nothing
} else {
var tid,uri,i;
if (this.n == this.list.length -1) {
this.invokeActions();
return;
}
for (i = this.n + 1; i < this.list.length; i++) {
if ((tid = this.wiki.getTiddler(this.list[i]))) {
this.wiki.setTextReference(this.syntid,this.list[i],this.getVariable("currentTiddler"));
break;
}
}
this.n = (i == this.list.length ? this.list.length - 1 : i);
}
}
MPlayListWidget.prototype.doPrev = function() {
if (this.mode == "dynamic") this.updatelist();
if(this.list.length === 0) {
//do nothing
} else {
var tid,i;
for (i = this.n - 1; i >=0; i--) {
if (tid = this.wiki.getTiddler(this.list[i])) {
this.wiki.setTextReference(this.syntid,this.list[i],this.getVariable("currentTiddler"));
break;
}
}
this.n = (i == -1? 0 : i);
}
}
MPlayListWidget.prototype.handleNextEvent = function(event) {
// Check for an empty list
this.doNext();
return false; // dont propegate
}
MPlayListWidget.prototype.handleMoveEvent = function(event) {
// Check for an empty list
this.doMove(event.navigateTo);
return false; // dont propegate
}
MPlayListWidget.prototype.handlePrevEvent = function(event) {
// Check for an empty list
this.doPrev();
return false; // dont propegate
}
exports["playlist"] = MPlayListWidget;
})();
/*\
title: $:/bj/modules/widgets/refresh.js
type: application/javascript
module-type: widget
refreshWiget -
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var refreshWiget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
refreshWiget.prototype = new Widget();
/*
Render this widget into the DOM
*/
refreshWiget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
refreshWiget.prototype.execute = function() {
// Get our parameters
this.msg=this.getAttribute("msg");
if (this.msg) {
this.eventListeners = {};
this.addEventListeners([
{type: this.msg, handler: "handleRefreshEvent"}
]);
}
// Construct the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
refreshWiget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes["msg"] ) {
this.refreshSelf();
return true;
}
else {
return this.refreshChildren(changedTiddlers);
}
};
refreshWiget.prototype.handleRefreshEvent = function(event) {
var list = {},additionalFields,title;
if(typeof event.paramObject === "object") {
additionalFields = event.paramObject;
title = additionalFields.title;
}
if (title) {
list[title] = {};
list[title]["modified"] = true;
}
this.refreshChildren(list);
return false;//always consume event
};
exports.refresh = refreshWiget;
})();
/*\
title: $:/bj/modules/widgets/setvar.js
type: application/javascript
module-type: widget
setvarWiget -
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var setvarWiget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
setvarWiget.prototype = new Widget();
/*
Render this widget into the DOM
*/
setvarWiget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
setvarWiget.prototype.execute = function() {
// Get our parameters
this.msg=this.getAttribute("msg");
if (this.msg) {
this.eventListeners = {};
this.addEventListeners([
{type: this.msg, handler: "handleSetvarEvent"}
]);
}
// Construct the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
setvarWiget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes["msg"] ) {
this.refreshSelf();
return true;
}
else {
return this.refreshChildren(changedTiddlers);
}
};
setvarWiget.prototype.handleSetvarEvent = function(event) {
var additionalFields,setvar,setval;
if(typeof event.paramObject === "object") {
additionalFields = event.paramObject;
setvar = additionalFields.setvar;
setval = additionalFields.setval;
}
if (setvar && setval)
this.setVariable(setvar,setval);
return true;
};
exports.setvar = setvarWiget;
})();
/*\
title: $:/bj/modules/wikiadapter/norefesh.js
type: application/javascript
module-type: global
overrides for wiki.js
\*/
(function(){
var wiki = require("$:/core/modules/wiki.js");
wiki.oldenqueueTiddlerEvent = wiki.enqueueTiddlerEvent;
wiki.enqueueTiddlerEvent = function(title,isDeleted) {
if (title.substring(0,17) !== "$:/temp/__priv__/") this.oldenqueueTiddlerEvent(title,isDeleted);
};
})();
{{$:/language/OfficialPluginLibrary/Hint}}
[all[]] -[[$:/HistoryList]] -[[$:/StoryList]] -[[$:/Import]] -[[$:/isEncrypted]] -[[$:/UploadName]] -[prefix[$:/state/]] -[prefix[$:/temp/]]
$:/core/ui/DefaultSearchResultList
[is[tiddler]] -[[$:/HistoryList]] -[[$:/Import]] -[[$:/isEncrypted]] -[prefix[$:/status/]] -[prefix[$:/state/]] -[prefix[$:/temp/]]
$:/core/ui/TiddlerInfo/Fields
<div class="tc-control-panel">
<<tabs "[all[shadows+tiddlers]tag[$:/tags/ControlPanel]!has[draft.of]]" "$:/core/ui/ControlPanel/Info">>
</div>
TiddlyWiki created by Jeremy Ruston, (jeremy [at] jermolene [dot] com)
Copyright © Jeremy Ruston 2004-2007
Copyright © UnaMesa Association 2007-2016
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
Neither the name of the UnaMesa Association nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
<svg width="22pt" height="22pt" viewBox="0 0 128 128"><path d="M64 0l54.56 32v64L64 128 9.44 96V32L64 0zm21.127 95.408c-3.578-.103-5.15-.094-6.974-3.152l-1.42.042c-1.653-.075-.964-.04-2.067-.097-1.844-.07-1.548-1.86-1.873-2.8-.52-3.202.687-6.43.65-9.632-.014-1.14-1.593-5.17-2.157-6.61-1.768.34-3.546.406-5.34.497-4.134-.01-8.24-.527-12.317-1.183-.8 3.35-3.16 8.036-1.21 11.44 2.37 3.52 4.03 4.495 6.61 4.707 2.572.212 3.16 3.18 2.53 4.242-.55.73-1.52.864-2.346 1.04l-1.65.08c-1.296-.046-2.455-.404-3.61-.955-1.93-1.097-3.925-3.383-5.406-5.024.345.658.55 1.938.24 2.53-.878 1.27-4.665 1.26-6.4.47-1.97-.89-6.73-7.162-7.468-11.86 1.96-3.78 4.812-7.07 6.255-11.186-3.146-2.05-4.83-5.384-4.61-9.16l.08-.44c-3.097.59-1.49.37-4.82.628-10.608-.032-19.935-7.37-14.68-18.774.34-.673.664-1.287 1.243-.994.466.237.4 1.18.166 2.227-3.005 13.627 11.67 13.732 20.69 11.21.89-.25 2.67-1.936 3.905-2.495 2.016-.91 4.205-1.282 6.376-1.55 5.4-.63 11.893 2.276 15.19 2.37 3.3.096 7.99-.805 10.87-.615 2.09.098 4.143.483 6.16 1.03 1.306-6.49 1.4-11.27 4.492-12.38 1.814.293 3.213 2.818 4.25 4.167 2.112-.086 4.12.46 6.115 1.066 3.61-.522 6.642-2.593 9.833-4.203-3.234 2.69-3.673 7.075-3.303 11.127.138 2.103-.444 4.386-1.164 6.54-1.348 3.507-3.95 7.204-6.97 7.014-1.14-.036-1.805-.695-2.653-1.4-.164 1.427-.81 2.7-1.434 3.96-1.44 2.797-5.203 4.03-8.687 7.016-3.484 2.985 1.114 13.65 2.23 15.594 1.114 1.94 4.226 2.652 3.02 4.406-.37.58-.936.785-1.54 1.01l-.82.11zm-40.097-8.85l.553.14c.694-.27 2.09.15 2.83.353-1.363-1.31-3.417-3.24-4.897-4.46-.485-1.47-.278-2.96-.174-4.46l.02-.123c-.582 1.205-1.322 2.376-1.72 3.645-.465 1.71 2.07 3.557 3.052 4.615l.336.3z" fill-rule="evenodd"/></svg>
<svg class="tc-image-advanced-search-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M74.5651535,87.9848361 C66.9581537,93.0488876 57.8237115,96 48,96 C21.490332,96 0,74.509668 0,48 C0,21.490332 21.490332,0 48,0 C74.509668,0 96,21.490332 96,48 C96,57.8541369 93.0305793,67.0147285 87.9377231,74.6357895 L122.284919,108.982985 C125.978897,112.676963 125.973757,118.65366 122.284271,122.343146 C118.593975,126.033442 112.613238,126.032921 108.92411,122.343793 L74.5651535,87.9848361 Z M48,80 C65.673112,80 80,65.673112 80,48 C80,30.326888 65.673112,16 48,16 C30.326888,16 16,30.326888 16,48 C16,65.673112 30.326888,80 48,80 Z"></path>
<circle cx="48" cy="48" r="8"></circle>
<circle cx="28" cy="48" r="8"></circle>
<circle cx="68" cy="48" r="8"></circle>
</g>
</svg>
<svg class="tc-image-blank tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt"></svg>
<svg class="tc-image-cancel-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<g fill-rule="evenodd">
<path d="M64,76.3137085 L47.0294734,93.2842351 C43.9038742,96.4098343 38.8399231,96.4084656 35.7157288,93.2842712 C32.5978915,90.166434 32.5915506,85.0947409 35.7157649,81.9705266 L52.6862915,65 L35.7157649,48.0294734 C32.5901657,44.9038742 32.5915344,39.8399231 35.7157288,36.7157288 C38.833566,33.5978915 43.9052591,33.5915506 47.0294734,36.7157649 L64,53.6862915 L80.9705266,36.7157649 C84.0961258,33.5901657 89.1600769,33.5915344 92.2842712,36.7157288 C95.4021085,39.833566 95.4084494,44.9052591 92.2842351,48.0294734 L75.3137085,65 L92.2842351,81.9705266 C95.4098343,85.0961258 95.4084656,90.1600769 92.2842712,93.2842712 C89.166434,96.4021085 84.0947409,96.4084494 80.9705266,93.2842351 L64,76.3137085 Z M64,129 C99.346224,129 128,100.346224 128,65 C128,29.653776 99.346224,1 64,1 C28.653776,1 1.13686838e-13,29.653776 1.13686838e-13,65 C1.13686838e-13,100.346224 28.653776,129 64,129 Z M64,113 C90.509668,113 112,91.509668 112,65 C112,38.490332 90.509668,17 64,17 C37.490332,17 16,38.490332 16,65 C16,91.509668 37.490332,113 64,113 Z"></path>
</g>
</svg>
<svg class="tc-image-chevron-down tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd" transform="translate(64.000000, 40.500000) rotate(-270.000000) translate(-64.000000, -40.500000) translate(-22.500000, -26.500000)">
<path d="M112.743107,112.12741 C111.310627,113.561013 109.331747,114.449239 107.145951,114.449239 L27.9777917,114.449239 C23.6126002,114.449239 20.0618714,110.904826 20.0618714,106.532572 C20.0618714,102.169214 23.6059497,98.6159054 27.9777917,98.6159054 L99.2285381,98.6159054 L99.2285381,27.365159 C99.2285381,22.9999675 102.77295,19.4492387 107.145205,19.4492387 C111.508562,19.4492387 115.061871,22.993317 115.061871,27.365159 L115.061871,106.533318 C115.061871,108.71579 114.175869,110.694669 112.743378,112.127981 Z" transform="translate(67.561871, 66.949239) rotate(-45.000000) translate(-67.561871, -66.949239) "></path>
<path d="M151.35638,112.12741 C149.923899,113.561013 147.94502,114.449239 145.759224,114.449239 L66.5910645,114.449239 C62.225873,114.449239 58.6751442,110.904826 58.6751442,106.532572 C58.6751442,102.169214 62.2192225,98.6159054 66.5910645,98.6159054 L137.841811,98.6159054 L137.841811,27.365159 C137.841811,22.9999675 141.386223,19.4492387 145.758478,19.4492387 C150.121835,19.4492387 153.675144,22.993317 153.675144,27.365159 L153.675144,106.533318 C153.675144,108.71579 152.789142,110.694669 151.356651,112.127981 Z" transform="translate(106.175144, 66.949239) rotate(-45.000000) translate(-106.175144, -66.949239) "></path>
</g>
</svg>
<svg class="tc-image-chevron-left tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128" version="1.1">
<g fill-rule="evenodd" transform="translate(92.500000, 64.000000) rotate(-180.000000) translate(-92.500000, -64.000000) translate(6.000000, -3.000000)">
<path d="M112.743107,112.12741 C111.310627,113.561013 109.331747,114.449239 107.145951,114.449239 L27.9777917,114.449239 C23.6126002,114.449239 20.0618714,110.904826 20.0618714,106.532572 C20.0618714,102.169214 23.6059497,98.6159054 27.9777917,98.6159054 L99.2285381,98.6159054 L99.2285381,27.365159 C99.2285381,22.9999675 102.77295,19.4492387 107.145205,19.4492387 C111.508562,19.4492387 115.061871,22.993317 115.061871,27.365159 L115.061871,106.533318 C115.061871,108.71579 114.175869,110.694669 112.743378,112.127981 Z" transform="translate(67.561871, 66.949239) rotate(-45.000000) translate(-67.561871, -66.949239) "></path>
<path d="M151.35638,112.12741 C149.923899,113.561013 147.94502,114.449239 145.759224,114.449239 L66.5910645,114.449239 C62.225873,114.449239 58.6751442,110.904826 58.6751442,106.532572 C58.6751442,102.169214 62.2192225,98.6159054 66.5910645,98.6159054 L137.841811,98.6159054 L137.841811,27.365159 C137.841811,22.9999675 141.386223,19.4492387 145.758478,19.4492387 C150.121835,19.4492387 153.675144,22.993317 153.675144,27.365159 L153.675144,106.533318 C153.675144,108.71579 152.789142,110.694669 151.356651,112.127981 Z" transform="translate(106.175144, 66.949239) rotate(-45.000000) translate(-106.175144, -66.949239) "></path>
</g>
</svg>
<svg class="tc-image-chevron-right tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd" transform="translate(-48.000000, -3.000000)">
<path d="M112.743107,112.12741 C111.310627,113.561013 109.331747,114.449239 107.145951,114.449239 L27.9777917,114.449239 C23.6126002,114.449239 20.0618714,110.904826 20.0618714,106.532572 C20.0618714,102.169214 23.6059497,98.6159054 27.9777917,98.6159054 L99.2285381,98.6159054 L99.2285381,27.365159 C99.2285381,22.9999675 102.77295,19.4492387 107.145205,19.4492387 C111.508562,19.4492387 115.061871,22.993317 115.061871,27.365159 L115.061871,106.533318 C115.061871,108.71579 114.175869,110.694669 112.743378,112.127981 Z" transform="translate(67.561871, 66.949239) rotate(-45.000000) translate(-67.561871, -66.949239) "></path>
<path d="M151.35638,112.12741 C149.923899,113.561013 147.94502,114.449239 145.759224,114.449239 L66.5910645,114.449239 C62.225873,114.449239 58.6751442,110.904826 58.6751442,106.532572 C58.6751442,102.169214 62.2192225,98.6159054 66.5910645,98.6159054 L137.841811,98.6159054 L137.841811,27.365159 C137.841811,22.9999675 141.386223,19.4492387 145.758478,19.4492387 C150.121835,19.4492387 153.675144,22.993317 153.675144,27.365159 L153.675144,106.533318 C153.675144,108.71579 152.789142,110.694669 151.356651,112.127981 Z" transform="translate(106.175144, 66.949239) rotate(-45.000000) translate(-106.175144, -66.949239) "></path>
</g>
</svg>
<svg class="tc-image-chevron-up tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd" transform="translate(64.000000, 89.500000) rotate(-90.000000) translate(-64.000000, -89.500000) translate(-22.500000, 22.500000)">
<path d="M112.743107,112.12741 C111.310627,113.561013 109.331747,114.449239 107.145951,114.449239 L27.9777917,114.449239 C23.6126002,114.449239 20.0618714,110.904826 20.0618714,106.532572 C20.0618714,102.169214 23.6059497,98.6159054 27.9777917,98.6159054 L99.2285381,98.6159054 L99.2285381,27.365159 C99.2285381,22.9999675 102.77295,19.4492387 107.145205,19.4492387 C111.508562,19.4492387 115.061871,22.993317 115.061871,27.365159 L115.061871,106.533318 C115.061871,108.71579 114.175869,110.694669 112.743378,112.127981 Z" transform="translate(67.561871, 66.949239) rotate(-45.000000) translate(-67.561871, -66.949239) "></path>
<path d="M151.35638,112.12741 C149.923899,113.561013 147.94502,114.449239 145.759224,114.449239 L66.5910645,114.449239 C62.225873,114.449239 58.6751442,110.904826 58.6751442,106.532572 C58.6751442,102.169214 62.2192225,98.6159054 66.5910645,98.6159054 L137.841811,98.6159054 L137.841811,27.365159 C137.841811,22.9999675 141.386223,19.4492387 145.758478,19.4492387 C150.121835,19.4492387 153.675144,22.993317 153.675144,27.365159 L153.675144,106.533318 C153.675144,108.71579 152.789142,110.694669 151.356651,112.127981 Z" transform="translate(106.175144, 66.949239) rotate(-45.000000) translate(-106.175144, -66.949239) "></path>
</g>
</svg>
<svg class="tc-clone-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M32.2650915,96 L32.2650915,120.002359 C32.2650915,124.419334 35.8432884,128 40.2627323,128 L120.002359,128 C124.419334,128 128,124.421803 128,120.002359 L128,40.2627323 C128,35.8457573 124.421803,32.2650915 120.002359,32.2650915 L96,32.2650915 L96,48 L108.858899,48 C110.519357,48 111.853018,49.3405131 111.853018,50.9941198 L111.853018,108.858899 C111.853018,110.519357 110.512505,111.853018 108.858899,111.853018 L50.9941198,111.853018 C49.333661,111.853018 48,110.512505 48,108.858899 L48,96 L32.2650915,96 Z"></path>
<path d="M40,56 L32.0070969,56 C27.5881712,56 24,52.418278 24,48 C24,43.5907123 27.5848994,40 32.0070969,40 L40,40 L40,32.0070969 C40,27.5881712 43.581722,24 48,24 C52.4092877,24 56,27.5848994 56,32.0070969 L56,40 L63.9929031,40 C68.4118288,40 72,43.581722 72,48 C72,52.4092877 68.4151006,56 63.9929031,56 L56,56 L56,63.9929031 C56,68.4118288 52.418278,72 48,72 C43.5907123,72 40,68.4151006 40,63.9929031 L40,56 Z M7.9992458,0 C3.58138434,0 0,3.5881049 0,7.9992458 L0,88.0007542 C0,92.4186157 3.5881049,96 7.9992458,96 L88.0007542,96 C92.4186157,96 96,92.4118951 96,88.0007542 L96,7.9992458 C96,3.58138434 92.4118951,0 88.0007542,0 L7.9992458,0 Z M19.0010118,16 C17.3435988,16 16,17.336731 16,19.0010118 L16,76.9989882 C16,78.6564012 17.336731,80 19.0010118,80 L76.9989882,80 C78.6564012,80 80,78.663269 80,76.9989882 L80,19.0010118 C80,17.3435988 78.663269,16 76.9989882,16 L19.0010118,16 Z"></path>
</g>
</svg>
<svg class="tc-close-all-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd" transform="translate(-23.000000, -23.000000)">
<path d="M43,131 L22.9976794,131 C18.5827987,131 15,127.418278 15,123 C15,118.590712 18.5806831,115 22.9976794,115 L43,115 L43,94.9976794 C43,90.5827987 46.581722,87 51,87 C55.4092877,87 59,90.5806831 59,94.9976794 L59,115 L79.0023206,115 C83.4172013,115 87,118.581722 87,123 C87,127.409288 83.4193169,131 79.0023206,131 L59,131 L59,151.002321 C59,155.417201 55.418278,159 51,159 C46.5907123,159 43,155.419317 43,151.002321 L43,131 Z" transform="translate(51.000000, 123.000000) rotate(-45.000000) translate(-51.000000, -123.000000) "></path>
<path d="M43,59 L22.9976794,59 C18.5827987,59 15,55.418278 15,51 C15,46.5907123 18.5806831,43 22.9976794,43 L43,43 L43,22.9976794 C43,18.5827987 46.581722,15 51,15 C55.4092877,15 59,18.5806831 59,22.9976794 L59,43 L79.0023206,43 C83.4172013,43 87,46.581722 87,51 C87,55.4092877 83.4193169,59 79.0023206,59 L59,59 L59,79.0023206 C59,83.4172013 55.418278,87 51,87 C46.5907123,87 43,83.4193169 43,79.0023206 L43,59 Z" transform="translate(51.000000, 51.000000) rotate(-45.000000) translate(-51.000000, -51.000000) "></path>
<path d="M115,59 L94.9976794,59 C90.5827987,59 87,55.418278 87,51 C87,46.5907123 90.5806831,43 94.9976794,43 L115,43 L115,22.9976794 C115,18.5827987 118.581722,15 123,15 C127.409288,15 131,18.5806831 131,22.9976794 L131,43 L151.002321,43 C155.417201,43 159,46.581722 159,51 C159,55.4092877 155.419317,59 151.002321,59 L131,59 L131,79.0023206 C131,83.4172013 127.418278,87 123,87 C118.590712,87 115,83.4193169 115,79.0023206 L115,59 Z" transform="translate(123.000000, 51.000000) rotate(-45.000000) translate(-123.000000, -51.000000) "></path>
<path d="M115,131 L94.9976794,131 C90.5827987,131 87,127.418278 87,123 C87,118.590712 90.5806831,115 94.9976794,115 L115,115 L115,94.9976794 C115,90.5827987 118.581722,87 123,87 C127.409288,87 131,90.5806831 131,94.9976794 L131,115 L151.002321,115 C155.417201,115 159,118.581722 159,123 C159,127.409288 155.419317,131 151.002321,131 L131,131 L131,151.002321 C131,155.417201 127.418278,159 123,159 C118.590712,159 115,155.419317 115,151.002321 L115,131 Z" transform="translate(123.000000, 123.000000) rotate(-45.000000) translate(-123.000000, -123.000000) "></path>
</g>
</svg>
<svg class="tc-image-close-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<g fill-rule="evenodd">
<path d="M65.0864256,75.4091629 L14.9727349,125.522854 C11.8515951,128.643993 6.78104858,128.64922 3.65685425,125.525026 C0.539017023,122.407189 0.5336324,117.334539 3.65902635,114.209145 L53.7727171,64.0954544 L3.65902635,13.9817637 C0.537886594,10.8606239 0.532659916,5.79007744 3.65685425,2.6658831 C6.77469148,-0.451954124 11.8473409,-0.457338747 14.9727349,2.66805521 L65.0864256,52.7817459 L115.200116,2.66805521 C118.321256,-0.453084553 123.391803,-0.458311231 126.515997,2.6658831 C129.633834,5.78372033 129.639219,10.8563698 126.513825,13.9817637 L76.4001341,64.0954544 L126.513825,114.209145 C129.634965,117.330285 129.640191,122.400831 126.515997,125.525026 C123.39816,128.642863 118.32551,128.648248 115.200116,125.522854 L65.0864256,75.4091629 L65.0864256,75.4091629 Z"></path>
</g>
</svg>
<svg class="tc-image-close-others-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M64,128 C99.346224,128 128,99.346224 128,64 C128,28.653776 99.346224,0 64,0 C28.653776,0 0,28.653776 0,64 C0,99.346224 28.653776,128 64,128 Z M64,112 C90.509668,112 112,90.509668 112,64 C112,37.490332 90.509668,16 64,16 C37.490332,16 16,37.490332 16,64 C16,90.509668 37.490332,112 64,112 Z M64,96 C81.673112,96 96,81.673112 96,64 C96,46.326888 81.673112,32 64,32 C46.326888,32 32,46.326888 32,64 C32,81.673112 46.326888,96 64,96 Z M64,80 C72.836556,80 80,72.836556 80,64 C80,55.163444 72.836556,48 64,48 C55.163444,48 48,55.163444 48,64 C48,72.836556 55.163444,80 64,80 Z"></path>
</g>
</svg>
<svg class="tc-image-delete-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<g fill-rule="evenodd" transform="translate(12.000000, 0.000000)">
<rect x="0" y="11" width="105" height="16" rx="8"></rect>
<rect x="28" y="0" width="48" height="16" rx="8"></rect>
<rect x="8" y="16" width="16" height="112" rx="8"></rect>
<rect x="8" y="112" width="88" height="16" rx="8"></rect>
<rect x="80" y="16" width="16" height="112" rx="8"></rect>
<rect x="56" y="16" width="16" height="112" rx="8"></rect>
<rect x="32" y="16" width="16" height="112" rx="8"></rect>
</g>
</svg>
<svg class="tc-image-done-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<g fill-rule="evenodd">
<path d="M3.52445141,76.8322939 C2.07397484,75.3828178 1.17514421,73.3795385 1.17514421,71.1666288 L1.17514421,23.1836596 C1.17514421,18.7531992 4.75686621,15.1751442 9.17514421,15.1751442 C13.5844319,15.1751442 17.1751442,18.7606787 17.1751442,23.1836596 L17.1751442,63.1751442 L119.173716,63.1751442 C123.590457,63.1751442 127.175144,66.7568662 127.175144,71.1751442 C127.175144,75.5844319 123.592783,79.1751442 119.173716,79.1751442 L9.17657227,79.1751442 C6.96796403,79.1751442 4.9674142,78.279521 3.51911285,76.8315312 Z" id="Rectangle-285" transform="translate(64.175144, 47.175144) rotate(-45.000000) translate(-64.175144, -47.175144) "></path>
</g>
</svg>
<svg class="tc-image-down-arrow tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<path d="M109.35638,81.3533152 C107.923899,82.7869182 105.94502,83.6751442 103.759224,83.6751442 L24.5910645,83.6751442 C20.225873,83.6751442 16.6751442,80.1307318 16.6751442,75.7584775 C16.6751442,71.3951199 20.2192225,67.8418109 24.5910645,67.8418109 L95.8418109,67.8418109 L95.8418109,-3.40893546 C95.8418109,-7.77412698 99.3862233,-11.3248558 103.758478,-11.3248558 C108.121835,-11.3248558 111.675144,-7.78077754 111.675144,-3.40893546 L111.675144,75.7592239 C111.675144,77.9416955 110.789142,79.9205745 109.356651,81.3538862 Z" transform="translate(64.175144, 36.175144) rotate(45.000000) translate(-64.175144, -36.175144) "></path>
</svg>
<svg class="tc-image-download-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128"><g fill-rule="evenodd"><path class="tc-image-download-button-ring" d="M64,128 C99.346224,128 128,99.346224 128,64 C128,28.653776 99.346224,0 64,0 C28.653776,0 0,28.653776 0,64 C0,99.346224 28.653776,128 64,128 Z M64,112 C90.509668,112 112,90.509668 112,64 C112,37.490332 90.509668,16 64,16 C37.490332,16 16,37.490332 16,64 C16,90.509668 37.490332,112 64,112 Z"/><path d="M34.3496823,66.4308767 L61.2415823,93.634668 C63.0411536,95.4551107 65.9588502,95.4551107 67.7584215,93.634668 L94.6503215,66.4308767 C96.4498928,64.610434 96.4498928,61.6588981 94.6503215,59.8384554 C93.7861334,58.9642445 92.6140473,58.4731195 91.3919019,58.4731195 L82.9324098,58.4731195 C80.3874318,58.4731195 78.3243078,56.3860674 78.3243078,53.8115729 L78.3243078,38.6615466 C78.3243078,36.0870521 76.2611837,34 73.7162058,34 L55.283798,34 C52.7388201,34 50.675696,36.0870521 50.675696,38.6615466 L50.675696,38.6615466 L50.675696,53.8115729 C50.675696,56.3860674 48.612572,58.4731195 46.0675941,58.4731195 L37.608102,58.4731195 C35.063124,58.4731195 33,60.5601716 33,63.134666 C33,64.3709859 33.4854943,65.5566658 34.3496823,66.4308767 L34.3496823,66.4308767 Z"/></g></svg>
<svg class="tc-image-edit-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<g fill-rule="evenodd">
<path d="M116.870058,45.3431458 L108.870058,45.3431458 L108.870058,45.3431458 L108.870058,61.3431458 L116.870058,61.3431458 L116.870058,45.3431458 Z M124.870058,45.3431458 L127.649881,45.3431458 C132.066101,45.3431458 135.656854,48.9248678 135.656854,53.3431458 C135.656854,57.7524334 132.07201,61.3431458 127.649881,61.3431458 L124.870058,61.3431458 L124.870058,45.3431458 Z M100.870058,45.3431458 L15.6638275,45.3431458 C15.5064377,45.3431458 15.3501085,45.3476943 15.1949638,45.3566664 L15.1949638,45.3566664 C15.0628002,45.3477039 14.928279,45.3431458 14.7913977,45.3431458 C6.68160973,45.3431458 -8.34314575,53.3431458 -8.34314575,53.3431458 C-8.34314575,53.3431458 6.85614548,61.3431458 14.7913977,61.3431458 C14.9266533,61.3431458 15.0596543,61.3384973 15.190398,61.3293588 C15.3470529,61.3385075 15.5049057,61.3431458 15.6638275,61.3431458 L100.870058,61.3431458 L100.870058,45.3431458 L100.870058,45.3431458 Z" transform="translate(63.656854, 53.343146) rotate(-45.000000) translate(-63.656854, -53.343146) "></path>
<path d="M35.1714596,124.189544 C41.9594858,123.613403 49.068777,121.917633 58.85987,118.842282 C60.6854386,118.268877 62.4306907,117.705515 65.1957709,116.802278 C81.1962861,111.575575 87.0734839,109.994907 93.9414474,109.655721 C102.29855,109.242993 107.795169,111.785371 111.520478,118.355045 C112.610163,120.276732 115.051363,120.951203 116.97305,119.861518 C118.894737,118.771832 119.569207,116.330633 118.479522,114.408946 C113.146151,105.003414 104.734907,101.112919 93.5468356,101.66546 C85.6716631,102.054388 79.4899908,103.716944 62.7116783,109.197722 C59.9734132,110.092199 58.2519873,110.64787 56.4625698,111.20992 C37.002649,117.322218 25.6914684,118.282267 16.8654804,112.957098 C14.9739614,111.815848 12.5154166,112.424061 11.3741667,114.31558 C10.2329168,116.207099 10.84113,118.665644 12.7326489,119.806894 C19.0655164,123.627836 26.4866335,124.926678 35.1714596,124.189544 Z"></path>
</g>
</svg>
<svg class="tc-image-export-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M8.00348646,127.999999 C8.00464867,128 8.00581094,128 8.00697327,128 L119.993027,128 C122.205254,128 124.207939,127.101378 125.657096,125.651198 L125.656838,125.65759 C127.104563,124.210109 128,122.21009 128,119.999949 L128,56.0000511 C128,51.5817449 124.409288,48 120,48 C115.581722,48 112,51.5797863 112,56.0000511 L112,112 L16,112 L16,56.0000511 C16,51.5817449 12.4092877,48 8,48 C3.581722,48 7.10542736e-15,51.5797863 7.10542736e-15,56.0000511 L7.10542736e-15,119.999949 C7.10542736e-15,124.418255 3.59071231,128 8,128 C8.00116233,128 8.0023246,128 8.00348681,127.999999 Z M56.6235633,27.3113724 L47.6580188,36.2769169 C44.5333664,39.4015692 39.4634864,39.4061295 36.339292,36.2819351 C33.2214548,33.1640979 33.2173444,28.0901742 36.3443103,24.9632084 L58.9616908,2.34582788 C60.5248533,0.782665335 62.5748436,0.000361191261 64.624516,2.38225238e-14 L64.6193616,0.00151809229 C66.6695374,0.000796251595 68.7211167,0.781508799 70.2854358,2.34582788 L92.9028163,24.9632084 C96.0274686,28.0878607 96.0320289,33.1577408 92.9078345,36.2819351 C89.7899973,39.3997724 84.7160736,39.4038827 81.5891078,36.2769169 L72.6235633,27.3113724 L72.6235633,88.5669606 C72.6235633,92.9781015 69.0418413,96.5662064 64.6235633,96.5662064 C60.2142756,96.5662064 56.6235633,92.984822 56.6235633,88.5669606 L56.6235633,27.3113724 L56.6235633,27.3113724 Z"></path>
</g>
</svg>
<svg class="tc-image-file tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="nonzero">
<path d="M111.96811,30.5 L112,30.5 L112,119.999079 C112,124.417866 108.419113,128 104.000754,128 L23.9992458,128 C19.5813843,128 16,124.417687 16,119.999079 L16,8.00092105 C16,3.58213437 19.5808867,0 23.9992458,0 L81,0 L81,0.0201838424 C83.1589869,-0.071534047 85.3482153,0.707077645 86.9982489,2.35711116 L109.625176,24.9840387 C111.151676,26.510538 111.932942,28.4998414 111.96811,30.5 L111.96811,30.5 Z M81,8 L24,8 L24,120 L104,120 L104,30.5 L89.0003461,30.5 C84.5818769,30.5 81,26.9216269 81,22.4996539 L81,8 Z"></path>
<rect x="32" y="36" width="64" height="8" rx="8"></rect>
<rect x="32" y="52" width="64" height="8" rx="8"></rect>
<rect x="32" y="68" width="64" height="8" rx="8"></rect>
<rect x="32" y="84" width="64" height="8" rx="8"></rect>
<rect x="32" y="100" width="64" height="8" rx="8"></rect>
<rect x="32" y="20" width="40" height="8" rx="8"></rect>
</g>
</svg>
<svg class="tc-image-fold-all tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<rect x="0" y="0" width="128" height="16" rx="8"></rect>
<rect x="0" y="64" width="128" height="16" rx="8"></rect>
<path d="M64.0292774,58.6235628 C61.9791013,58.6242848 59.9275217,57.8435723 58.3632024,56.279253 L35.7458219,33.6618725 C32.6211696,30.5372202 32.6166093,25.4673401 35.7408036,22.3431458 C38.8586409,19.2253085 43.9325646,19.2211982 47.0595304,22.348164 L64.0250749,39.3137085 L80.9906194,22.348164 C84.1152717,19.2235117 89.1851518,19.2189514 92.3093461,22.3431458 C95.4271834,25.460983 95.4312937,30.5349067 92.3043279,33.6618725 L69.6869474,56.279253 C68.1237851,57.8424153 66.0737951,58.6247195 64.0241231,58.6250809 Z" transform="translate(64.024316, 39.313708) scale(1, -1) translate(-64.024316, -39.313708) "></path>
<path d="M64.0292774,123.621227 C61.9791013,123.621949 59.9275217,122.841236 58.3632024,121.276917 L35.7458219,98.6595365 C32.6211696,95.5348842 32.6166093,90.4650041 35.7408036,87.3408098 C38.8586409,84.2229725 43.9325646,84.2188622 47.0595304,87.345828 L64.0250749,104.311373 L80.9906194,87.345828 C84.1152717,84.2211757 89.1851518,84.2166154 92.3093461,87.3408098 C95.4271834,90.458647 95.4312937,95.5325707 92.3043279,98.6595365 L69.6869474,121.276917 C68.1237851,122.840079 66.0737951,123.622383 64.0241231,123.622745 Z" transform="translate(64.024316, 104.311372) scale(1, -1) translate(-64.024316, -104.311372) "></path>
</g>
</svg>
<svg class="tc-image-fold tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<rect x="0" y="0" width="128" height="16" rx="8"></rect>
<path d="M64.0292774,63.6235628 C61.9791013,63.6242848 59.9275217,62.8435723 58.3632024,61.279253 L35.7458219,38.6618725 C32.6211696,35.5372202 32.6166093,30.4673401 35.7408036,27.3431458 C38.8586409,24.2253085 43.9325646,24.2211982 47.0595304,27.348164 L64.0250749,44.3137085 L80.9906194,27.348164 C84.1152717,24.2235117 89.1851518,24.2189514 92.3093461,27.3431458 C95.4271834,30.460983 95.4312937,35.5349067 92.3043279,38.6618725 L69.6869474,61.279253 C68.1237851,62.8424153 66.0737951,63.6247195 64.0241231,63.6250809 Z" transform="translate(64.024316, 44.313708) scale(1, -1) translate(-64.024316, -44.313708) "></path>
<path d="M64.0049614,105.998482 C61.9547853,105.999204 59.9032057,105.218491 58.3388864,103.654172 L35.7215059,81.0367916 C32.5968535,77.9121393 32.5922933,72.8422592 35.7164876,69.7180649 C38.8343248,66.6002276 43.9082485,66.5961173 47.0352144,69.7230831 L64.0007589,86.6886276 L80.9663034,69.7230831 C84.0909557,66.5984308 89.1608358,66.5938705 92.2850301,69.7180649 C95.4028673,72.8359021 95.4069777,77.9098258 92.2800119,81.0367916 L69.6626314,103.654172 C68.099469,105.217334 66.0494791,105.999639 63.999807,106 Z" transform="translate(64.000000, 86.688628) scale(1, -1) translate(-64.000000, -86.688628) "></path>
</g>
</svg>
<svg class="tc-image-fold-others tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<rect x="0" y="56.0314331" width="128" height="16" rx="8"></rect>
<path d="M101.657101,104.948818 C100.207918,103.498614 98.2051847,102.599976 95.9929031,102.599976 L72,102.599976 L72,78.6070725 C72,76.3964271 71.1036108,74.3936927 69.6545293,72.9441002 L69.6571005,72.9488183 C68.2079177,71.4986143 66.2051847,70.5999756 63.9929031,70.5999756 L32.0070969,70.5999756 C27.5881712,70.5999756 24,74.1816976 24,78.5999756 C24,83.0092633 27.5848994,86.5999756 32.0070969,86.5999756 L56,86.5999756 L56,110.592879 C56,112.803524 56.8963895,114.806259 58.3454713,116.255852 L58.3429,116.251133 C59.7920828,117.701337 61.7948156,118.599976 64.0070969,118.599976 L88,118.599976 L88,142.592879 C88,147.011804 91.581722,150.599976 96,150.599976 C100.409288,150.599976 104,147.015076 104,142.592879 L104,110.607072 C104,108.396427 103.103611,106.393693 101.654529,104.9441 Z" transform="translate(64.000000, 110.599976) rotate(-45.000000) translate(-64.000000, -110.599976) "></path>
<path d="M101.725643,11.7488671 C100.27646,10.2986632 98.2737272,9.40002441 96.0614456,9.40002441 L72.0685425,9.40002441 L72.0685425,-14.5928787 C72.0685425,-16.8035241 71.1721533,-18.8062584 69.7230718,-20.255851 L69.725643,-20.2511329 C68.2764602,-21.7013368 66.2737272,-22.5999756 64.0614456,-22.5999756 L32.0756394,-22.5999756 C27.6567137,-22.5999756 24.0685425,-19.0182536 24.0685425,-14.5999756 C24.0685425,-10.1906879 27.6534419,-6.59997559 32.0756394,-6.59997559 L56.0685425,-6.59997559 L56.0685425,17.3929275 C56.0685425,19.6035732 56.964932,21.6063078 58.4140138,23.0559004 L58.4114425,23.0511823 C59.8606253,24.5013859 61.8633581,25.4000244 64.0756394,25.4000244 L88.0685425,25.4000244 L88.0685425,49.3929275 C88.0685425,53.8118532 91.6502645,57.4000244 96.0685425,57.4000244 C100.47783,57.4000244 104.068542,53.815125 104.068542,49.3929275 L104.068542,17.4071213 C104.068542,15.1964759 103.172153,13.1937416 101.723072,11.744149 Z" transform="translate(64.068542, 17.400024) scale(1, -1) rotate(-45.000000) translate(-64.068542, -17.400024) "></path>
</g>
</svg>
<svg class="tc-image-folder tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M55.6943257,128.000004 L7.99859666,128.000004 C3.5810937,128.000004 0,124.413822 0,119.996384 L0,48.0036243 C0,43.5833471 3.58387508,40.0000044 7.99859666,40.0000044 L16,40.0000044 L16,31.9999914 C16,27.5817181 19.5783731,24 24.0003461,24 L55.9996539,24 C60.4181231,24 64,27.5800761 64,31.9999914 L64,40.0000044 L104.001403,40.0000044 C108.418906,40.0000044 112,43.5861868 112,48.0036243 L112,59.8298353 L104,59.7475921 L104,51.9994189 C104,49.7887607 102.207895,48.0000044 99.9972215,48.0000044 L56,48.0000044 L56,36.0000255 C56,33.7898932 54.2072328,32 51.9957423,32 L28.0042577,32 C25.7890275,32 24,33.7908724 24,36.0000255 L24,48.0000044 L12.0027785,48.0000044 C9.78987688,48.0000044 8,49.7906032 8,51.9994189 L8,116.00059 C8,118.211248 9.79210499,120.000004 12.0027785,120.000004 L58.7630167,120.000004 L55.6943257,128.000004 L55.6943257,128.000004 Z"></path>
<path d="M23.8728955,55.5 L119.875702,55.5 C124.293205,55.5 126.87957,59.5532655 125.650111,64.5630007 L112.305967,118.936999 C111.077582,123.942356 106.497904,128 102.083183,128 L6.08037597,128 C1.66287302,128 -0.923492342,123.946735 0.305967145,118.936999 L13.650111,64.5630007 C14.878496,59.5576436 19.4581739,55.5 23.8728955,55.5 L23.8728955,55.5 L23.8728955,55.5 Z M25.6530124,64 L113.647455,64 C115.858129,64 117.151473,66.0930612 116.538306,68.6662267 L105.417772,115.333773 C104.803671,117.910859 102.515967,120 100.303066,120 L12.3086228,120 C10.0979492,120 8.8046054,117.906939 9.41777189,115.333773 L20.5383062,68.6662267 C21.1524069,66.0891409 23.4401107,64 25.6530124,64 L25.6530124,64 L25.6530124,64 Z"></path>
</g>
</svg>
<svg class="tc-image-full-screen-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g>
<g>
<path d="M5.29777586e-31,8 C1.59060409e-15,3.581722 3.581722,0 8,0 L40,0 C44.418278,0 48,3.581722 48,8 C48,12.418278 44.418278,16 40,16 L16,16 L16,40 C16,44.418278 12.418278,48 8,48 C3.581722,48 -3.55271368e-15,44.418278 0,40 L3.55271368e-15,8 Z"></path>
</g>
<g transform="translate(104.000000, 104.000000) rotate(-180.000000) translate(-104.000000, -104.000000) translate(80.000000, 80.000000)">
<path d="M5.29777586e-31,8 C1.59060409e-15,3.581722 3.581722,0 8,0 L40,0 C44.418278,0 48,3.581722 48,8 C48,12.418278 44.418278,16 40,16 L16,16 L16,40 C16,44.418278 12.418278,48 8,48 C3.581722,48 -3.55271368e-15,44.418278 0,40 L3.55271368e-15,8 Z"></path>
</g>
<g transform="translate(24.000000, 104.000000) rotate(-90.000000) translate(-24.000000, -104.000000) translate(0.000000, 80.000000)">
<path d="M5.29777586e-31,8 C1.59060409e-15,3.581722 3.581722,0 8,0 L40,0 C44.418278,0 48,3.581722 48,8 C48,12.418278 44.418278,16 40,16 L16,16 L16,40 C16,44.418278 12.418278,48 8,48 C3.581722,48 -3.55271368e-15,44.418278 0,40 L3.55271368e-15,8 Z"></path>
</g>
<g transform="translate(104.000000, 24.000000) rotate(90.000000) translate(-104.000000, -24.000000) translate(80.000000, 0.000000)">
<path d="M5.29777586e-31,8 C1.59060409e-15,3.581722 3.581722,0 8,0 L40,0 C44.418278,0 48,3.581722 48,8 C48,12.418278 44.418278,16 40,16 L16,16 L16,40 C16,44.418278 12.418278,48 8,48 C3.581722,48 -3.55271368e-15,44.418278 0,40 L3.55271368e-15,8 Z"></path>
</g>
</g>
</svg>
<svg class="tc-image-github tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M63.9383506,1.60695328 C28.6017227,1.60695328 -0.055756057,30.2970814 -0.055756057,65.6906208 C-0.055756057,94.003092 18.2804728,118.019715 43.7123154,126.493393 C46.9143781,127.083482 48.0812647,125.104717 48.0812647,123.405261 C48.0812647,121.886765 48.02626,117.85449 47.9948287,112.508284 C30.1929317,116.379268 26.4368926,103.916587 26.4368926,103.916587 C23.5255693,96.5129372 19.3294921,94.5420399 19.3294921,94.5420399 C13.5186324,90.5687739 19.7695302,90.6474524 19.7695302,90.6474524 C26.1933001,91.099854 29.5721638,97.2525155 29.5721638,97.2525155 C35.2808718,107.044059 44.5531024,104.215566 48.1991321,102.575118 C48.7806109,98.4366275 50.4346826,95.612068 52.2616263,94.0109598 C38.0507543,92.3941159 23.1091047,86.8944862 23.1091047,62.3389152 C23.1091047,55.3443933 25.6039634,49.6205298 29.6978889,45.1437211 C29.0378318,43.5229433 26.8415704,37.0044266 30.3265147,28.1845627 C30.3265147,28.1845627 35.6973364,26.4615028 47.9241083,34.7542205 C53.027764,33.330139 58.5046663,32.6220321 63.9462084,32.5944947 C69.3838216,32.6220321 74.856795,33.330139 79.9683085,34.7542205 C92.1872225,26.4615028 97.5501864,28.1845627 97.5501864,28.1845627 C101.042989,37.0044266 98.8467271,43.5229433 98.190599,45.1437211 C102.292382,49.6205298 104.767596,55.3443933 104.767596,62.3389152 C104.767596,86.9574291 89.8023734,92.3744463 75.5482834,93.9598188 C77.8427675,95.9385839 79.8897303,99.8489072 79.8897303,105.828476 C79.8897303,114.392635 79.8111521,121.304544 79.8111521,123.405261 C79.8111521,125.120453 80.966252,127.114954 84.2115327,126.489459 C109.623731,117.996111 127.944244,93.9952241 127.944244,65.6906208 C127.944244,30.2970814 99.2867652,1.60695328 63.9383506,1.60695328"></path>
</g>
</svg>
<svg class="tc-image-globe tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M72.8111354,37.1275855 C72.8111354,37.9789875 72.8111354,38.8303894 72.8111354,39.6817913 C72.8111354,41.8784743 73.7885604,46.5631866 72.8111354,48.5143758 C71.3445471,51.4420595 68.1617327,52.0543531 66.4170946,54.3812641 C65.2352215,55.9575873 61.7987417,64.9821523 62.7262858,67.3005778 C66.6959269,77.2228204 74.26087,70.4881886 80.6887657,76.594328 C81.5527211,77.415037 83.5758191,78.8666631 83.985137,79.8899578 C87.2742852,88.1128283 76.4086873,94.8989524 87.7419325,106.189751 C88.9872885,107.430443 91.555495,102.372895 91.8205061,101.575869 C92.6726866,99.0129203 98.5458765,96.1267309 100.908882,94.5234439 C102.928056,93.1534443 105.782168,91.8557166 107.236936,89.7775886 C109.507391,86.5342557 108.717505,82.2640435 110.334606,79.0328716 C112.473794,74.7585014 114.163418,69.3979002 116.332726,65.0674086 C120.230862,57.2857361 121.054075,67.1596684 121.400359,67.5059523 C121.757734,67.8633269 122.411167,67.5059523 122.916571,67.5059523 C123.011132,67.5059523 124.364019,67.6048489 124.432783,67.5059523 C125.0832,66.5705216 123.390209,49.5852316 123.114531,48.2089091 C121.710578,41.1996597 116.17083,32.4278331 111.249523,27.7092761 C104.975994,21.6942076 104.160516,11.5121686 92.9912146,12.7547535 C92.7872931,12.7774397 87.906794,22.9027026 85.2136766,26.2672064 C81.486311,30.9237934 82.7434931,22.1144904 78.6876623,22.1144904 C78.6065806,22.1144904 77.5045497,22.0107615 77.4353971,22.1144904 C76.8488637,22.9942905 75.9952305,26.0101404 75.1288269,26.5311533 C74.8635477,26.6906793 73.4071369,26.2924966 73.2826811,26.5311533 C71.0401728,30.8313939 81.5394677,28.7427264 79.075427,34.482926 C76.7225098,39.9642538 72.747373,32.4860199 72.747373,43.0434079"></path>
<path d="M44.4668556,7.01044608 C54.151517,13.1403033 45.1489715,19.2084878 47.1611905,23.2253896 C48.8157833,26.5283781 51.4021933,28.6198851 48.8753629,33.038878 C46.8123257,36.6467763 42.0052989,37.0050492 39.251679,39.7621111 C36.2115749,42.8060154 33.7884281,48.7028116 32.4624592,52.6732691 C30.8452419,57.5158356 47.0088721,59.5388126 44.5246867,63.6811917 C43.1386839,65.9923513 37.7785192,65.1466282 36.0880227,63.8791519 C34.9234453,63.0059918 32.4946425,63.3331166 31.6713597,62.0997342 C29.0575851,58.1839669 29.4107339,54.0758543 28.0457962,49.9707786 C27.1076833,47.1493864 21.732611,47.8501656 20.2022714,49.3776393 C19.6790362,49.8998948 19.8723378,51.1703278 19.8723378,51.8829111 C19.8723378,57.1682405 26.9914913,55.1986414 26.9914913,58.3421973 C26.9914913,72.9792302 30.9191897,64.8771867 38.1313873,69.6793121 C48.1678018,76.3618966 45.9763926,76.981595 53.0777543,84.0829567 C56.7511941,87.7563965 60.8192437,87.7689005 62.503478,93.3767069 C64.1046972,98.7081071 53.1759798,98.7157031 50.786754,100.825053 C49.663965,101.816317 47.9736094,104.970571 46.5680513,105.439676 C44.7757187,106.037867 43.334221,105.93607 41.6242359,107.219093 C39.1967302,109.040481 37.7241465,112.151588 37.6034934,112.030935 C35.4555278,109.88297 34.0848666,96.5511248 33.7147244,93.7726273 C33.1258872,89.3524817 28.1241923,88.2337027 26.7275443,84.7420826 C25.1572737,80.8164061 28.2518481,75.223612 25.599097,70.9819941 C19.0797019,60.557804 13.7775712,56.4811506 10.2493953,44.6896152 C9.3074899,41.5416683 13.5912267,38.1609942 15.1264825,35.8570308 C17.0029359,33.0410312 17.7876232,30.0028946 19.8723378,27.2224065 C22.146793,24.1888519 40.8551166,9.46076832 43.8574051,8.63490613 L44.4668556,7.01044608 Z"></path>
<path d="M64,126 C98.2416545,126 126,98.2416545 126,64 C126,29.7583455 98.2416545,2 64,2 C29.7583455,2 2,29.7583455 2,64 C2,98.2416545 29.7583455,126 64,126 Z M64,120 C94.927946,120 120,94.927946 120,64 C120,33.072054 94.927946,8 64,8 C33.072054,8 8,33.072054 8,64 C8,94.927946 33.072054,120 64,120 Z"></path>
</g>
</svg>
<svg class="tc-image-help tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M36.0548906,111.44117 C30.8157418,115.837088 20.8865444,118.803477 9.5,118.803477 C7.86465619,118.803477 6.25937294,118.742289 4.69372699,118.624467 C12.612543,115.984876 18.7559465,110.02454 21.0611049,102.609942 C8.74739781,92.845129 1.04940554,78.9359851 1.04940554,63.5 C1.04940554,33.9527659 29.2554663,10 64.0494055,10 C98.8433448,10 127.049406,33.9527659 127.049406,63.5 C127.049406,93.0472341 98.8433448,117 64.0494055,117 C53.9936953,117 44.48824,114.999337 36.0548906,111.44117 L36.0548906,111.44117 Z M71.4042554,77.5980086 C71.406883,77.2865764 71.4095079,76.9382011 71.4119569,76.5610548 C71.4199751,75.3262169 71.4242825,74.0811293 71.422912,72.9158546 C71.4215244,71.736154 71.4143321,70.709635 71.4001396,69.8743525 C71.4078362,68.5173028 71.9951951,67.7870427 75.1273009,65.6385471 C75.2388969,65.5619968 76.2124091,64.8981068 76.5126553,64.6910879 C79.6062455,62.5580654 81.5345849,60.9050204 83.2750652,58.5038955 C85.6146327,55.2762841 86.8327108,51.426982 86.8327108,46.8554323 C86.8327108,33.5625756 76.972994,24.9029551 65.3778484,24.9029551 C54.2752771,24.9029551 42.8794554,34.5115163 41.3121702,47.1975534 C40.9043016,50.4989536 43.2499725,53.50591 46.5513726,53.9137786 C49.8527728,54.3216471 52.8597292,51.9759763 53.2675978,48.6745761 C54.0739246,42.1479456 60.2395837,36.9492759 65.3778484,36.9492759 C70.6427674,36.9492759 74.78639,40.5885487 74.78639,46.8554323 C74.78639,50.4892974 73.6853224,52.008304 69.6746221,54.7736715 C69.4052605,54.9593956 68.448509,55.6118556 68.3131127,55.7047319 C65.6309785,57.5445655 64.0858213,58.803255 62.6123358,60.6352315 C60.5044618,63.2559399 59.3714208,66.3518252 59.3547527,69.9487679 C59.3684999,70.8407274 59.3752803,71.8084521 59.3765995,72.9300232 C59.3779294,74.0607297 59.3737237,75.2764258 59.36589,76.482835 C59.3634936,76.8518793 59.3609272,77.1924914 59.3583633,77.4963784 C59.3568319,77.6778944 59.3556368,77.8074256 59.3549845,77.8730928 C59.3219814,81.1994287 61.9917551,83.9227111 65.318091,83.9557142 C68.644427,83.9887173 71.3677093,81.3189435 71.4007124,77.9926076 C71.4014444,77.9187458 71.402672,77.7856841 71.4042554,77.5980086 Z M65.3778489,102.097045 C69.5359735,102.097045 72.9067994,98.7262189 72.9067994,94.5680944 C72.9067994,90.4099698 69.5359735,87.0391439 65.3778489,87.0391439 C61.2197243,87.0391439 57.8488984,90.4099698 57.8488984,94.5680944 C57.8488984,98.7262189 61.2197243,102.097045 65.3778489,102.097045 Z"></path>
</g>
</svg>
<svg class="tc-image-home-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<g fill-rule="evenodd">
<path d="M112.9847,119.501583 C112.99485,119.336814 113,119.170705 113,119.003406 L113,67.56802 C116.137461,70.5156358 121.076014,70.4518569 124.133985,67.3938855 C127.25818,64.2696912 127.260618,59.2068102 124.131541,56.0777326 L70.3963143,2.34250601 C68.8331348,0.779326498 66.7828947,-0.000743167069 64.7337457,1.61675364e-05 C62.691312,-0.00409949529 60.6426632,0.777559815 59.077717,2.34250601 L33,28.420223 L33,28.420223 L33,8.00697327 C33,3.58484404 29.4092877,0 25,0 C20.581722,0 17,3.59075293 17,8.00697327 L17,44.420223 L5.3424904,56.0777326 C2.21694607,59.2032769 2.22220878,64.2760483 5.34004601,67.3938855 C8.46424034,70.5180798 13.5271213,70.5205187 16.6561989,67.3914411 L17,67.04764 L17,119.993027 C17,119.994189 17.0000002,119.995351 17.0000007,119.996514 C17.0000002,119.997675 17,119.998838 17,120 C17,124.418278 20.5881049,128 24.9992458,128 L105.000754,128 C109.418616,128 113,124.409288 113,120 C113,119.832611 112.99485,119.666422 112.9847,119.501583 Z M97,112 L97,51.5736087 L97,51.5736087 L64.7370156,19.3106244 L33,51.04764 L33,112 L97,112 Z"></path>
</g>
</svg>
<svg class="tc-image-import-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M105.449437,94.2138951 C105.449437,94.2138951 110.049457,94.1897106 110.049457,99.4026111 C110.049457,104.615512 105.163246,104.615511 105.163246,104.615511 L45.0075072,105.157833 C45.0075072,105.157833 0.367531803,106.289842 0.367532368,66.6449212 C0.367532934,27.0000003 45.0428249,27.0000003 45.0428249,27.0000003 L105.532495,27.0000003 C105.532495,27.0000003 138.996741,25.6734987 138.996741,55.1771866 C138.996741,84.6808745 105.727102,82.8457535 105.727102,82.8457535 L56.1735087,82.8457535 C56.1735087,82.8457535 22.6899229,85.1500223 22.6899229,66.0913753 C22.6899229,47.0327282 56.1735087,49.3383013 56.1735087,49.3383013 L105.727102,49.3383013 C105.727102,49.3383013 111.245209,49.3383024 111.245209,54.8231115 C111.245209,60.3079206 105.727102,60.5074524 105.727102,60.5074524 L56.1735087,60.5074524 C56.1735087,60.5074524 37.48913,60.5074528 37.48913,66.6449195 C37.48913,72.7823862 56.1735087,71.6766023 56.1735087,71.6766023 L105.727102,71.6766029 C105.727102,71.6766029 127.835546,73.1411469 127.835546,55.1771866 C127.835546,35.5304025 105.727102,38.3035317 105.727102,38.3035317 L45.0428249,38.3035317 C45.0428249,38.3035317 11.5287276,38.3035313 11.5287276,66.6449208 C11.5287276,94.9863103 45.0428244,93.9579678 45.0428244,93.9579678 L105.449437,94.2138951 Z" transform="translate(69.367532, 66.000000) rotate(-45.000000) translate(-69.367532, -66.000000) "></path>
</g>
</svg>
<svg class="tc-image-info-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<g fill-rule="evenodd">
<g transform="translate(0.049406, 0.000000)">
<path d="M64,128 C99.346224,128 128,99.346224 128,64 C128,28.653776 99.346224,0 64,0 C28.653776,0 0,28.653776 0,64 C0,99.346224 28.653776,128 64,128 Z M64,112 C90.509668,112 112,90.509668 112,64 C112,37.490332 90.509668,16 64,16 C37.490332,16 16,37.490332 16,64 C16,90.509668 37.490332,112 64,112 Z"></path>
<circle cx="64" cy="32" r="8"></circle>
<rect x="56" y="48" width="16" height="56" rx="8"></rect>
</g>
</g>
</g>
</svg>
<svg class="tc-image-left-arrow tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<path transform="rotate(135, 63.8945, 64.1752)" d="m109.07576,109.35336c-1.43248,1.43361 -3.41136,2.32182 -5.59717,2.32182l-79.16816,0c-4.36519,0 -7.91592,-3.5444 -7.91592,-7.91666c0,-4.36337 3.54408,-7.91667 7.91592,-7.91667l71.25075,0l0,-71.25075c0,-4.3652 3.54442,-7.91592 7.91667,-7.91592c4.36336,0 7.91667,3.54408 7.91667,7.91592l0,79.16815c0,2.1825 -0.88602,4.16136 -2.3185,5.59467l-0.00027,-0.00056z"/>
</svg>
<svg class="tc-image-locked-padlock tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M96.4723753,64 L105,64 L105,96.0097716 C105,113.673909 90.6736461,128 73.001193,128 L55.998807,128 C38.3179793,128 24,113.677487 24,96.0097716 L24,64 L32.0000269,64 C32.0028554,48.2766389 32.3030338,16.2688026 64.1594984,16.2688041 C95.9543927,16.2688056 96.4648869,48.325931 96.4723753,64 Z M80.5749059,64 L48.4413579,64 C48.4426205,47.71306 48.5829272,31.9999996 64.1595001,31.9999996 C79.8437473,31.9999996 81.1369461,48.1359182 80.5749059,64 Z M67.7315279,92.3641717 C70.8232551,91.0923621 73,88.0503841 73,84.5 C73,79.8055796 69.1944204,76 64.5,76 C59.8055796,76 56,79.8055796 56,84.5 C56,87.947435 58.0523387,90.9155206 61.0018621,92.2491029 L55.9067479,115.020857 L72.8008958,115.020857 L67.7315279,92.3641717 L67.7315279,92.3641717 Z"></path>
</g>
</svg>
<svg class="tc-image-mail tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M122.826782,104.894066 C121.945525,105.22777 120.990324,105.41043 119.993027,105.41043 L8.00697327,105.41043 C7.19458381,105.41043 6.41045219,105.289614 5.67161357,105.064967 L5.67161357,105.064967 L39.8346483,70.9019325 L60.6765759,91.7438601 C61.6118278,92.679112 62.8865166,93.0560851 64.0946097,92.8783815 C65.2975108,93.0473238 66.5641085,92.6696979 67.4899463,91.7438601 L88.5941459,70.6396605 C88.6693095,70.7292352 88.7490098,70.8162939 88.8332479,70.9005321 L122.826782,104.894066 Z M127.903244,98.6568194 C127.966933,98.2506602 128,97.8343714 128,97.4103789 L128,33.410481 C128,32.7414504 127.917877,32.0916738 127.763157,31.4706493 L94.2292399,65.0045665 C94.3188145,65.0797417 94.4058701,65.1594458 94.4901021,65.2436778 L127.903244,98.6568194 Z M0.205060636,99.2178117 C0.0709009529,98.6370366 0,98.0320192 0,97.4103789 L0,33.410481 C0,32.694007 0.0944223363,31.9995312 0.27147538,31.3387595 L0.27147538,31.3387595 L34.1777941,65.2450783 L0.205060636,99.2178117 L0.205060636,99.2178117 Z M5.92934613,25.6829218 C6.59211333,25.5051988 7.28862283,25.4104299 8.00697327,25.4104299 L119.993027,25.4104299 C120.759109,25.4104299 121.500064,25.5178649 122.201605,25.7184927 L122.201605,25.7184927 L64.0832611,83.8368368 L5.92934613,25.6829218 L5.92934613,25.6829218 Z"></path>
</g>
</svg>
<svg class="tc-image-menu-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<rect x="0" y="16" width="128" height="16" rx="8"></rect>
<rect x="0" y="56" width="128" height="16" rx="8"></rect>
<rect x="0" y="96" width="128" height="16" rx="8"></rect>
</svg>
<svg class="tc-image-new-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<g fill-rule="evenodd">
<path d="M56,72 L8.00697327,72 C3.59075293,72 0,68.418278 0,64 C0,59.5907123 3.58484404,56 8.00697327,56 L56,56 L56,8.00697327 C56,3.59075293 59.581722,0 64,0 C68.4092877,0 72,3.58484404 72,8.00697327 L72,56 L119.993027,56 C124.409247,56 128,59.581722 128,64 C128,68.4092877 124.415156,72 119.993027,72 L72,72 L72,119.993027 C72,124.409247 68.418278,128 64,128 C59.5907123,128 56,124.415156 56,119.993027 L56,72 L56,72 Z"></path>
</g>
</svg>
<svg class="tc-image-new-here-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<g transform="translate(52.233611, 64.389922) rotate(75.000000) translate(-52.233611, -64.389922) translate(-7.734417, 3.702450)">
<path d="M18.9270186,45.959338 L18.9080585,49.6521741 C18.8884833,53.4648378 21.0574548,58.7482162 23.7526408,61.4434022 L78.5671839,116.257945 C81.2617332,118.952495 85.6348701,118.950391 88.3334363,116.251825 L115.863237,88.7220241 C118.555265,86.0299959 118.564544,81.6509578 115.869358,78.9557717 L61.0548144,24.1412286 C58.3602652,21.4466794 53.0787224,19.2788426 49.2595808,19.3006519 L25.9781737,19.4336012 C22.1633003,19.4553862 19.0471195,22.5673232 19.0275223,26.3842526 L18.9871663,34.2443819 C19.0818862,34.255617 19.1779758,34.2665345 19.2754441,34.2771502 C22.6891275,34.6489512 27.0485594,34.2348566 31.513244,33.2285542 C31.7789418,32.8671684 32.075337,32.5211298 32.4024112,32.1940556 C34.8567584,29.7397084 38.3789778,29.0128681 41.4406288,30.0213822 C41.5958829,29.9543375 41.7503946,29.8866669 41.9041198,29.8183808 L42.1110981,30.2733467 C43.1114373,30.6972371 44.0473796,31.3160521 44.8614145,32.1300869 C48.2842088,35.5528813 48.2555691,41.130967 44.7974459,44.5890903 C41.4339531,47.952583 36.0649346,48.0717177 32.6241879,44.9262969 C27.8170558,45.8919233 23.0726921,46.2881596 18.9270186,45.959338 Z"></path>
<path d="M45.4903462,38.8768094 C36.7300141,42.6833154 26.099618,44.7997354 18.1909048,43.9383587 C7.2512621,42.7468685 1.50150083,35.8404432 4.66865776,24.7010202 C7.51507386,14.6896965 15.4908218,6.92103848 24.3842626,4.38423012 C34.1310219,1.60401701 42.4070208,6.15882777 42.4070209,16.3101169 L34.5379395,16.310117 C34.5379394,11.9285862 31.728784,10.3825286 26.5666962,11.8549876 C20.2597508,13.6540114 14.3453742,19.4148216 12.2444303,26.8041943 C10.4963869,32.9523565 12.6250796,35.5092726 19.0530263,36.2093718 C25.5557042,36.9176104 35.0513021,34.9907189 42.7038419,31.5913902 L42.7421786,31.6756595 C44.3874154,31.5384763 47.8846101,37.3706354 45.9274416,38.6772897 L45.9302799,38.6835285 C45.9166992,38.6895612 45.9031139,38.6955897 45.8895238,38.7016142 C45.8389288,38.7327898 45.7849056,38.7611034 45.7273406,38.7863919 C45.6506459,38.8200841 45.571574,38.8501593 45.4903462,38.8768094 Z"></path>
</g>
<rect x="96" y="80" width="16" height="48" rx="8"></rect>
<rect x="80" y="96" width="48" height="16" rx="8"></rect>
</g>
</g>
</svg>
<svg class="tc-image-new-journal-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M102.545455,112.818182 L102.545455,124.636364 L102.545455,124.636364 L102.545455,124.636364 C102.545455,125.941761 103.630828,127 104.969697,127 L111.030303,127 C112.369172,127 113.454545,125.941761 113.454545,124.636364 L113.454545,112.818182 L125.575758,112.818182 C126.914626,112.818182 128,111.759982 128,110.454545 L128,104.545455 C128,103.240018 126.914626,102.181818 125.575758,102.181818 L113.454545,102.181818 L113.454545,90.3636364 C113.454545,89.0582 112.369172,88 111.030303,88 L104.969697,88 L104.969697,88 C103.630828,88 102.545455,89.0582 102.545455,90.3636364 L102.545455,102.181818 L90.4242424,102.181818 L90.4242424,102.181818 C89.0853705,102.181818 88,103.240018 88,104.545455 L88,110.454545 L88,110.454545 L88,110.454545 C88,111.759982 89.0853705,112.818182 90.4242424,112.818182 L102.545455,112.818182 Z"></path>
<g transform="translate(59.816987, 64.316987) rotate(30.000000) translate(-59.816987, -64.316987) translate(20.316987, 12.816987)">
<g transform="translate(0.000000, 0.000000)">
<path d="M9.99631148,0 C4.4755011,0 -2.27373675e-13,4.48070044 -2.27373675e-13,9.99759461 L-2.27373675e-13,91.6128884 C-2.27373675e-13,97.1344074 4.46966773,101.610483 9.99631148,101.610483 L68.9318917,101.610483 C74.4527021,101.610483 78.9282032,97.1297826 78.9282032,91.6128884 L78.9282032,9.99759461 C78.9282032,4.47607557 74.4585355,0 68.9318917,0 L9.99631148,0 Z M20.8885263,26 C24.2022348,26 26.8885263,23.3137085 26.8885263,20 C26.8885263,16.6862915 24.2022348,14 20.8885263,14 C17.5748178,14 14.8885263,16.6862915 14.8885263,20 C14.8885263,23.3137085 17.5748178,26 20.8885263,26 Z M57.3033321,25.6783342 C60.6170406,25.6783342 63.3033321,22.9920427 63.3033321,19.6783342 C63.3033321,16.3646258 60.6170406,13.6783342 57.3033321,13.6783342 C53.9896236,13.6783342 51.3033321,16.3646258 51.3033321,19.6783342 C51.3033321,22.9920427 53.9896236,25.6783342 57.3033321,25.6783342 Z"></path>
<text font-family="Helvetica" font-size="47.1724138" font-weight="bold" fill="#FFFFFF">
<tspan x="42" y="77.4847912" text-anchor="middle"><<now "DD">></tspan>
</text>
</g>
</g>
</g>
</svg>
<svg class="tc-image-open-window tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M16,112 L104.993898,112 C108.863261,112 112,115.590712 112,120 C112,124.418278 108.858091,128 104.993898,128 L7.00610161,128 C3.13673853,128 0,124.409288 0,120 C0,119.998364 4.30952878e-07,119.996727 1.29273572e-06,119.995091 C4.89579306e-07,119.993456 0,119.99182 0,119.990183 L0,24.0098166 C0,19.586117 3.59071231,16 8,16 C12.418278,16 16,19.5838751 16,24.0098166 L16,112 Z"></path>
<path d="M96,43.1959595 L96,56 C96,60.418278 99.581722,64 104,64 C108.418278,64 112,60.418278 112,56 L112,24 C112,19.5907123 108.415101,16 103.992903,16 L72.0070969,16 C67.5881712,16 64,19.581722 64,24 C64,28.4092877 67.5848994,32 72.0070969,32 L84.5685425,32 L48.2698369,68.2987056 C45.1421332,71.4264093 45.1434327,76.4904296 48.267627,79.614624 C51.3854642,82.7324612 56.4581306,82.7378289 59.5835454,79.6124141 L96,43.1959595 Z M32,7.9992458 C32,3.58138434 35.5881049,0 39.9992458,0 L120.000754,0 C124.418616,0 128,3.5881049 128,7.9992458 L128,88.0007542 C128,92.4186157 124.411895,96 120.000754,96 L39.9992458,96 C35.5813843,96 32,92.4118951 32,88.0007542 L32,7.9992458 Z"></path>
</g>
</svg>
<svg class="tc-image-options-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M110.48779,76.0002544 C109.354214,80.4045063 107.611262,84.5641217 105.354171,88.3838625 L105.354171,88.3838625 L112.07833,95.1080219 C115.20107,98.2307613 115.210098,103.299824 112.089164,106.420759 L106.420504,112.089418 C103.301049,115.208874 98.2346851,115.205502 95.1077675,112.078585 L88.3836082,105.354425 C84.5638673,107.611516 80.4042519,109.354468 76,110.488045 L76,110.488045 L76,119.993281 C76,124.409501 72.4220153,128.000254 68.0083475,128.000254 L59.9916525,128.000254 C55.5800761,128.000254 52,124.41541 52,119.993281 L52,110.488045 C47.5957481,109.354468 43.4361327,107.611516 39.6163918,105.354425 L32.8922325,112.078585 C29.7694931,115.201324 24.7004301,115.210353 21.5794957,112.089418 L15.9108363,106.420759 C12.7913807,103.301303 12.7947522,98.2349395 15.9216697,95.1080219 L22.6458291,88.3838625 C20.3887383,84.5641217 18.6457859,80.4045063 17.5122098,76.0002544 L8.00697327,76.0002544 C3.59075293,76.0002544 2.19088375e-16,72.4222697 4.89347582e-16,68.0086019 L9.80228577e-16,59.9919069 C1.25035972e-15,55.5803305 3.58484404,52.0002544 8.00697327,52.0002544 L17.5122098,52.0002544 C18.6457859,47.5960025 20.3887383,43.4363871 22.6458291,39.6166462 L15.9216697,32.8924868 C12.7989304,29.7697475 12.7899019,24.7006845 15.9108363,21.5797501 L21.5794957,15.9110907 C24.6989513,12.7916351 29.7653149,12.7950065 32.8922325,15.9219241 L39.6163918,22.6460835 C43.4361327,20.3889927 47.5957481,18.6460403 52,17.5124642 L52,8.00722764 C52,3.5910073 55.5779847,0.000254375069 59.9916525,0.000254375069 L68.0083475,0.000254375069 C72.4199239,0.000254375069 76,3.58509841 76,8.00722764 L76,17.5124642 C80.4042519,18.6460403 84.5638673,20.3889927 88.3836082,22.6460835 L95.1077675,15.9219241 C98.2305069,12.7991848 103.29957,12.7901562 106.420504,15.9110907 L112.089164,21.5797501 C115.208619,24.6992057 115.205248,29.7655693 112.07833,32.8924868 L105.354171,39.6166462 L105.354171,39.6166462 C107.611262,43.4363871 109.354214,47.5960025 110.48779,52.0002544 L119.993027,52.0002544 C124.409247,52.0002544 128,55.5782391 128,59.9919069 L128,68.0086019 C128,72.4201783 124.415156,76.0002544 119.993027,76.0002544 L110.48779,76.0002544 L110.48779,76.0002544 Z M64,96.0002544 C81.673112,96.0002544 96,81.6733664 96,64.0002544 C96,46.3271424 81.673112,32.0002544 64,32.0002544 C46.326888,32.0002544 32,46.3271424 32,64.0002544 C32,81.6733664 46.326888,96.0002544 64,96.0002544 Z"></path>
</g>
</svg>
<svg class="tc-image-palette tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M80.2470434,39.1821571 C75.0645698,38.2680897 69.6261555,37.7814854 64.0193999,37.7814854 C28.6624616,37.7814854 0,57.1324214 0,81.0030106 C0,90.644534 4.67604329,99.5487133 12.5805659,106.738252 C23.5031767,91.1899067 26.3405471,72.3946229 36.8885698,63.5622337 C52.0716764,50.8486559 63.4268694,55.7343343 63.4268694,55.7343343 L80.2470434,39.1821571 Z M106.781666,48.8370714 C119.830962,56.749628 128.0388,68.229191 128.0388,81.0030106 C128.0388,90.3534932 128.557501,98.4142085 116.165191,106.082518 C105.367708,112.763955 112.341384,99.546808 104.321443,95.1851533 C96.3015017,90.8234987 84.3749007,96.492742 86.1084305,103.091059 C89.3087234,115.272303 105.529892,114.54645 92.4224435,119.748569 C79.3149955,124.950687 74.2201582,124.224536 64.0193999,124.224536 C56.1979176,124.224536 48.7040365,123.277578 41.7755684,121.544216 C51.620343,117.347916 69.6563669,109.006202 75.129737,102.088562 C82.7876655,92.4099199 87.3713218,80.0000002 83.3235694,72.4837191 C83.1303943,72.1250117 94.5392656,60.81569 106.781666,48.8370714 Z M1.13430476,123.866563 C0.914084026,123.867944 0.693884185,123.868637 0.473712455,123.868637 C33.9526848,108.928928 22.6351223,59.642592 59.2924543,59.6425917 C59.6085574,61.0606542 59.9358353,62.5865065 60.3541977,64.1372318 C34.4465025,59.9707319 36.7873124,112.168427 1.13429588,123.866563 L1.13430476,123.866563 Z M1.84669213,123.859694 C40.7185279,123.354338 79.9985412,101.513051 79.9985401,79.0466836 C70.7284906,79.0466835 65.9257264,75.5670082 63.1833375,71.1051511 C46.585768,64.1019718 32.81846,116.819636 1.84665952,123.859695 L1.84669213,123.859694 Z M67.1980193,59.8524981 C62.748213,63.9666823 72.0838429,76.2846822 78.5155805,71.1700593 C89.8331416,59.8524993 112.468264,37.2173758 123.785825,25.8998146 C135.103386,14.5822535 123.785825,3.26469247 112.468264,14.5822535 C101.150703,25.8998144 78.9500931,48.9868127 67.1980193,59.8524981 Z"></path>
</g>
</svg>
<svg class="tc-image-permalink-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M80.4834582,48 L73.0956761,80 L73.0956761,80 L47.5165418,80 L54.9043239,48 L80.4834582,48 Z M84.1773493,32 L89.8007299,7.64246248 C90.7941633,3.33942958 95.0918297,0.64641956 99.3968675,1.64031585 C103.693145,2.63218977 106.385414,6.93288901 105.390651,11.2416793 L100.598215,32 L104.000754,32 C108.411895,32 112,35.581722 112,40 C112,44.4092877 108.418616,48 104.000754,48 L96.9043239,48 L89.5165418,80 L104.000754,80 C108.411895,80 112,83.581722 112,88 C112,92.4092877 108.418616,96 104.000754,96 L85.8226507,96 L80.1992701,120.357538 C79.2058367,124.66057 74.9081703,127.35358 70.6031325,126.359684 C66.3068546,125.36781 63.6145865,121.067111 64.6093491,116.758321 L69.401785,96 L43.8226507,96 L38.1992701,120.357538 C37.2058367,124.66057 32.9081703,127.35358 28.6031325,126.359684 C24.3068546,125.36781 21.6145865,121.067111 22.6093491,116.758321 L27.401785,96 L23.9992458,96 C19.5881049,96 16,92.418278 16,88 C16,83.5907123 19.5813843,80 23.9992458,80 L31.0956761,80 L38.4834582,48 L23.9992458,48 C19.5881049,48 16,44.418278 16,40 C16,35.5907123 19.5813843,32 23.9992458,32 L42.1773493,32 L47.8007299,7.64246248 C48.7941633,3.33942958 53.0918297,0.64641956 57.3968675,1.64031585 C61.6931454,2.63218977 64.3854135,6.93288901 63.3906509,11.2416793 L58.598215,32 L84.1773493,32 Z"></path>
</g>
</svg>
<svg class="tc-image-permaview-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M81.4834582,48 L79.6365127,56 L79.6365127,56 L74.0573784,56 L75.9043239,48 L81.4834582,48 Z M85.1773493,32 L90.8007299,7.64246248 C91.7941633,3.33942958 96.0918297,0.64641956 100.396867,1.64031585 C104.693145,2.63218977 107.385414,6.93288901 106.390651,11.2416793 L101.598215,32 L104.000754,32 C108.411895,32 112,35.581722 112,40 C112,44.4092877 108.418616,48 104.000754,48 L97.9043239,48 L96.0573784,56 L104.000754,56 C108.411895,56 112,59.581722 112,64 C112,68.4092877 108.418616,72 104.000754,72 L92.3634873,72 L90.5165418,80 L104.000754,80 C108.411895,80 112,83.581722 112,88 C112,92.4092877 108.418616,96 104.000754,96 L86.8226507,96 L81.1992701,120.357538 C80.2058367,124.66057 75.9081703,127.35358 71.6031325,126.359684 C67.3068546,125.36781 64.6145865,121.067111 65.6093491,116.758321 L70.401785,96 L64.8226507,96 L59.1992701,120.357538 C58.2058367,124.66057 53.9081703,127.35358 49.6031325,126.359684 C45.3068546,125.36781 42.6145865,121.067111 43.6093491,116.758321 L48.401785,96 L42.8226507,96 L37.1992701,120.357538 C36.2058367,124.66057 31.9081703,127.35358 27.6031325,126.359684 C23.3068546,125.36781 20.6145865,121.067111 21.6093491,116.758321 L26.401785,96 L23.9992458,96 C19.5881049,96 16,92.418278 16,88 C16,83.5907123 19.5813843,80 23.9992458,80 L30.0956761,80 L31.9426216,72 L23.9992458,72 C19.5881049,72 16,68.418278 16,64 C16,59.5907123 19.5813843,56 23.9992458,56 L35.6365127,56 L37.4834582,48 L23.9992458,48 C19.5881049,48 16,44.418278 16,40 C16,35.5907123 19.5813843,32 23.9992458,32 L41.1773493,32 L46.8007299,7.64246248 C47.7941633,3.33942958 52.0918297,0.64641956 56.3968675,1.64031585 C60.6931454,2.63218977 63.3854135,6.93288901 62.3906509,11.2416793 L57.598215,32 L63.1773493,32 L68.8007299,7.64246248 C69.7941633,3.33942958 74.0918297,0.64641956 78.3968675,1.64031585 C82.6931454,2.63218977 85.3854135,6.93288901 84.3906509,11.2416793 L79.598215,32 L85.1773493,32 Z M53.9043239,48 L52.0573784,56 L57.6365127,56 L59.4834582,48 L53.9043239,48 Z M75.9426216,72 L74.0956761,80 L74.0956761,80 L68.5165418,80 L70.3634873,72 L75.9426216,72 L75.9426216,72 Z M48.3634873,72 L46.5165418,80 L52.0956761,80 L53.9426216,72 L48.3634873,72 L48.3634873,72 Z"></path>
</g>
</svg>
<svg width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M61.2072232,68.1369825 C56.8829239,70.9319564 54.2082892,74.793177 54.2082892,79.0581634 C54.2082892,86.9638335 63.3980995,93.4821994 75.2498076,94.3940006 C77.412197,98.2964184 83.8475284,101.178858 91.5684735,101.403106 C86.4420125,100.27851 82.4506393,97.6624107 80.9477167,94.3948272 C92.8046245,93.4861461 102,86.9662269 102,79.0581634 C102,70.5281905 91.3014611,63.6132813 78.1041446,63.6132813 C71.5054863,63.6132813 65.5315225,65.3420086 61.2072232,68.1369825 Z M74.001066,53.9793443 C69.6767667,56.7743182 63.7028029,58.5030456 57.1041446,58.5030456 C54.4851745,58.5030456 51.9646095,58.2307276 49.6065315,57.7275105 C46.2945155,59.9778212 41.2235699,61.4171743 35.5395922,61.4171743 C35.4545771,61.4171743 35.3696991,61.4168523 35.2849622,61.4162104 C39.404008,60.5235193 42.7961717,58.6691298 44.7630507,56.286533 C37.8379411,53.5817651 33.2082892,48.669413 33.2082892,43.0581634 C33.2082892,34.5281905 43.9068281,27.6132812 57.1041446,27.6132812 C70.3014611,27.6132812 81,34.5281905 81,43.0581634 C81,47.3231498 78.3253653,51.1843704 74.001066,53.9793443 Z M64,0 L118.5596,32 L118.5596,96 L64,128 L9.44039956,96 L9.44039956,32 L64,0 Z"></path>
</g>
</svg>
<svg width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M40.3972881,76.4456988 L40.3972881,95.3404069 L54.5170166,95.3404069 L54.5170166,95.3404069 C54.5165526,95.3385183 54.516089,95.3366295 54.515626,95.3347404 C54.6093153,95.3385061 54.7034848,95.3404069 54.7980982,95.3404069 C58.6157051,95.3404069 61.710487,92.245625 61.710487,88.4280181 C61.710487,86.6197822 61.01617,84.9737128 59.8795929,83.7418666 L59.8795929,83.7418666 C59.8949905,83.7341665 59.9104102,83.7265043 59.925852,83.7188798 C58.8840576,82.5086663 58.2542926,80.9336277 58.2542926,79.2114996 C58.2542926,75.3938927 61.3490745,72.2991108 65.1666814,72.2991108 C68.9842884,72.2991108 72.0790703,75.3938927 72.0790703,79.2114996 C72.0790703,81.1954221 71.2432806,82.9841354 69.9045961,84.2447446 L69.9045961,84.2447446 C69.9333407,84.2629251 69.9619885,84.281245 69.9905383,84.2997032 L69.9905383,84.2997032 C69.1314315,85.4516923 68.6228758,86.8804654 68.6228758,88.4280181 C68.6228758,91.8584969 71.1218232,94.7053153 74.3986526,95.2474079 C74.3913315,95.2784624 74.3838688,95.3094624 74.3762652,95.3404069 L95.6963988,95.3404069 L95.6963988,75.5678578 L95.6963988,75.5678578 C95.6466539,75.5808558 95.5967614,75.5934886 95.5467242,75.6057531 C95.5504899,75.5120637 95.5523907,75.4178943 95.5523907,75.3232809 C95.5523907,71.505674 92.4576088,68.4108921 88.6400019,68.4108921 C86.831766,68.4108921 85.1856966,69.105209 83.9538504,70.2417862 L83.9538504,70.2417862 C83.9461503,70.2263886 83.938488,70.2109688 83.9308636,70.1955271 C82.7206501,71.2373215 81.1456115,71.8670865 79.4234834,71.8670865 C75.6058765,71.8670865 72.5110946,68.7723046 72.5110946,64.9546976 C72.5110946,61.1370907 75.6058765,58.0423088 79.4234834,58.0423088 C81.4074059,58.0423088 83.1961192,58.8780985 84.4567284,60.2167829 L84.4567284,60.2167829 C84.4749089,60.1880383 84.4932288,60.1593906 84.511687,60.1308407 L84.511687,60.1308407 C85.6636761,60.9899475 87.0924492,61.4985032 88.6400019,61.4985032 C92.0704807,61.4985032 94.9172991,58.9995558 95.4593917,55.7227265 C95.538755,55.7414363 95.6177614,55.761071 95.6963988,55.7816184 L95.6963988,40.0412962 L74.3762652,40.0412962 L74.3762652,40.0412962 C74.3838688,40.0103516 74.3913315,39.9793517 74.3986526,39.9482971 L74.3986526,39.9482971 C71.1218232,39.4062046 68.6228758,36.5593862 68.6228758,33.1289073 C68.6228758,31.5813547 69.1314315,30.1525815 69.9905383,29.0005925 C69.9619885,28.9821342 69.9333407,28.9638143 69.9045961,28.9456339 C71.2432806,27.6850247 72.0790703,25.8963113 72.0790703,23.9123888 C72.0790703,20.0947819 68.9842884,17 65.1666814,17 C61.3490745,17 58.2542926,20.0947819 58.2542926,23.9123888 C58.2542926,25.6345169 58.8840576,27.2095556 59.925852,28.419769 L59.925852,28.419769 C59.9104102,28.4273935 59.8949905,28.4350558 59.8795929,28.4427558 C61.01617,29.674602 61.710487,31.3206715 61.710487,33.1289073 C61.710487,36.9465143 58.6157051,40.0412962 54.7980982,40.0412962 C54.7034848,40.0412962 54.6093153,40.0393953 54.515626,40.0356296 L54.515626,40.0356296 C54.516089,40.0375187 54.5165526,40.0394075 54.5170166,40.0412962 L40.3972881,40.0412962 L40.3972881,52.887664 L40.3972881,52.887664 C40.4916889,53.3430132 40.5412962,53.8147625 40.5412962,54.2980982 C40.5412962,58.1157051 37.4465143,61.210487 33.6289073,61.210487 C32.0813547,61.210487 30.6525815,60.7019313 29.5005925,59.8428245 C29.4821342,59.8713744 29.4638143,59.9000221 29.4456339,59.9287667 C28.1850247,58.5900823 26.3963113,57.7542926 24.4123888,57.7542926 C20.5947819,57.7542926 17.5,60.8490745 17.5,64.6666814 C17.5,68.4842884 20.5947819,71.5790703 24.4123888,71.5790703 C26.134517,71.5790703 27.7095556,70.9493053 28.919769,69.9075109 L28.919769,69.9075109 C28.9273935,69.9229526 28.9350558,69.9383724 28.9427558,69.95377 C30.174602,68.8171928 31.8206715,68.1228758 33.6289073,68.1228758 C37.4465143,68.1228758 40.5412962,71.2176578 40.5412962,75.0352647 C40.5412962,75.5186004 40.4916889,75.9903496 40.3972881,76.4456988 Z M64,0 L118.5596,32 L118.5596,96 L64,128 L9.44039956,96 L9.44039956,32 L64,0 Z"></path>
</g>
</svg>
<svg width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M29.4078519,91.4716406 L51.4693474,69.4101451 L51.4646675,69.4054652 C50.5969502,68.5377479 50.5929779,67.1348725 51.4693474,66.2585029 C52.3396494,65.3882009 53.7499654,65.3874786 54.6163097,66.2538229 L64.0805963,75.7181095 C64.9483136,76.5858268 64.9522859,77.9887022 64.0759163,78.8650718 C63.2056143,79.7353737 61.7952984,79.736096 60.9289541,78.8697517 L60.9242741,78.8650718 L60.9242741,78.8650718 L38.8627786,100.926567 C36.2518727,103.537473 32.0187578,103.537473 29.4078519,100.926567 C26.796946,98.3156614 26.796946,94.0825465 29.4078519,91.4716406 Z M60.8017407,66.3810363 C58.3659178,63.6765806 56.3370667,61.2899536 54.9851735,59.5123615 C48.1295381,50.4979488 44.671561,55.2444054 40.7586738,59.5123614 C36.8457866,63.7803174 41.789473,67.2384487 38.0759896,70.2532832 C34.3625062,73.2681177 34.5917646,74.3131575 28.3243876,68.7977024 C22.0570105,63.2822473 21.6235306,61.7636888 24.5005999,58.6166112 C27.3776691,55.4695337 29.7823103,60.4247912 35.6595047,54.8320442 C41.5366991,49.2392972 36.5996215,44.2825646 36.5996215,44.2825646 C36.5996215,44.2825646 48.8365511,19.267683 65.1880231,21.1152173 C81.5394952,22.9627517 59.0022276,18.7228947 53.3962199,38.3410355 C50.9960082,46.7405407 53.8429162,44.7613399 58.3941742,48.3090467 C59.7875202,49.3951602 64.4244828,52.7100463 70.1884353,56.9943417 L90.8648751,36.3179019 L92.4795866,31.5515482 L100.319802,26.8629752 L103.471444,30.0146174 L98.782871,37.8548326 L94.0165173,39.4695441 L73.7934912,59.6925702 C86.4558549,69.2403631 102.104532,81.8392557 102.104532,86.4016913 C102.104533,93.6189834 99.0337832,97.9277545 92.5695848,95.5655717 C87.8765989,93.8506351 73.8015497,80.3744087 63.8173444,69.668717 L60.9242741,72.5617873 L57.7726319,69.4101451 L60.8017407,66.3810363 L60.8017407,66.3810363 Z M63.9533761,1.42108547e-13 L118.512977,32 L118.512977,96 L63.9533761,128 L9.39377563,96 L9.39377563,32 L63.9533761,1.42108547e-13 Z"></path>
</g>
</svg>
<svg class="tc-image-refresh-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M106.369002,39.4325143 C116.529932,60.3119371 112.939592,86.1974934 95.5979797,103.539105 C73.7286194,125.408466 38.2713806,125.408466 16.4020203,103.539105 C-5.46734008,81.6697449 -5.46734008,46.2125061 16.4020203,24.3431458 C19.5262146,21.2189514 24.5915344,21.2189514 27.7157288,24.3431458 C30.8399231,27.4673401 30.8399231,32.5326599 27.7157288,35.6568542 C12.0947571,51.2778259 12.0947571,76.6044251 27.7157288,92.2253967 C43.3367004,107.846368 68.6632996,107.846368 84.2842712,92.2253967 C97.71993,78.7897379 99.5995262,58.1740623 89.9230597,42.729491 L83.4844861,54.9932839 C81.4307001,58.9052072 76.5945372,60.4115251 72.682614,58.3577391 C68.7706907,56.3039532 67.2643728,51.4677903 69.3181587,47.555867 L84.4354914,18.7613158 C86.4966389,14.8353707 91.3577499,13.3347805 95.273202,15.415792 L124.145886,30.7612457 C128.047354,32.8348248 129.52915,37.6785572 127.455571,41.5800249 C125.381992,45.4814927 120.53826,46.9632892 116.636792,44.8897102 L106.369002,39.4325143 Z M98.1470904,27.0648707 C97.9798954,26.8741582 97.811187,26.6843098 97.6409651,26.4953413 L98.6018187,26.1987327 L98.1470904,27.0648707 Z"></path>
</g>
</svg>
<svg class="tc-image-right-arrow tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<path d="M80.3563798,109.353315 C78.9238993,110.786918 76.9450203,111.675144 74.7592239,111.675144 L-4.40893546,111.675144 C-8.77412698,111.675144 -12.3248558,108.130732 -12.3248558,103.758478 C-12.3248558,99.3951199 -8.78077754,95.8418109 -4.40893546,95.8418109 L66.8418109,95.8418109 L66.8418109,24.5910645 C66.8418109,20.225873 70.3862233,16.6751442 74.7584775,16.6751442 C79.1218352,16.6751442 82.6751442,20.2192225 82.6751442,24.5910645 L82.6751442,103.759224 C82.6751442,105.941695 81.7891419,107.920575 80.3566508,109.353886 Z" transform="translate(35.175144, 64.175144) rotate(-45.000000) translate(-35.175144, -64.175144) "></path>
</svg>
<svg class="tc-image-save-button tc-image-button" viewBox="0 0 128 128" width="22pt" height="22pt">
<g fill-rule="evenodd">
<path d="M120.78304,34.329058 C125.424287,43.1924006 128.049406,53.2778608 128.049406,63.9764502 C128.049406,99.3226742 99.3956295,127.97645 64.0494055,127.97645 C28.7031816,127.97645 0.0494055385,99.3226742 0.0494055385,63.9764502 C0.0494055385,28.6302262 28.7031816,-0.0235498012 64.0494055,-0.0235498012 C82.8568763,-0.0235498012 99.769563,8.08898558 111.479045,21.0056358 L114.159581,18.3250998 C117.289194,15.1954866 122.356036,15.1939641 125.480231,18.3181584 C128.598068,21.4359957 128.601317,26.5107804 125.473289,29.6388083 L120.78304,34.329058 Z M108.72451,46.3875877 C110.870571,51.8341374 112.049406,57.767628 112.049406,63.9764502 C112.049406,90.4861182 90.5590735,111.97645 64.0494055,111.97645 C37.5397375,111.97645 16.0494055,90.4861182 16.0494055,63.9764502 C16.0494055,37.4667822 37.5397375,15.9764502 64.0494055,15.9764502 C78.438886,15.9764502 91.3495036,22.308215 100.147097,32.3375836 L58.9411255,73.5435552 L41.975581,56.5780107 C38.8486152,53.4510448 33.7746915,53.4551552 30.6568542,56.5729924 C27.5326599,59.6971868 27.5372202,64.7670668 30.6618725,67.8917192 L53.279253,90.5090997 C54.8435723,92.073419 56.8951519,92.8541315 58.9380216,92.8558261 C60.987971,92.8559239 63.0389578,92.0731398 64.6049211,90.5071765 L108.72451,46.3875877 Z"></path>
</g>
</svg>
<svg class="tc-image-spiral tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="nonzero">
<path d="M64.534 68.348c3.39 0 6.097-2.62 6.476-5.968l-4.755-.538 4.75.583c.377-3.07-1.194-6.054-3.89-7.78-2.757-1.773-6.34-2.01-9.566-.7-3.46 1.403-6.14 4.392-7.35 8.148l-.01.026c-1.3 4.08-.72 8.64 1.58 12.52 2.5 4.2 6.77 7.2 11.76 8.27 5.37 1.15 11.11-.05 15.83-3.31 5.04-3.51 8.46-9.02 9.45-15.3 1.05-6.7-.72-13.63-4.92-19.19l.02.02c-4.42-5.93-11.2-9.82-18.78-10.78-7.96-1.01-16.13 1.31-22.59 6.43-6.81 5.39-11.18 13.41-12.11 22.26-.98 9.27 1.87 18.65 7.93 26.02 6.32 7.69 15.6 12.56 25.74 13.48 10.54.96 21.15-2.42 29.45-9.4l.01-.01c8.58-7.25 13.94-17.78 14.86-29.21.94-11.84-2.96-23.69-10.86-32.9-8.19-9.5-19.95-15.36-32.69-16.27-13.16-.94-26.24 3.49-36.34 12.34l.01-.01c-10.41 9.08-16.78 22.1-17.68 36.15-.93 14.44 4.03 28.77 13.79 39.78 10.03 11.32 24.28 18.2 39.6 19.09 15.73.92 31.31-4.56 43.24-15.234 12.23-10.954 19.61-26.44 20.5-43.074.14-2.64-1.89-4.89-4.52-5.03-2.64-.14-4.89 1.88-5.03 4.52-.75 14.1-7 27.2-17.33 36.45-10.03 8.98-23.11 13.58-36.3 12.81-12.79-.75-24.67-6.48-33-15.89-8.07-9.11-12.17-20.94-11.41-32.827.74-11.52 5.942-22.15 14.43-29.54l.01-.01c8.18-7.17 18.74-10.75 29.35-9.998 10.21.726 19.6 5.41 26.11 12.96 6.24 7.273 9.32 16.61 8.573 25.894-.718 8.9-4.88 17.064-11.504 22.66l.01-.007c-6.36 5.342-14.44 7.92-22.425 7.19-7.604-.68-14.52-4.314-19.21-10.027-4.44-5.4-6.517-12.23-5.806-18.94.67-6.3 3.76-11.977 8.54-15.766 4.46-3.54 10.05-5.128 15.44-4.44 5.03.63 9.46 3.18 12.32 7.01l.02.024c2.65 3.5 3.75 7.814 3.1 11.92-.59 3.71-2.58 6.925-5.45 8.924-2.56 1.767-5.61 2.403-8.38 1.81-2.42-.516-4.42-1.92-5.53-3.79-.93-1.56-1.15-3.3-.69-4.75l-4.56-1.446L59.325 65c.36-1.12 1.068-1.905 1.84-2.22.25-.103.48-.14.668-.13.06.006.11.015.14.025.01 0 .01 0-.01-.01-.02-.015-.054-.045-.094-.088-.06-.064-.12-.145-.17-.244-.15-.29-.23-.678-.18-1.11l-.005.04c.15-1.332 1.38-2.523 3.035-2.523-2.65 0-4.79 2.144-4.79 4.787s2.14 4.785 4.78 4.785z"></path>
</g>
</svg>
<svg class="tc-image-star-filled tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="nonzero">
<path d="M61.8361286,96.8228569 L99.1627704,124.110219 C101.883827,126.099427 105.541968,123.420868 104.505636,120.198072 L90.2895569,75.9887263 L89.0292911,79.8977279 L126.314504,52.5528988 C129.032541,50.5595011 127.635256,46.2255025 124.273711,46.2229134 L78.1610486,46.1873965 L81.4604673,48.6032923 L67.1773543,4.41589688 C66.1361365,1.19470104 61.6144265,1.19470104 60.5732087,4.41589688 L46.2900957,48.6032923 L49.5895144,46.1873965 L3.47685231,46.2229134 C0.115307373,46.2255025 -1.28197785,50.5595011 1.43605908,52.5528988 L38.7212719,79.8977279 L37.4610061,75.9887263 L23.2449266,120.198072 C22.2085954,123.420868 25.8667356,126.099427 28.5877926,124.110219 L65.9144344,96.8228569 L61.8361286,96.8228569 Z"></path>
</g>
</svg>
<svg class="tc-image-storyview-classic tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M8.00697327,0 C3.58484404,0 0,3.59075293 0,8.00697327 L0,119.993027 C0,124.415156 3.59075293,128 8.00697327,128 L119.993027,128 C124.415156,128 128,124.409247 128,119.993027 L128,8.00697327 C128,3.58484404 124.409247,0 119.993027,0 L8.00697327,0 L8.00697327,0 Z M23.9992458,16 C19.5813843,16 16,19.5776607 16,23.9924054 L16,40.0075946 C16,44.4216782 19.5881049,48 23.9992458,48 L104.000754,48 C108.418616,48 112,44.4223393 112,40.0075946 L112,23.9924054 C112,19.5783218 108.411895,16 104.000754,16 L23.9992458,16 L23.9992458,16 Z M23.9992458,64 C19.5813843,64 16,67.5907123 16,72 C16,76.418278 19.5881049,80 23.9992458,80 L104.000754,80 C108.418616,80 112,76.4092877 112,72 C112,67.581722 108.411895,64 104.000754,64 L23.9992458,64 L23.9992458,64 Z M23.9992458,96 C19.5813843,96 16,99.5907123 16,104 C16,108.418278 19.5881049,112 23.9992458,112 L104.000754,112 C108.418616,112 112,108.409288 112,104 C112,99.581722 108.411895,96 104.000754,96 L23.9992458,96 L23.9992458,96 Z"></path>
</g>
</svg>
<svg class="tc-image-storyview-pop tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M8.00697327,0 C3.58484404,0 0,3.59075293 0,8.00697327 L0,119.993027 C0,124.415156 3.59075293,128 8.00697327,128 L119.993027,128 C124.415156,128 128,124.409247 128,119.993027 L128,8.00697327 C128,3.58484404 124.409247,0 119.993027,0 L8.00697327,0 L8.00697327,0 Z M23.9992458,16 C19.5813843,16 16,19.5776607 16,23.9924054 L16,40.0075946 C16,44.4216782 19.5881049,48 23.9992458,48 L104.000754,48 C108.418616,48 112,44.4223393 112,40.0075946 L112,23.9924054 C112,19.5783218 108.411895,16 104.000754,16 L23.9992458,16 L23.9992458,16 Z M16.0098166,56 C11.586117,56 8,59.5776607 8,63.9924054 L8,80.0075946 C8,84.4216782 11.5838751,88 16.0098166,88 L111.990183,88 C116.413883,88 120,84.4223393 120,80.0075946 L120,63.9924054 C120,59.5783218 116.416125,56 111.990183,56 L16.0098166,56 L16.0098166,56 Z M23.9992458,96 C19.5813843,96 16,99.5907123 16,104 C16,108.418278 19.5881049,112 23.9992458,112 L104.000754,112 C108.418616,112 112,108.409288 112,104 C112,99.581722 108.411895,96 104.000754,96 L23.9992458,96 L23.9992458,96 Z M23.9992458,64 C19.5813843,64 16,67.5907123 16,72 C16,76.418278 19.5881049,80 23.9992458,80 L104.000754,80 C108.418616,80 112,76.4092877 112,72 C112,67.581722 108.411895,64 104.000754,64 L23.9992458,64 L23.9992458,64 Z"></path>
</g>
</svg>
<svg class="tc-image-storyview-zoomin tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M8.00697327,0 C3.58484404,0 0,3.59075293 0,8.00697327 L0,119.993027 C0,124.415156 3.59075293,128 8.00697327,128 L119.993027,128 C124.415156,128 128,124.409247 128,119.993027 L128,8.00697327 C128,3.58484404 124.409247,0 119.993027,0 L8.00697327,0 L8.00697327,0 Z M23.9992458,16 C19.5813843,16 16,19.578055 16,24.0085154 L16,71.9914846 C16,76.4144655 19.5881049,80 23.9992458,80 L104.000754,80 C108.418616,80 112,76.421945 112,71.9914846 L112,24.0085154 C112,19.5855345 108.411895,16 104.000754,16 L23.9992458,16 L23.9992458,16 Z"></path>
</g>
</svg>
<svg class="tc-image-tag-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M18.1643182,47.6600756 L18.1677196,51.7651887 C18.1708869,55.5878829 20.3581578,60.8623899 23.0531352,63.5573673 L84.9021823,125.406414 C87.5996731,128.103905 91.971139,128.096834 94.6717387,125.396234 L125.766905,94.3010679 C128.473612,91.5943612 128.472063,87.2264889 125.777085,84.5315115 L63.9280381,22.6824644 C61.2305472,19.9849735 55.9517395,17.801995 52.1318769,17.8010313 L25.0560441,17.7942007 C21.2311475,17.7932358 18.1421354,20.8872832 18.1452985,24.7049463 L18.1535504,34.6641936 C18.2481119,34.6754562 18.3439134,34.6864294 18.4409623,34.6971263 C22.1702157,35.1081705 26.9295004,34.6530132 31.806204,33.5444844 C32.1342781,33.0700515 32.5094815,32.6184036 32.9318197,32.1960654 C35.6385117,29.4893734 39.5490441,28.718649 42.94592,29.8824694 C43.0432142,29.8394357 43.1402334,29.7961748 43.2369683,29.7526887 L43.3646982,30.0368244 C44.566601,30.5115916 45.6933052,31.2351533 46.6655958,32.2074439 C50.4612154,36.0030635 50.4663097,42.1518845 46.6769742,45.94122 C43.0594074,49.5587868 37.2914155,49.7181264 33.4734256,46.422636 C28.1082519,47.5454734 22.7987486,48.0186448 18.1643182,47.6600756 Z"></path>
<path d="M47.6333528,39.5324628 L47.6562932,39.5834939 C37.9670934,43.9391617 26.0718874,46.3819521 17.260095,45.4107025 C5.27267473,44.0894301 -1.02778744,36.4307276 2.44271359,24.0779512 C5.56175386,12.9761516 14.3014034,4.36129832 24.0466405,1.54817001 C34.7269254,-1.53487574 43.7955833,3.51606438 43.7955834,14.7730751 L35.1728168,14.7730752 C35.1728167,9.91428944 32.0946059,8.19982862 26.4381034,9.83267419 C19.5270911,11.8276553 13.046247,18.2159574 10.7440788,26.4102121 C8.82861123,33.2280582 11.161186,36.0634845 18.2047888,36.8398415 C25.3302805,37.6252244 35.7353482,35.4884477 44.1208333,31.7188498 L44.1475077,31.7781871 C44.159701,31.7725635 44.1718402,31.7671479 44.1839238,31.7619434 C45.9448098,31.0035157 50.4503245,38.3109156 47.7081571,39.5012767 C47.6834429,39.512005 47.6585061,39.5223987 47.6333528,39.5324628 Z"></path>
</g>
</svg>
<svg class="tc-image-theme-button tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M55.854113,66.9453198 C54.3299482,65.1432292 53.0133883,63.518995 51.9542746,62.1263761 C40.8899947,47.578055 35.3091807,55.2383404 28.9941893,62.1263758 C22.6791979,69.0144112 30.6577916,74.5954741 24.6646171,79.4611023 C18.6714426,84.3267304 19.0414417,86.0133155 8.92654943,77.1119468 C-1.18834284,68.2105781 -1.88793412,65.7597832 2.7553553,60.6807286 C7.39864472,55.601674 11.2794845,63.5989423 20.7646627,54.5728325 C30.2498409,45.5467226 22.2819131,37.5470737 22.2819131,37.5470737 C22.2819131,37.5470737 42.0310399,-2.82433362 68.4206088,0.157393922 C94.8101776,3.13912147 58.4373806,-3.70356506 49.3898693,27.958066 C45.5161782,41.5139906 50.1107906,38.3197672 57.4560458,44.0453955 C59.1625767,45.3756367 63.8839488,48.777453 70.127165,53.3625321 C63.9980513,59.2416709 58.9704753,64.0315459 55.854113,66.9453198 Z M67.4952439,79.8919946 C83.5082212,96.9282402 105.237121,117.617674 112.611591,120.312493 C123.044132,124.12481 128.000001,117.170903 128,105.522947 C127.999999,98.3705516 104.170675,78.980486 84.0760493,63.7529565 C76.6683337,70.9090328 70.7000957,76.7055226 67.4952439,79.8919946 Z"></path>
<path d="M58.2852966,138.232794 L58.2852966,88.3943645 C56.318874,88.3923153 54.7254089,86.7952906 54.7254089,84.8344788 C54.7254089,82.8684071 56.3175932,81.2745911 58.2890859,81.2745911 L79.6408336,81.2745911 C81.608998,81.2745911 83.2045105,82.8724076 83.2045105,84.8344788 C83.2045105,86.7992907 81.614366,88.3923238 79.6446228,88.3943645 L79.6446228,88.3943646 L79.6446228,138.232794 C79.6446228,144.131009 74.8631748,148.912457 68.9649597,148.912457 C63.0667446,148.912457 58.2852966,144.131009 58.2852966,138.232794 Z M65.405072,-14.8423767 L72.5248474,-14.8423767 L76.0847351,-0.690681892 L72.5248474,6.51694947 L72.5248474,81.2745911 L65.405072,81.2745911 L65.405072,6.51694947 L61.8451843,-0.690681892 L65.405072,-14.8423767 Z" transform="translate(68.964960, 67.035040) rotate(45.000000) translate(-68.964960, -67.035040) "></path>
</g>
</svg>
<svg class="tc-image-tip tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M64,128.241818 C99.346224,128.241818 128,99.5880417 128,64.2418177 C128,28.8955937 99.346224,0.241817675 64,0.241817675 C28.653776,0.241817675 0,28.8955937 0,64.2418177 C0,99.5880417 28.653776,128.241818 64,128.241818 Z M75.9358659,91.4531941 C75.3115438,95.581915 70.2059206,98.8016748 64,98.8016748 C57.7940794,98.8016748 52.6884562,95.581915 52.0641341,91.4531941 C54.3299053,94.0502127 58.8248941,95.8192805 64,95.8192805 C69.1751059,95.8192805 73.6700947,94.0502127 75.9358659,91.4531941 L75.9358659,91.4531941 Z M75.9358659,95.9453413 C75.3115438,100.074062 70.2059206,103.293822 64,103.293822 C57.7940794,103.293822 52.6884562,100.074062 52.0641341,95.9453413 C54.3299053,98.5423599 58.8248941,100.311428 64,100.311428 C69.1751059,100.311428 73.6700947,98.5423599 75.9358659,95.9453413 L75.9358659,95.9453413 Z M75.9358659,100.40119 C75.3115438,104.529911 70.2059206,107.74967 64,107.74967 C57.7940794,107.74967 52.6884562,104.529911 52.0641341,100.40119 C54.3299053,102.998208 58.8248941,104.767276 64,104.767276 C69.1751059,104.767276 73.6700947,102.998208 75.9358659,100.40119 L75.9358659,100.40119 Z M75.9358659,104.893337 C75.3115438,109.022058 70.2059206,112.241818 64,112.241818 C57.7940794,112.241818 52.6884562,109.022058 52.0641341,104.893337 C54.3299053,107.490356 58.8248941,109.259423 64,109.259423 C69.1751059,109.259423 73.6700947,107.490356 75.9358659,104.893337 L75.9358659,104.893337 Z M64.3010456,24.2418177 C75.9193117,24.2418188 88.0000013,32.0619847 88,48.4419659 C87.9999987,64.8219472 75.9193018,71.7540963 75.9193021,83.5755932 C75.9193022,89.4486648 70.0521957,92.8368862 63.9999994,92.8368862 C57.947803,92.8368862 51.9731007,89.8295115 51.9731007,83.5755932 C51.9731007,71.1469799 39.9999998,65.4700602 40,48.4419647 C40.0000002,31.4138691 52.6827796,24.2418166 64.3010456,24.2418177 Z"></path>
</g>
</svg>
<svg class="tc-image-twitter tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M41.6263422,115.803477 C27.0279663,115.803477 13.4398394,111.540813 1.99987456,104.234833 C4.02221627,104.472643 6.08004574,104.594302 8.16644978,104.594302 C20.277456,104.594302 31.4238403,100.47763 40.270894,93.5715185 C28.9590538,93.3635501 19.4123842,85.9189246 16.1230832,75.6885328 C17.7011365,75.9892376 19.320669,76.1503787 20.9862896,76.1503787 C23.344152,76.1503787 25.6278127,75.8359011 27.7971751,75.247346 C15.9709927,72.8821073 7.06079851,62.4745062 7.06079851,49.9982394 C7.06079851,49.8898938 7.06079851,49.7820074 7.06264203,49.67458 C10.5482779,51.6032228 14.5339687,52.7615103 18.7717609,52.8951059 C11.8355159,48.277565 7.2714207,40.3958845 7.2714207,31.4624258 C7.2714207,26.7434257 8.54621495,22.3200804 10.7713439,18.5169676 C23.5211299,34.0957738 42.568842,44.3472839 64.0532269,45.4210985 C63.6126256,43.5365285 63.3835682,41.5711584 63.3835682,39.5529928 C63.3835682,25.3326379 74.95811,13.8034766 89.2347917,13.8034766 C96.6697089,13.8034766 103.387958,16.930807 108.103682,21.9353619 C113.991886,20.780288 119.52429,18.6372496 124.518847,15.6866694 C122.588682,21.6993889 118.490075,26.7457211 113.152623,29.9327334 C118.381769,29.3102055 123.363882,27.926045 127.999875,25.8780385 C124.534056,31.0418981 120.151087,35.5772616 115.100763,39.2077561 C115.150538,40.3118708 115.175426,41.4224128 115.175426,42.538923 C115.175426,76.5663154 89.1744164,115.803477 41.6263422,115.803477"></path>
</g>
</svg>
<svg class="tc-image-unfold-all tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<rect x="0" y="0" width="128" height="16" rx="8"></rect>
<rect x="0" y="64" width="128" height="16" rx="8"></rect>
<path d="M85.598226,8.34884273 C84.1490432,6.89863875 82.1463102,6 79.9340286,6 L47.9482224,6 C43.5292967,6 39.9411255,9.581722 39.9411255,14 C39.9411255,18.4092877 43.5260249,22 47.9482224,22 L71.9411255,22 L71.9411255,45.9929031 C71.9411255,50.4118288 75.5228475,54 79.9411255,54 C84.3504132,54 87.9411255,50.4151006 87.9411255,45.9929031 L87.9411255,14.0070969 C87.9411255,11.7964515 87.0447363,9.79371715 85.5956548,8.34412458 Z" transform="translate(63.941125, 30.000000) scale(1, -1) rotate(-45.000000) translate(-63.941125, -30.000000) "></path>
<path d="M85.6571005,72.2899682 C84.2079177,70.8397642 82.2051847,69.9411255 79.9929031,69.9411255 L48.0070969,69.9411255 C43.5881712,69.9411255 40,73.5228475 40,77.9411255 C40,82.3504132 43.5848994,85.9411255 48.0070969,85.9411255 L72,85.9411255 L72,109.934029 C72,114.352954 75.581722,117.941125 80,117.941125 C84.4092877,117.941125 88,114.356226 88,109.934029 L88,77.9482224 C88,75.737577 87.1036108,73.7348426 85.6545293,72.2852501 Z" transform="translate(64.000000, 93.941125) scale(1, -1) rotate(-45.000000) translate(-64.000000, -93.941125) "></path>
</g>
</svg>
<svg class="tc-image-unfold tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<rect x="0" y="0" width="128" height="16" rx="8"></rect>
<path d="M85.598226,11.3488427 C84.1490432,9.89863875 82.1463102,9 79.9340286,9 L47.9482224,9 C43.5292967,9 39.9411255,12.581722 39.9411255,17 C39.9411255,21.4092877 43.5260249,25 47.9482224,25 L71.9411255,25 L71.9411255,48.9929031 C71.9411255,53.4118288 75.5228475,57 79.9411255,57 C84.3504132,57 87.9411255,53.4151006 87.9411255,48.9929031 L87.9411255,17.0070969 C87.9411255,14.7964515 87.0447363,12.7937171 85.5956548,11.3441246 Z" transform="translate(63.941125, 33.000000) scale(1, -1) rotate(-45.000000) translate(-63.941125, -33.000000) "></path>
<path d="M85.6571005,53.4077172 C84.2079177,51.9575133 82.2051847,51.0588745 79.9929031,51.0588745 L48.0070969,51.0588745 C43.5881712,51.0588745 40,54.6405965 40,59.0588745 C40,63.4681622 43.5848994,67.0588745 48.0070969,67.0588745 L72,67.0588745 L72,91.0517776 C72,95.4707033 75.581722,99.0588745 80,99.0588745 C84.4092877,99.0588745 88,95.4739751 88,91.0517776 L88,59.0659714 C88,56.855326 87.1036108,54.8525917 85.6545293,53.4029991 Z" transform="translate(64.000000, 75.058875) scale(1, -1) rotate(-45.000000) translate(-64.000000, -75.058875) "></path>
</g>
</svg>
<svg class="tc-image-unlocked-padlock tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M48.6266053,64 L105,64 L105,96.0097716 C105,113.673909 90.6736461,128 73.001193,128 L55.998807,128 C38.3179793,128 24,113.677487 24,96.0097716 L24,64 L30.136303,64 C19.6806213,51.3490406 2.77158986,28.2115132 25.8366966,8.85759246 C50.4723026,-11.8141335 71.6711028,13.2108337 81.613302,25.0594855 C91.5555012,36.9081373 78.9368488,47.4964439 69.1559674,34.9513593 C59.375086,22.4062748 47.9893192,10.8049522 35.9485154,20.9083862 C23.9077117,31.0118202 34.192312,43.2685325 44.7624679,55.8655518 C47.229397,58.805523 48.403443,61.5979188 48.6266053,64 Z M67.7315279,92.3641717 C70.8232551,91.0923621 73,88.0503841 73,84.5 C73,79.8055796 69.1944204,76 64.5,76 C59.8055796,76 56,79.8055796 56,84.5 C56,87.947435 58.0523387,90.9155206 61.0018621,92.2491029 L55.9067479,115.020857 L72.8008958,115.020857 L67.7315279,92.3641717 L67.7315279,92.3641717 Z"></path>
</g>
</svg>
<svg class="tc-image-up-arrow tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<path transform="rotate(-135, 63.8945, 64.1752)" d="m109.07576,109.35336c-1.43248,1.43361 -3.41136,2.32182 -5.59717,2.32182l-79.16816,0c-4.36519,0 -7.91592,-3.5444 -7.91592,-7.91666c0,-4.36337 3.54408,-7.91667 7.91592,-7.91667l71.25075,0l0,-71.25074c0,-4.3652 3.54442,-7.91592 7.91667,-7.91592c4.36336,0 7.91667,3.54408 7.91667,7.91592l0,79.16815c0,2.1825 -0.88602,4.16136 -2.3185,5.59467l-0.00027,-0.00056l0.00001,-0.00001z" />
</svg>
<svg class="tc-image-video tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M64,12 C29.0909091,12 8.72727273,14.9166667 5.81818182,17.8333333 C2.90909091,20.75 1.93784382e-15,41.1666667 0,64.5 C1.93784382e-15,87.8333333 2.90909091,108.25 5.81818182,111.166667 C8.72727273,114.083333 29.0909091,117 64,117 C98.9090909,117 119.272727,114.083333 122.181818,111.166667 C125.090909,108.25 128,87.8333333 128,64.5 C128,41.1666667 125.090909,20.75 122.181818,17.8333333 C119.272727,14.9166667 98.9090909,12 64,12 Z M54.9161194,44.6182253 C51.102648,42.0759111 48.0112186,43.7391738 48.0112186,48.3159447 L48.0112186,79.6840553 C48.0112186,84.2685636 51.109784,85.9193316 54.9161194,83.3817747 L77.0838806,68.6032672 C80.897352,66.0609529 80.890216,61.9342897 77.0838806,59.3967328 L54.9161194,44.6182253 Z"></path>
</g>
</svg>
<svg class="tc-image-warning tc-image-button" width="22pt" height="22pt" viewBox="0 0 128 128">
<g fill-rule="evenodd">
<path d="M57.0717968,11 C60.1509982,5.66666667 67.8490018,5.66666667 70.9282032,11 L126.353829,107 C129.433031,112.333333 125.584029,119 119.425626,119 L8.57437416,119 C2.41597129,119 -1.43303051,112.333333 1.64617093,107 L57.0717968,11 Z M64,37 C59.581722,37 56,40.5820489 56,44.9935776 L56,73.0064224 C56,77.4211534 59.5907123,81 64,81 C68.418278,81 72,77.4179511 72,73.0064224 L72,44.9935776 C72,40.5788466 68.4092877,37 64,37 Z M64,104 C68.418278,104 72,100.418278 72,96 C72,91.581722 68.418278,88 64,88 C59.581722,88 56,91.581722 56,96 C56,100.418278 59.581722,104 64,104 Z"></path>
</g>
</svg>
\define colour(name)
<$transclude tiddler={{$:/palette}} index="$name$"><$transclude tiddler="$:/palettes/Vanilla" index="$name$"/></$transclude>
\end
\define color(name)
<<colour $name$>>
\end
\define box-shadow(shadow)
``
-webkit-box-shadow: $shadow$;
-moz-box-shadow: $shadow$;
box-shadow: $shadow$;
``
\end
\define filter(filter)
``
-webkit-filter: $filter$;
-moz-filter: $filter$;
filter: $filter$;
``
\end
\define transition(transition)
``
-webkit-transition: $transition$;
-moz-transition: $transition$;
transition: $transition$;
``
\end
\define transform-origin(origin)
``
-webkit-transform-origin: $origin$;
-moz-transform-origin: $origin$;
transform-origin: $origin$;
``
\end
\define background-linear-gradient(gradient)
``
background-image: linear-gradient($gradient$);
background-image: -o-linear-gradient($gradient$);
background-image: -moz-linear-gradient($gradient$);
background-image: -webkit-linear-gradient($gradient$);
background-image: -ms-linear-gradient($gradient$);
``
\end
\define datauri(title)
<$macrocall $name="makedatauri" type={{$title$!!type}} text={{$title$}}/>
\end
\define if-sidebar(text)
<$reveal state="$:/state/sidebar" type="match" text="yes" default="yes">$text$</$reveal>
\end
\define if-no-sidebar(text)
<$reveal state="$:/state/sidebar" type="nomatch" text="yes" default="yes">$text$</$reveal>
\end
\define exportButtonFilename(baseFilename)
$baseFilename$$(extension)$
\end
\define exportButton(exportFilter:"[!is[system]sort[title]]",lingoBase,baseFilename:"tiddlers")
<span class="tc-popup-keep">
<$button popup=<<qualify "$:/state/popup/export">> tooltip={{$lingoBase$Hint}} aria-label={{$lingoBase$Caption}} class=<<tv-config-toolbar-class>> selectedClass="tc-selected">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/export-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$lingoBase$Caption}}/></span>
</$list>
</$button>
</span>
<$reveal state=<<qualify "$:/state/popup/export">> type="popup" position="below" animate="yes">
<div class="tc-drop-down">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/Exporter]]">
<$set name="extension" value={{!!extension}}>
<$button class="tc-btn-invisible">
<$action-sendmessage $message="tm-download-file" $param=<<currentTiddler>> exportFilter="""$exportFilter$""" filename=<<exportButtonFilename """$baseFilename$""">>/>
<$action-deletetiddler $tiddler=<<qualify "$:/state/popup/export">>/>
<$transclude field="description"/>
</$button>
</$set>
</$list>
</div>
</$reveal>
\end
\define lingo-base()
$:/language/
\end
\define lingo(title)
{{$(lingo-base)$$title$}}
\end
\define list-links(filter,type:"ul",subtype:"li",class:"")
<$type$ class="$class$">
<$list filter="$filter$">
<$subtype$>
<$link to={{!!title}}>
<$transclude field="caption">
<$view field="title"/>
</$transclude>
</$link>
</$subtype$>
</$list>
</$type$>
\end
\define tabs(tabsList,default,state:"$:/state/tab",class,template)
<div class="tc-tab-set $class$">
<div class="tc-tab-buttons $class$">
<$list filter="$tabsList$" variable="currentTab"><$set name="save-currentTiddler" value=<<currentTiddler>>><$tiddler tiddler=<<currentTab>>><$button set=<<qualify "$state$">> setTo=<<currentTab>> default="$default$" selectedClass="tc-tab-selected" tooltip={{!!tooltip}}>
<$tiddler tiddler=<<save-currentTiddler>>>
<$set name="tv-wikilinks" value="no">
<$transclude tiddler=<<currentTab>> field="caption">
<$macrocall $name="currentTab" $type="text/plain" $output="text/plain"/>
</$transclude>
</$set></$tiddler></$button></$tiddler></$set></$list>
</div>
<div class="tc-tab-divider $class$"/>
<div class="tc-tab-content $class$">
<$list filter="$tabsList$" variable="currentTab">
<$reveal type="match" state=<<qualify "$state$">> text=<<currentTab>> default="$default$">
<$transclude tiddler="$template$" mode="block">
<$transclude tiddler=<<currentTab>> mode="block"/>
</$transclude>
</$reveal>
</$list>
</div>
</div>
\end
\define tag(tag)
{{$tag$||$:/core/ui/TagTemplate}}
\end
\define thumbnail(link,icon,color,background-color,image,caption,width:"280",height:"157")
<$link to="""$link$"""><div class="tc-thumbnail-wrapper">
<div class="tc-thumbnail-image" style="width:$width$px;height:$height$px;"><$reveal type="nomatch" text="" default="""$image$""" tag="div" style="width:$width$px;height:$height$px;">
[img[$image$]]
</$reveal><$reveal type="match" text="" default="""$image$""" tag="div" class="tc-thumbnail-background" style="width:$width$px;height:$height$px;background-color:$background-color$;"></$reveal></div><div class="tc-thumbnail-icon" style="fill:$color$;color:$color$;">
$icon$
</div><div class="tc-thumbnail-caption">
$caption$
</div>
</div></$link>
\end
\define thumbnail-right(link,icon,color,background-color,image,caption,width:"280",height:"157")
<div class="tc-thumbnail-right-wrapper"><<thumbnail """$link$""" """$icon$""" """$color$""" """$background-color$""" """$image$""" """$caption$""" """$width$""" """$height$""">></div>
\end
\define list-thumbnails(filter,width:"280",height:"157")
<$list filter="""$filter$"""><$macrocall $name="thumbnail" link={{!!link}} icon={{!!icon}} color={{!!color}} background-color={{!!background-color}} image={{!!image}} caption={{!!caption}} width="""$width$""" height="""$height$"""/></$list>
\end
\define timeline-title()
<!-- Override this macro with a global macro
of the same name if you need to change
how titles are displayed on the timeline
-->
<$view field="title"/>
\end
\define timeline(limit:"100",format:"DDth MMM YYYY",subfilter:"",dateField:"modified")
<div class="tc-timeline">
<$list filter="[!is[system]$subfilter$has[$dateField$]!sort[$dateField$]limit[$limit$]eachday[$dateField$]]">
<div class="tc-menu-list-item">
<$view field="$dateField$" format="date" template="$format$"/>
<$list filter="[sameday:$dateField${!!$dateField$}!is[system]$subfilter$!sort[$dateField$]]">
<div class="tc-menu-list-subitem">
<$link to={{!!title}}>
<<timeline-title>>
</$link>
</div>
</$list>
</div>
</$list>
</div>
\end
\define toc-caption()
<$set name="tv-wikilinks" value="no">
<$transclude field="caption">
<$view field="title"/>
</$transclude>
</$set>
\end
\define toc-body(rootTag,tag,sort:"",itemClassFilter)
<ol class="tc-toc">
<$list filter="""[all[shadows+tiddlers]tag[$tag$]!has[draft.of]$sort$]""">
<$set name="toc-item-class" filter="""$itemClassFilter$""" value="toc-item-selected" emptyValue="toc-item">
<li class=<<toc-item-class>>>
<$list filter="[all[current]toc-link[no]]" emptyMessage="<$link><$view field='caption'><$view field='title'/></$view></$link>">
<<toc-caption>>
</$list>
<$list filter="""[all[current]] -[[$rootTag$]]""">
<$macrocall $name="toc-body" rootTag="""$rootTag$""" tag=<<currentTiddler>> sort="""$sort$""" itemClassFilter="""$itemClassFilter$"""/>
</$list>
</li>
</$set>
</$list>
</ol>
\end
\define toc(tag,sort:"",itemClassFilter)
<<toc-body rootTag:"""$tag$""" tag:"""$tag$""" sort:"""$sort$""" itemClassFilter:"""itemClassFilter""">>
\end
\define toc-linked-expandable-body(tag,sort:"",itemClassFilter)
<$set name="toc-state" value=<<qualify "$:/state/toc/$tag$-$(currentTiddler)$">>>
<$set name="toc-item-class" filter="""$itemClassFilter$""" value="toc-item-selected" emptyValue="toc-item">
<li class=<<toc-item-class>>>
<$link>
<$reveal type="nomatch" state=<<toc-state>> text="open">
<$button set=<<toc-state>> setTo="open" class="tc-btn-invisible">
{{$:/core/images/right-arrow}}
</$button>
</$reveal>
<$reveal type="match" state=<<toc-state>> text="open">
<$button set=<<toc-state>> setTo="close" class="tc-btn-invisible">
{{$:/core/images/down-arrow}}
</$button>
</$reveal>
<<toc-caption>>
</$link>
<$reveal type="match" state=<<toc-state>> text="open">
<$macrocall $name="toc-expandable" tag=<<currentTiddler>> sort="""$sort$""" itemClassFilter="""$itemClassFilter$"""/>
</$reveal>
</li>
</$set>
</$set>
\end
\define toc-unlinked-expandable-body(tag,sort:"",itemClassFilter)
<$set name="toc-state" value=<<qualify "$:/state/toc/$tag$-$(currentTiddler)$">>>
<$set name="toc-item-class" filter="""$itemClassFilter$""" value="toc-item-selected" emptyValue="toc-item">
<li class=<<toc-item-class>>>
<$reveal type="nomatch" state=<<toc-state>> text="open">
<$button set=<<toc-state>> setTo="open" class="tc-btn-invisible">
{{$:/core/images/right-arrow}}
<<toc-caption>>
</$button>
</$reveal>
<$reveal type="match" state=<<toc-state>> text="open">
<$button set=<<toc-state>> setTo="close" class="tc-btn-invisible">
{{$:/core/images/down-arrow}}
<<toc-caption>>
</$button>
</$reveal>
<$reveal type="match" state=<<toc-state>> text="open">
<$macrocall $name="toc-expandable" tag=<<currentTiddler>> sort="""$sort$""" itemClassFilter="""$itemClassFilter$"""/>
</$reveal>
</li>
</$set>
</$set>
\end
\define toc-expandable(tag,sort:"",itemClassFilter)
<ol class="tc-toc toc-expandable">
<$list filter="[all[shadows+tiddlers]tag[$tag$]!has[draft.of]$sort$]">
<$list filter="[all[current]toc-link[no]]" emptyMessage="<<toc-linked-expandable-body tag:'$tag$' sort:'$sort$' itemClassFilter:'$itemClassFilter$'>>">
<<toc-unlinked-expandable-body tag:"""$tag$""" sort:"""$sort$""" itemClassFilter:"""itemClassFilter""">>
</$list>
</$list>
</ol>
\end
\define toc-linked-selective-expandable-body(tag,sort:"",itemClassFilter)
<$set name="toc-state" value=<<qualify "$:/state/toc/$tag$-$(currentTiddler)$">>>
<$set name="toc-item-class" filter="""$itemClassFilter$""" value="toc-item-selected" emptyValue="toc-item">
<li class=<<toc-item-class>>>
<$link>
<$list filter="[all[current]tagging[]limit[1]]" variable="ignore" emptyMessage="<$button class='tc-btn-invisible'>{{$:/core/images/blank}}</$button>">
<$reveal type="nomatch" state=<<toc-state>> text="open">
<$button set=<<toc-state>> setTo="open" class="tc-btn-invisible">
{{$:/core/images/right-arrow}}
</$button>
</$reveal>
<$reveal type="match" state=<<toc-state>> text="open">
<$button set=<<toc-state>> setTo="close" class="tc-btn-invisible">
{{$:/core/images/down-arrow}}
</$button>
</$reveal>
</$list>
<<toc-caption>>
</$link>
<$reveal type="match" state=<<toc-state>> text="open">
<$macrocall $name="toc-selective-expandable" tag=<<currentTiddler>> sort="""$sort$""" itemClassFilter="""$itemClassFilter$"""/>
</$reveal>
</li>
</$set>
</$set>
\end
\define toc-unlinked-selective-expandable-body(tag,sort:"",itemClassFilter)
<$set name="toc-state" value=<<qualify "$:/state/toc/$tag$-$(currentTiddler)$">>>
<$set name="toc-item-class" filter="""$itemClassFilter$""" value="toc-item-selected" emptyValue="toc-item">
<li class=<<toc-item-class>>>
<$list filter="[all[current]tagging[]limit[1]]" variable="ignore" emptyMessage="<$button class='tc-btn-invisible'>{{$:/core/images/blank}}</$button> <$view field='caption'><$view field='title'/></$view>">
<$reveal type="nomatch" state=<<toc-state>> text="open">
<$button set=<<toc-state>> setTo="open" class="tc-btn-invisible">
{{$:/core/images/right-arrow}}
<<toc-caption>>
</$button>
</$reveal>
<$reveal type="match" state=<<toc-state>> text="open">
<$button set=<<toc-state>> setTo="close" class="tc-btn-invisible">
{{$:/core/images/down-arrow}}
<<toc-caption>>
</$button>
</$reveal>
</$list>
<$reveal type="match" state=<<toc-state>> text="open">
<$macrocall $name="""toc-selective-expandable""" tag=<<currentTiddler>> sort="""$sort$""" itemClassFilter="""$itemClassFilter$"""/>
</$reveal>
</li>
</$set>
</$set>
\end
\define toc-selective-expandable(tag,sort:"",itemClassFilter)
<ol class="tc-toc toc-selective-expandable">
<$list filter="[all[shadows+tiddlers]tag[$tag$]!has[draft.of]$sort$]">
<$list filter="[all[current]toc-link[no]]" variable="ignore" emptyMessage="<<toc-linked-selective-expandable-body tag:'$tag$' sort:'$sort$' itemClassFilter:'$itemClassFilter$'>>">
<<toc-unlinked-selective-expandable-body tag:"""$tag$""" sort:"""$sort$""" itemClassFilter:"""$itemClassFilter$""">>
</$list>
</$list>
</ol>
\end
\define toc-tabbed-selected-item-filter(selectedTiddler)
[all[current]field:title{$selectedTiddler$}]
\end
\define toc-tabbed-external-nav(tag,sort:"",selectedTiddler:"$:/temp/toc/selectedTiddler",unselectedText,missingText,template:"")
<$tiddler tiddler={{$selectedTiddler$}}>
<div class="tc-tabbed-table-of-contents">
<$linkcatcher to="$selectedTiddler$">
<div class="tc-table-of-contents">
<$macrocall $name="toc-selective-expandable" tag="""$tag$""" sort="""$sort$""" itemClassFilter=<<toc-tabbed-selected-item-filter selectedTiddler:"""$selectedTiddler$""">>/>
</div>
</$linkcatcher>
<div class="tc-tabbed-table-of-contents-content">
<$reveal state="""$selectedTiddler$""" type="nomatch" text="">
<$transclude mode="block" tiddler="$template$">
<h1><<toc-caption>></h1>
<$transclude mode="block">$missingText$</$transclude>
</$transclude>
</$reveal>
<$reveal state="""$selectedTiddler$""" type="match" text="">
$unselectedText$
</$reveal>
</div>
</div>
</$tiddler>
\end
\define toc-tabbed-internal-nav(tag,sort:"",selectedTiddler:"$:/temp/toc/selectedTiddler",unselectedText,missingText,template:"")
<$linkcatcher to="""$selectedTiddler$""">
<$macrocall $name="toc-tabbed-external-nav" tag="""$tag$""" sort="""$sort$""" selectedTiddler="""$selectedTiddler$""" unselectedText="""$unselectedText$""" missingText="""$missingText$""" template="""$template$"""/>
</$linkcatcher>
\end
/*\
title: $:/core/modules/browser-messaging.js
type: application/javascript
module-type: startup
Browser message handling
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "browser-messaging";
exports.platforms = ["browser"];
exports.after = ["startup"];
exports.synchronous = true;
/*
Load a specified url as an iframe and call the callback when it is loaded. If the url is already loaded then the existing iframe instance is used
*/
function loadIFrame(url,callback) {
// Check if iframe already exists
var iframeInfo = $tw.browserMessaging.iframeInfoMap[url];
if(iframeInfo) {
// We've already got the iframe
callback(null,iframeInfo);
} else {
// Create the iframe and save it in the list
var iframe = document.createElement("iframe"),
iframeInfo = {
url: url,
status: "loading",
domNode: iframe
};
$tw.browserMessaging.iframeInfoMap[url] = iframeInfo;
saveIFrameInfoTiddler(iframeInfo);
// Add the iframe to the DOM and hide it
iframe.style.display = "none";
document.body.appendChild(iframe);
// Set up onload
iframe.onload = function() {
iframeInfo.status = "loaded";
saveIFrameInfoTiddler(iframeInfo);
callback(null,iframeInfo);
};
iframe.onerror = function() {
callback("Cannot load iframe");
};
try {
iframe.src = url;
} catch(ex) {
callback(ex);
}
}
}
function saveIFrameInfoTiddler(iframeInfo) {
$tw.wiki.addTiddler(new $tw.Tiddler($tw.wiki.getCreationFields(),{
title: "$:/temp/ServerConnection/" + iframeInfo.url,
text: iframeInfo.status,
tags: ["$:/tags/ServerConnection"],
url: iframeInfo.url
},$tw.wiki.getModificationFields()));
}
exports.startup = function() {
// Initialise the store of iframes we've created
$tw.browserMessaging = {
iframeInfoMap: {} // Hashmap by URL of {url:,status:"loading/loaded",domNode:}
};
// Listen for widget messages to control loading the plugin library
$tw.rootWidget.addEventListener("tm-load-plugin-library",function(event) {
var paramObject = event.paramObject || {},
url = paramObject.url;
if(url) {
loadIFrame(url,function(err,iframeInfo) {
if(err) {
alert("Error loading plugin library: " + url);
} else {
iframeInfo.domNode.contentWindow.postMessage({
verb: "GET",
url: "recipes/library/tiddlers.json",
cookies: {
type: "save-info",
infoTitlePrefix: paramObject.infoTitlePrefix || "$:/temp/RemoteAssetInfo/",
url: url
}
},"*");
}
});
}
});
$tw.rootWidget.addEventListener("tm-load-plugin-from-library",function(event) {
var paramObject = event.paramObject || {},
url = paramObject.url,
title = paramObject.title;
if(url && title) {
loadIFrame(url,function(err,iframeInfo) {
if(err) {
alert("Error loading plugin library: " + url);
} else {
iframeInfo.domNode.contentWindow.postMessage({
verb: "GET",
url: "recipes/library/tiddlers/" + encodeURIComponent(title) + ".json",
cookies: {
type: "save-tiddler",
url: url
}
},"*");
}
});
}
});
// Listen for window messages from other windows
window.addEventListener("message",function listener(event){
console.log("browser-messaging: ",document.location.toString())
console.log("browser-messaging: Received message from",event.origin);
console.log("browser-messaging: Message content",event.data);
switch(event.data.verb) {
case "GET-RESPONSE":
if(event.data.status.charAt(0) === "2") {
if(event.data.cookies) {
if(event.data.cookies.type === "save-info") {
var tiddlers = JSON.parse(event.data.body);
$tw.utils.each(tiddlers,function(tiddler) {
$tw.wiki.addTiddler(new $tw.Tiddler($tw.wiki.getCreationFields(),tiddler,{
title: event.data.cookies.infoTitlePrefix + event.data.cookies.url + "/" + tiddler.title,
"original-title": tiddler.title,
text: "",
type: "text/vnd.tiddlywiki",
"original-type": tiddler.type,
"plugin-type": undefined,
"original-plugin-type": tiddler["plugin-type"],
"module-type": undefined,
"original-module-type": tiddler["module-type"],
tags: ["$:/tags/RemoteAssetInfo"],
"original-tags": $tw.utils.stringifyList(tiddler.tags || []),
"server-url": event.data.cookies.url
},$tw.wiki.getModificationFields()));
});
} else if(event.data.cookies.type === "save-tiddler") {
var tiddler = JSON.parse(event.data.body);
$tw.wiki.addTiddler(new $tw.Tiddler(tiddler));
}
}
}
break;
}
},false);
};
})();
/*\
title: $:/core/modules/commander.js
type: application/javascript
module-type: global
The $tw.Commander class is a command interpreter
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Parse a sequence of commands
commandTokens: an array of command string tokens
wiki: reference to the wiki store object
streams: {output:, error:}, each of which has a write(string) method
callback: a callback invoked as callback(err) where err is null if there was no error
*/
var Commander = function(commandTokens,callback,wiki,streams) {
var path = require("path");
this.commandTokens = commandTokens;
this.nextToken = 0;
this.callback = callback;
this.wiki = wiki;
this.streams = streams;
this.outputPath = path.resolve($tw.boot.wikiPath,$tw.config.wikiOutputSubDir);
};
/*
Add a string of tokens to the command queue
*/
Commander.prototype.addCommandTokens = function(commandTokens) {
var params = commandTokens.slice(0);
params.unshift(0);
params.unshift(this.nextToken);
Array.prototype.splice.apply(this.commandTokens,params);
};
/*
Execute the sequence of commands and invoke a callback on completion
*/
Commander.prototype.execute = function() {
this.executeNextCommand();
};
/*
Execute the next command in the sequence
*/
Commander.prototype.executeNextCommand = function() {
var self = this;
// Invoke the callback if there are no more commands
if(this.nextToken >= this.commandTokens.length) {
this.callback(null);
} else {
// Get and check the command token
var commandName = this.commandTokens[this.nextToken++];
if(commandName.substr(0,2) !== "--") {
this.callback("Missing command: " + commandName);
} else {
commandName = commandName.substr(2); // Trim off the --
// Accumulate the parameters to the command
var params = [];
while(this.nextToken < this.commandTokens.length &&
this.commandTokens[this.nextToken].substr(0,2) !== "--") {
params.push(this.commandTokens[this.nextToken++]);
}
// Get the command info
var command = $tw.commands[commandName],
c,err;
if(!command) {
this.callback("Unknown command: " + commandName);
} else {
if(this.verbose) {
this.streams.output.write("Executing command: " + commandName + " " + params.join(" ") + "\n");
}
if(command.info.synchronous) {
// Synchronous command
c = new command.Command(params,this);
err = c.execute();
if(err) {
this.callback(err);
} else {
this.executeNextCommand();
}
} else {
// Asynchronous command
c = new command.Command(params,this,function(err) {
if(err) {
self.callback(err);
} else {
self.executeNextCommand();
}
});
err = c.execute();
if(err) {
this.callback(err);
}
}
}
}
}
};
Commander.initCommands = function(moduleType) {
moduleType = moduleType || "command";
$tw.commands = {};
$tw.modules.forEachModuleOfType(moduleType,function(title,module) {
var c = $tw.commands[module.info.name] = {};
// Add the methods defined by the module
for(var f in module) {
if($tw.utils.hop(module,f)) {
c[f] = module[f];
}
}
});
};
exports.Commander = Commander;
})();
/*\
title: $:/core/modules/commands/build.js
type: application/javascript
module-type: command
Command to build a build target
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "build",
synchronous: true
};
var Command = function(params,commander) {
this.params = params;
this.commander = commander;
};
Command.prototype.execute = function() {
// Get the build targets defined in the wiki
var buildTargets = $tw.boot.wikiInfo.build;
if(!buildTargets) {
return "No build targets defined";
}
// Loop through each of the specified targets
var targets;
if(this.params.length > 0) {
targets = this.params;
} else {
targets = Object.keys(buildTargets);
}
for(var targetIndex=0; targetIndex<targets.length; targetIndex++) {
var target = targets[targetIndex],
commands = buildTargets[target];
if(!commands) {
return "Build target '" + target + "' not found";
}
// Add the commands to the queue
this.commander.addCommandTokens(commands);
}
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/clearpassword.js
type: application/javascript
module-type: command
Clear password for crypto operations
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "clearpassword",
synchronous: true
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
$tw.crypto.setPassword(null);
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/editions.js
type: application/javascript
module-type: command
Command to list the available editions
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "editions",
synchronous: true
};
var Command = function(params,commander) {
this.params = params;
this.commander = commander;
};
Command.prototype.execute = function() {
var self = this;
// Output the list
this.commander.streams.output.write("Available editions:\n\n");
var editionInfo = $tw.utils.getEditionInfo();
$tw.utils.each(editionInfo,function(info,name) {
self.commander.streams.output.write(" " + name + ": " + info.description + "\n");
});
this.commander.streams.output.write("\n");
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/help.js
type: application/javascript
module-type: command
Help command
\*/
(function(){
/*jshint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "help",
synchronous: true
};
var Command = function(params,commander) {
this.params = params;
this.commander = commander;
};
Command.prototype.execute = function() {
var subhelp = this.params[0] || "default",
helpBase = "$:/language/Help/",
text;
if(!this.commander.wiki.getTiddler(helpBase + subhelp)) {
subhelp = "notfound";
}
// Wikify the help as formatted text (ie block elements generate newlines)
text = this.commander.wiki.renderTiddler("text/plain-formatted",helpBase + subhelp);
// Remove any leading linebreaks
text = text.replace(/^(\r?\n)*/g,"");
this.commander.streams.output.write(text);
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/init.js
type: application/javascript
module-type: command
Command to initialise an empty wiki folder
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "init",
synchronous: true
};
var Command = function(params,commander) {
this.params = params;
this.commander = commander;
};
Command.prototype.execute = function() {
var fs = require("fs"),
path = require("path");
// Check that we don't already have a valid wiki folder
if($tw.boot.wikiTiddlersPath || ($tw.utils.isDirectory($tw.boot.wikiPath) && !$tw.utils.isDirectoryEmpty($tw.boot.wikiPath))) {
return "Wiki folder is not empty";
}
// Loop through each of the specified editions
var editions = this.params.length > 0 ? this.params : ["empty"];
for(var editionIndex=0; editionIndex<editions.length; editionIndex++) {
var editionName = editions[editionIndex];
// Check the edition exists
var editionPath = $tw.findLibraryItem(editionName,$tw.getLibraryItemSearchPaths($tw.config.editionsPath,$tw.config.editionsEnvVar));
if(!$tw.utils.isDirectory(editionPath)) {
return "Edition '" + editionName + "' not found";
}
// Copy the edition content
var err = $tw.utils.copyDirectory(editionPath,$tw.boot.wikiPath);
if(!err) {
this.commander.streams.output.write("Copied edition '" + editionName + "' to " + $tw.boot.wikiPath + "\n");
} else {
return err;
}
}
// Tweak the tiddlywiki.info to remove any included wikis
var packagePath = $tw.boot.wikiPath + "/tiddlywiki.info",
packageJson = JSON.parse(fs.readFileSync(packagePath));
delete packageJson.includeWikis;
fs.writeFileSync(packagePath,JSON.stringify(packageJson,null,$tw.config.preferences.jsonSpaces));
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/load.js
type: application/javascript
module-type: command
Command to load tiddlers from a file
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "load",
synchronous: false
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
var self = this,
fs = require("fs"),
path = require("path");
if(this.params.length < 1) {
return "Missing filename";
}
var ext = path.extname(self.params[0]);
fs.readFile(this.params[0],$tw.utils.getTypeEncoding(ext),function(err,data) {
if (err) {
self.callback(err);
} else {
var fields = {title: self.params[0]},
type = path.extname(self.params[0]);
var tiddlers = self.commander.wiki.deserializeTiddlers(type,data,fields);
if(!tiddlers) {
self.callback("No tiddlers found in file \"" + self.params[0] + "\"");
} else {
for(var t=0; t<tiddlers.length; t++) {
self.commander.wiki.importTiddler(new $tw.Tiddler(tiddlers[t]));
}
self.callback(null);
}
}
});
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/makelibrary.js
type: application/javascript
module-type: command
Command to pack all of the plugins in the library into a plugin tiddler of type "library"
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "makelibrary",
synchronous: true
};
var UPGRADE_LIBRARY_TITLE = "$:/UpgradeLibrary";
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
var wiki = this.commander.wiki,
fs = require("fs"),
path = require("path"),
upgradeLibraryTitle = this.params[0] || UPGRADE_LIBRARY_TITLE,
tiddlers = {};
// Collect up the library plugins
var collectPlugins = function(folder) {
var pluginFolders = fs.readdirSync(folder);
for(var p=0; p<pluginFolders.length; p++) {
if(!$tw.boot.excludeRegExp.test(pluginFolders[p])) {
pluginFields = $tw.loadPluginFolder(path.resolve(folder,"./" + pluginFolders[p]));
if(pluginFields && pluginFields.title) {
tiddlers[pluginFields.title] = pluginFields;
}
}
}
},
collectPublisherPlugins = function(folder) {
var publisherFolders = fs.readdirSync(folder);
for(var t=0; t<publisherFolders.length; t++) {
if(!$tw.boot.excludeRegExp.test(publisherFolders[t])) {
collectPlugins(path.resolve(folder,"./" + publisherFolders[t]));
}
}
};
collectPublisherPlugins(path.resolve($tw.boot.corePath,$tw.config.pluginsPath));
collectPublisherPlugins(path.resolve($tw.boot.corePath,$tw.config.themesPath));
collectPlugins(path.resolve($tw.boot.corePath,$tw.config.languagesPath));
// Save the upgrade library tiddler
var pluginFields = {
title: upgradeLibraryTitle,
type: "application/json",
"plugin-type": "library",
"text": JSON.stringify({tiddlers: tiddlers},null,$tw.config.preferences.jsonSpaces)
};
wiki.addTiddler(new $tw.Tiddler(pluginFields));
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/output.js
type: application/javascript
module-type: command
Command to set the default output location (defaults to current working directory)
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "output",
synchronous: true
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
var fs = require("fs"),
path = require("path");
if(this.params.length < 1) {
return "Missing output path";
}
this.commander.outputPath = path.resolve(process.cwd(),this.params[0]);
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/password.js
type: application/javascript
module-type: command
Save password for crypto operations
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "password",
synchronous: true
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
if(this.params.length < 1) {
return "Missing password";
}
$tw.crypto.setPassword(this.params[0]);
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/rendertiddler.js
type: application/javascript
module-type: command
Command to render a tiddler and save it to a file
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "rendertiddler",
synchronous: false
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
if(this.params.length < 2) {
return "Missing filename";
}
var self = this,
fs = require("fs"),
path = require("path"),
title = this.params[0],
filename = path.resolve(this.commander.outputPath,this.params[1]),
type = this.params[2] || "text/html",
template = this.params[3],
variables = {};
$tw.utils.createFileDirectories(filename);
if(template) {
variables.currentTiddler = title;
title = template;
}
fs.writeFile(filename,this.commander.wiki.renderTiddler(type,title,{variables: variables}),"utf8",function(err) {
self.callback(err);
});
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/rendertiddlers.js
type: application/javascript
module-type: command
Command to render several tiddlers to a folder of files
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var widget = require("$:/core/modules/widgets/widget.js");
exports.info = {
name: "rendertiddlers",
synchronous: true
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
if(this.params.length < 2) {
return "Missing filename";
}
var self = this,
fs = require("fs"),
path = require("path"),
wiki = this.commander.wiki,
filter = this.params[0],
template = this.params[1],
outputPath = this.commander.outputPath,
pathname = path.resolve(outputPath,this.params[2]),
type = this.params[3] || "text/html",
extension = this.params[4] || ".html",
deleteDirectory = (this.params[5] || "").toLowerCase() !== "noclean",
tiddlers = wiki.filterTiddlers(filter);
if(deleteDirectory) {
$tw.utils.deleteDirectory(pathname);
}
$tw.utils.each(tiddlers,function(title) {
var parser = wiki.parseTiddler(template),
widgetNode = wiki.makeWidget(parser,{variables: {currentTiddler: title}}),
container = $tw.fakeDocument.createElement("div");
widgetNode.render(container,null);
var text = type === "text/html" ? container.innerHTML : container.textContent,
exportPath = null;
if($tw.utils.hop($tw.macros,"tv-get-export-path")) {
var macroPath = $tw.macros["tv-get-export-path"].run.apply(self,[title]);
if(macroPath) {
exportPath = path.resolve(outputPath,macroPath + extension);
}
}
var finalPath = exportPath || path.resolve(pathname,encodeURIComponent(title) + extension);
$tw.utils.createFileDirectories(finalPath);
fs.writeFileSync(finalPath,text,"utf8");
});
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/savelibrarytiddlers.js
type: application/javascript
module-type: command
Command to save the subtiddlers of a bundle tiddler as a series of JSON files
--savelibrarytiddlers <tiddler> <pathname> <skinnylisting>
The tiddler identifies the bundle tiddler that contains the subtiddlers.
The pathname specifies the pathname to the folder in which the JSON files should be saved. The filename is the URL encoded title of the subtiddler.
The skinnylisting specifies the title of the tiddler to which a JSON catalogue of the subtiddlers will be saved. The JSON file contains the same data as the bundle tiddler but with the `text` field removed.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "savelibrarytiddlers",
synchronous: true
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
if(this.params.length < 2) {
return "Missing filename";
}
var self = this,
fs = require("fs"),
path = require("path"),
containerTitle = this.params[0],
filter = this.params[1],
basepath = this.params[2],
skinnyListTitle = this.params[3];
// Get the container tiddler as data
var containerData = self.commander.wiki.getTiddlerDataCached(containerTitle,undefined);
if(!containerData) {
return "'" + containerTitle + "' is not a tiddler bundle";
}
// Filter the list of plugins
var pluginList = [];
$tw.utils.each(containerData.tiddlers,function(tiddler,title) {
pluginList.push(title);
});
var filteredPluginList;
if(filter) {
filteredPluginList = self.commander.wiki.filterTiddlers(filter,null,self.commander.wiki.makeTiddlerIterator(pluginList));
} else {
filteredPluginList = pluginList;
}
// Iterate through the plugins
var skinnyList = [];
$tw.utils.each(filteredPluginList,function(title) {
var tiddler = containerData.tiddlers[title];
// Save each JSON file and collect the skinny data
var pathname = path.resolve(self.commander.outputPath,basepath + encodeURIComponent(title) + ".json");
$tw.utils.createFileDirectories(pathname);
fs.writeFileSync(pathname,JSON.stringify(tiddler,null,$tw.config.preferences.jsonSpaces),"utf8");
// Collect the skinny list data
var pluginTiddlers = JSON.parse(tiddler.text),
readmeContent = (pluginTiddlers.tiddlers[title + "/readme"] || {}).text,
iconTiddler = pluginTiddlers.tiddlers[title + "/icon"] || {},
iconType = iconTiddler.type,
iconText = iconTiddler.text,
iconContent;
if(iconType && iconText) {
iconContent = $tw.utils.makeDataUri(iconText,iconType);
}
skinnyList.push($tw.utils.extend({},tiddler,{text: undefined, readme: readmeContent, icon: iconContent}));
});
// Save the catalogue tiddler
if(skinnyListTitle) {
self.commander.wiki.setTiddlerData(skinnyListTitle,skinnyList);
}
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/savetiddler.js
type: application/javascript
module-type: command
Command to save the content of a tiddler to a file
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "savetiddler",
synchronous: false
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
if(this.params.length < 2) {
return "Missing filename";
}
var self = this,
fs = require("fs"),
path = require("path"),
title = this.params[0],
filename = path.resolve(this.commander.outputPath,this.params[1]),
tiddler = this.commander.wiki.getTiddler(title),
type = tiddler.fields.type || "text/vnd.tiddlywiki",
contentTypeInfo = $tw.config.contentTypeInfo[type] || {encoding: "utf8"};
$tw.utils.createFileDirectories(filename);
fs.writeFile(filename,tiddler.fields.text,contentTypeInfo.encoding,function(err) {
self.callback(err);
});
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/savetiddlers.js
type: application/javascript
module-type: command
Command to save several tiddlers to a folder of files
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var widget = require("$:/core/modules/widgets/widget.js");
exports.info = {
name: "savetiddlers",
synchronous: true
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
if(this.params.length < 1) {
return "Missing filename";
}
var self = this,
fs = require("fs"),
path = require("path"),
wiki = this.commander.wiki,
filter = this.params[0],
pathname = path.resolve(this.commander.outputPath,this.params[1]),
deleteDirectory = (this.params[2] || "").toLowerCase() !== "noclean",
tiddlers = wiki.filterTiddlers(filter);
if(deleteDirectory) {
$tw.utils.deleteDirectory(pathname);
}
$tw.utils.createDirectory(pathname);
$tw.utils.each(tiddlers,function(title) {
var tiddler = self.commander.wiki.getTiddler(title),
type = tiddler.fields.type || "text/vnd.tiddlywiki",
contentTypeInfo = $tw.config.contentTypeInfo[type] || {encoding: "utf8"},
filename = path.resolve(pathname,encodeURIComponent(title));
fs.writeFileSync(filename,tiddler.fields.text,contentTypeInfo.encoding);
});
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/server.js
type: application/javascript
module-type: command
Serve tiddlers over http
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
if($tw.node) {
var util = require("util"),
fs = require("fs"),
url = require("url"),
path = require("path"),
http = require("http");
}
exports.info = {
name: "server",
synchronous: true
};
/*
A simple HTTP server with regexp-based routes
*/
function SimpleServer(options) {
this.routes = options.routes || [];
this.wiki = options.wiki;
this.variables = options.variables || {};
}
SimpleServer.prototype.set = function(obj) {
var self = this;
$tw.utils.each(obj,function(value,name) {
self.variables[name] = value;
});
};
SimpleServer.prototype.get = function(name) {
return this.variables[name];
};
SimpleServer.prototype.addRoute = function(route) {
this.routes.push(route);
};
SimpleServer.prototype.findMatchingRoute = function(request,state) {
var pathprefix = this.get("pathprefix") || "";
for(var t=0; t<this.routes.length; t++) {
var potentialRoute = this.routes[t],
pathRegExp = potentialRoute.path,
pathname = state.urlInfo.pathname,
match;
if(pathprefix) {
if(pathname.substr(0,pathprefix.length) === pathprefix) {
pathname = pathname.substr(pathprefix.length);
match = potentialRoute.path.exec(pathname);
} else {
match = false;
}
} else {
match = potentialRoute.path.exec(pathname);
}
if(match && request.method === potentialRoute.method) {
state.params = [];
for(var p=1; p<match.length; p++) {
state.params.push(match[p]);
}
return potentialRoute;
}
}
return null;
};
SimpleServer.prototype.checkCredentials = function(request,incomingUsername,incomingPassword) {
var header = request.headers.authorization || "",
token = header.split(/\s+/).pop() || "",
auth = $tw.utils.base64Decode(token),
parts = auth.split(/:/),
username = parts[0],
password = parts[1];
if(incomingUsername === username && incomingPassword === password) {
return "ALLOWED";
} else {
return "DENIED";
}
};
SimpleServer.prototype.listen = function(port,host) {
var self = this;
http.createServer(function(request,response) {
// Compose the state object
var state = {};
state.wiki = self.wiki;
state.server = self;
state.urlInfo = url.parse(request.url);
// Find the route that matches this path
var route = self.findMatchingRoute(request,state);
// Check for the username and password if we've got one
var username = self.get("username"),
password = self.get("password");
if(username && password) {
// Check they match
if(self.checkCredentials(request,username,password) !== "ALLOWED") {
var servername = state.wiki.getTiddlerText("$:/SiteTitle") || "TiddlyWiki5";
response.writeHead(401,"Authentication required",{
"WWW-Authenticate": 'Basic realm="Please provide your username and password to login to ' + servername + '"'
});
response.end();
return;
}
}
// Return a 404 if we didn't find a route
if(!route) {
response.writeHead(404);
response.end();
return;
}
// Set the encoding for the incoming request
// TODO: Presumably this would need tweaking if we supported PUTting binary tiddlers
request.setEncoding("utf8");
// Dispatch the appropriate method
switch(request.method) {
case "GET": // Intentional fall-through
case "DELETE":
route.handler(request,response,state);
break;
case "PUT":
var data = "";
request.on("data",function(chunk) {
data += chunk.toString();
});
request.on("end",function() {
state.data = data;
route.handler(request,response,state);
});
break;
}
}).listen(port,host);
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
// Set up server
this.server = new SimpleServer({
wiki: this.commander.wiki
});
// Add route handlers
this.server.addRoute({
method: "PUT",
path: /^\/recipes\/default\/tiddlers\/(.+)$/,
handler: function(request,response,state) {
var title = decodeURIComponent(state.params[0]),
fields = JSON.parse(state.data);
// Pull up any subfields in the `fields` object
if(fields.fields) {
$tw.utils.each(fields.fields,function(field,name) {
fields[name] = field;
});
delete fields.fields;
}
// Remove any revision field
if(fields.revision) {
delete fields.revision;
}
state.wiki.addTiddler(new $tw.Tiddler(state.wiki.getCreationFields(),fields,{title: title},state.wiki.getModificationFields()));
var changeCount = state.wiki.getChangeCount(title).toString();
response.writeHead(204, "OK",{
Etag: "\"default/" + encodeURIComponent(title) + "/" + changeCount + ":\"",
"Content-Type": "text/plain"
});
response.end();
}
});
this.server.addRoute({
method: "DELETE",
path: /^\/bags\/default\/tiddlers\/(.+)$/,
handler: function(request,response,state) {
var title = decodeURIComponent(state.params[0]);
state.wiki.deleteTiddler(title);
response.writeHead(204, "OK", {
"Content-Type": "text/plain"
});
response.end();
}
});
this.server.addRoute({
method: "GET",
path: /^\/$/,
handler: function(request,response,state) {
response.writeHead(200, {"Content-Type": state.server.get("serveType")});
var text = state.wiki.renderTiddler(state.server.get("renderType"),state.server.get("rootTiddler"));
response.end(text,"utf8");
}
});
this.server.addRoute({
method: "GET",
path: /^\/status$/,
handler: function(request,response,state) {
response.writeHead(200, {"Content-Type": "application/json"});
var text = JSON.stringify({
username: state.server.get("username"),
space: {
recipe: "default"
},
tiddlywiki_version: $tw.version
});
response.end(text,"utf8");
}
});
this.server.addRoute({
method: "GET",
path: /^\/favicon.ico$/,
handler: function(request,response,state) {
response.writeHead(200, {"Content-Type": "image/x-icon"});
var buffer = state.wiki.getTiddlerText("$:/favicon.ico","");
response.end(buffer,"base64");
}
});
this.server.addRoute({
method: "GET",
path: /^\/recipes\/default\/tiddlers.json$/,
handler: function(request,response,state) {
response.writeHead(200, {"Content-Type": "application/json"});
var tiddlers = [];
state.wiki.forEachTiddler({sortField: "title"},function(title,tiddler) {
var tiddlerFields = {};
$tw.utils.each(tiddler.fields,function(field,name) {
if(name !== "text") {
tiddlerFields[name] = tiddler.getFieldString(name);
}
});
tiddlerFields.revision = state.wiki.getChangeCount(title);
tiddlerFields.type = tiddlerFields.type || "text/vnd.tiddlywiki";
tiddlers.push(tiddlerFields);
});
var text = JSON.stringify(tiddlers);
response.end(text,"utf8");
}
});
this.server.addRoute({
method: "GET",
path: /^\/recipes\/default\/tiddlers\/(.+)$/,
handler: function(request,response,state) {
var title = decodeURIComponent(state.params[0]),
tiddler = state.wiki.getTiddler(title),
tiddlerFields = {},
knownFields = [
"bag", "created", "creator", "modified", "modifier", "permissions", "recipe", "revision", "tags", "text", "title", "type", "uri"
];
if(tiddler) {
$tw.utils.each(tiddler.fields,function(field,name) {
var value = tiddler.getFieldString(name);
if(knownFields.indexOf(name) !== -1) {
tiddlerFields[name] = value;
} else {
tiddlerFields.fields = tiddlerFields.fields || {};
tiddlerFields.fields[name] = value;
}
});
tiddlerFields.revision = state.wiki.getChangeCount(title);
tiddlerFields.type = tiddlerFields.type || "text/vnd.tiddlywiki";
response.writeHead(200, {"Content-Type": "application/json"});
response.end(JSON.stringify(tiddlerFields),"utf8");
} else {
response.writeHead(404);
response.end();
}
}
});
};
Command.prototype.execute = function() {
if(!$tw.boot.wikiTiddlersPath) {
$tw.utils.warning("Warning: Wiki folder '" + $tw.boot.wikiPath + "' does not exist or is missing a tiddlywiki.info file");
}
var port = this.params[0] || "8080",
rootTiddler = this.params[1] || "$:/core/save/all",
renderType = this.params[2] || "text/plain",
serveType = this.params[3] || "text/html",
username = this.params[4],
password = this.params[5],
host = this.params[6] || "127.0.0.1",
pathprefix = this.params[7];
this.server.set({
rootTiddler: rootTiddler,
renderType: renderType,
serveType: serveType,
username: username,
password: password,
pathprefix: pathprefix
});
this.server.listen(port,host);
console.log("Serving on " + host + ":" + port);
console.log("(press ctrl-C to exit)");
// Warn if required plugins are missing
if(!$tw.wiki.getTiddler("$:/plugins/tiddlywiki/tiddlyweb") || !$tw.wiki.getTiddler("$:/plugins/tiddlywiki/filesystem")) {
$tw.utils.warning("Warning: Plugins required for client-server operation (\"tiddlywiki/filesystem\" and \"tiddlywiki/tiddlyweb\") are missing from tiddlywiki.info file");
}
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/setfield.js
type: application/javascript
module-type: command
Command to modify selected tiddlers to set a field to the text of a template tiddler that has been wikified with the selected tiddler as the current tiddler.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var widget = require("$:/core/modules/widgets/widget.js");
exports.info = {
name: "setfield",
synchronous: true
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
if(this.params.length < 4) {
return "Missing parameters";
}
var self = this,
wiki = this.commander.wiki,
filter = this.params[0],
fieldname = this.params[1] || "text",
templatetitle = this.params[2],
rendertype = this.params[3] || "text/plain",
tiddlers = wiki.filterTiddlers(filter);
$tw.utils.each(tiddlers,function(title) {
var parser = wiki.parseTiddler(templatetitle),
newFields = {},
tiddler = wiki.getTiddler(title);
if(parser) {
var widgetNode = wiki.makeWidget(parser,{variables: {currentTiddler: title}});
var container = $tw.fakeDocument.createElement("div");
widgetNode.render(container,null);
newFields[fieldname] = rendertype === "text/html" ? container.innerHTML : container.textContent;
} else {
newFields[fieldname] = undefined;
}
wiki.addTiddler(new $tw.Tiddler(tiddler,newFields));
});
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/unpackplugin.js
type: application/javascript
module-type: command
Command to extract the shadow tiddlers from within a plugin
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "unpackplugin",
synchronous: true
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
if(this.params.length < 1) {
return "Missing plugin name";
}
var self = this,
title = this.params[0],
pluginData = this.commander.wiki.getTiddlerDataCached(title);
if(!pluginData) {
return "Plugin '" + title + "' not found";
}
$tw.utils.each(pluginData.tiddlers,function(tiddler) {
self.commander.wiki.addTiddler(new $tw.Tiddler(tiddler));
});
return null;
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/verbose.js
type: application/javascript
module-type: command
Verbose command
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "verbose",
synchronous: true
};
var Command = function(params,commander) {
this.params = params;
this.commander = commander;
};
Command.prototype.execute = function() {
this.commander.verbose = true;
// Output the boot message log
this.commander.streams.output.write("Boot log:\n " + $tw.boot.logMessages.join("\n ") + "\n");
return null; // No error
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/commands/version.js
type: application/javascript
module-type: command
Version command
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.info = {
name: "version",
synchronous: true
};
var Command = function(params,commander) {
this.params = params;
this.commander = commander;
};
Command.prototype.execute = function() {
this.commander.streams.output.write($tw.version + "\n");
return null; // No error
};
exports.Command = Command;
})();
/*\
title: $:/core/modules/config.js
type: application/javascript
module-type: config
Core configuration constants
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.preferences = {};
exports.preferences.notificationDuration = 3 * 1000;
exports.preferences.jsonSpaces = 4;
exports.textPrimitives = {
upperLetter: "[A-Z\u00c0-\u00d6\u00d8-\u00de\u0150\u0170]",
lowerLetter: "[a-z\u00df-\u00f6\u00f8-\u00ff\u0151\u0171]",
anyLetter: "[A-Za-z0-9\u00c0-\u00d6\u00d8-\u00de\u00df-\u00f6\u00f8-\u00ff\u0150\u0170\u0151\u0171]",
blockPrefixLetters: "[A-Za-z0-9-_\u00c0-\u00d6\u00d8-\u00de\u00df-\u00f6\u00f8-\u00ff\u0150\u0170\u0151\u0171]"
};
exports.textPrimitives.unWikiLink = "~";
exports.textPrimitives.wikiLink = exports.textPrimitives.upperLetter + "+" +
exports.textPrimitives.lowerLetter + "+" +
exports.textPrimitives.upperLetter +
exports.textPrimitives.anyLetter + "*";
exports.htmlEntities = {quot:34, amp:38, apos:39, lt:60, gt:62, nbsp:160, iexcl:161, cent:162, pound:163, curren:164, yen:165, brvbar:166, sect:167, uml:168, copy:169, ordf:170, laquo:171, not:172, shy:173, reg:174, macr:175, deg:176, plusmn:177, sup2:178, sup3:179, acute:180, micro:181, para:182, middot:183, cedil:184, sup1:185, ordm:186, raquo:187, frac14:188, frac12:189, frac34:190, iquest:191, Agrave:192, Aacute:193, Acirc:194, Atilde:195, Auml:196, Aring:197, AElig:198, Ccedil:199, Egrave:200, Eacute:201, Ecirc:202, Euml:203, Igrave:204, Iacute:205, Icirc:206, Iuml:207, ETH:208, Ntilde:209, Ograve:210, Oacute:211, Ocirc:212, Otilde:213, Ouml:214, times:215, Oslash:216, Ugrave:217, Uacute:218, Ucirc:219, Uuml:220, Yacute:221, THORN:222, szlig:223, agrave:224, aacute:225, acirc:226, atilde:227, auml:228, aring:229, aelig:230, ccedil:231, egrave:232, eacute:233, ecirc:234, euml:235, igrave:236, iacute:237, icirc:238, iuml:239, eth:240, ntilde:241, ograve:242, oacute:243, ocirc:244, otilde:245, ouml:246, divide:247, oslash:248, ugrave:249, uacute:250, ucirc:251, uuml:252, yacute:253, thorn:254, yuml:255, OElig:338, oelig:339, Scaron:352, scaron:353, Yuml:376, fnof:402, circ:710, tilde:732, Alpha:913, Beta:914, Gamma:915, Delta:916, Epsilon:917, Zeta:918, Eta:919, Theta:920, Iota:921, Kappa:922, Lambda:923, Mu:924, Nu:925, Xi:926, Omicron:927, Pi:928, Rho:929, Sigma:931, Tau:932, Upsilon:933, Phi:934, Chi:935, Psi:936, Omega:937, alpha:945, beta:946, gamma:947, delta:948, epsilon:949, zeta:950, eta:951, theta:952, iota:953, kappa:954, lambda:955, mu:956, nu:957, xi:958, omicron:959, pi:960, rho:961, sigmaf:962, sigma:963, tau:964, upsilon:965, phi:966, chi:967, psi:968, omega:969, thetasym:977, upsih:978, piv:982, ensp:8194, emsp:8195, thinsp:8201, zwnj:8204, zwj:8205, lrm:8206, rlm:8207, ndash:8211, mdash:8212, lsquo:8216, rsquo:8217, sbquo:8218, ldquo:8220, rdquo:8221, bdquo:8222, dagger:8224, Dagger:8225, bull:8226, hellip:8230, permil:8240, prime:8242, Prime:8243, lsaquo:8249, rsaquo:8250, oline:8254, frasl:8260, euro:8364, image:8465, weierp:8472, real:8476, trade:8482, alefsym:8501, larr:8592, uarr:8593, rarr:8594, darr:8595, harr:8596, crarr:8629, lArr:8656, uArr:8657, rArr:8658, dArr:8659, hArr:8660, forall:8704, part:8706, exist:8707, empty:8709, nabla:8711, isin:8712, notin:8713, ni:8715, prod:8719, sum:8721, minus:8722, lowast:8727, radic:8730, prop:8733, infin:8734, ang:8736, and:8743, or:8744, cap:8745, cup:8746, int:8747, there4:8756, sim:8764, cong:8773, asymp:8776, ne:8800, equiv:8801, le:8804, ge:8805, sub:8834, sup:8835, nsub:8836, sube:8838, supe:8839, oplus:8853, otimes:8855, perp:8869, sdot:8901, lceil:8968, rceil:8969, lfloor:8970, rfloor:8971, lang:9001, rang:9002, loz:9674, spades:9824, clubs:9827, hearts:9829, diams:9830 };
exports.htmlVoidElements = "area,base,br,col,command,embed,hr,img,input,keygen,link,meta,param,source,track,wbr".split(",");
exports.htmlBlockElements = "address,article,aside,audio,blockquote,canvas,dd,div,dl,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,li,noscript,ol,output,p,pre,section,table,tfoot,ul,video".split(",");
exports.htmlUnsafeElements = "script".split(",");
})();
/*\
title: $:/core/modules/deserializers.js
type: application/javascript
module-type: tiddlerdeserializer
Functions to deserialise tiddlers from a block of text
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Utility function to parse an old-style tiddler DIV in a *.tid file. It looks like this:
<div title="Title" creator="JoeBloggs" modifier="JoeBloggs" created="201102111106" modified="201102111310" tags="myTag [[my long tag]]">
<pre>The text of the tiddler (without the expected HTML encoding).
</pre>
</div>
Note that the field attributes are HTML encoded, but that the body of the <PRE> tag is not encoded.
When these tiddler DIVs are encountered within a TiddlyWiki HTML file then the body is encoded in the usual way.
*/
var parseTiddlerDiv = function(text /* [,fields] */) {
// Slot together the default results
var result = {};
if(arguments.length > 1) {
for(var f=1; f<arguments.length; f++) {
var fields = arguments[f];
for(var t in fields) {
result[t] = fields[t];
}
}
}
// Parse the DIV body
var startRegExp = /^\s*<div\s+([^>]*)>(\s*<pre>)?/gi,
endRegExp,
match = startRegExp.exec(text);
if(match) {
// Old-style DIVs don't have the <pre> tag
if(match[2]) {
endRegExp = /<\/pre>\s*<\/div>\s*$/gi;
} else {
endRegExp = /<\/div>\s*$/gi;
}
var endMatch = endRegExp.exec(text);
if(endMatch) {
// Extract the text
result.text = text.substring(match.index + match[0].length,endMatch.index);
// Process the attributes
var attrRegExp = /\s*([^=\s]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi,
attrMatch;
do {
attrMatch = attrRegExp.exec(match[1]);
if(attrMatch) {
var name = attrMatch[1];
var value = attrMatch[2] !== undefined ? attrMatch[2] : attrMatch[3];
result[name] = value;
}
} while(attrMatch);
return result;
}
}
return undefined;
};
exports["application/x-tiddler-html-div"] = function(text,fields) {
return [parseTiddlerDiv(text,fields)];
};
exports["application/json"] = function(text,fields) {
var incoming = JSON.parse(text),
results = [];
if($tw.utils.isArray(incoming)) {
for(var t=0; t<incoming.length; t++) {
var incomingFields = incoming[t],
fields = {};
for(var f in incomingFields) {
if(typeof incomingFields[f] === "string") {
fields[f] = incomingFields[f];
}
}
results.push(fields);
}
}
return results;
};
/*
Parse an HTML file into tiddlers. There are three possibilities:
# A TiddlyWiki classic HTML file containing `text/x-tiddlywiki` tiddlers
# A TiddlyWiki5 HTML file containing `text/vnd.tiddlywiki` tiddlers
# An ordinary HTML file
*/
exports["text/html"] = function(text,fields) {
// Check if we've got a store area
var storeAreaMarkerRegExp = /<div id=["']?storeArea['"]?( style=["']?display:none;["']?)?>/gi,
match = storeAreaMarkerRegExp.exec(text);
if(match) {
// If so, it's either a classic TiddlyWiki file or an unencrypted TW5 file
// First read the normal tiddlers
var results = deserializeTiddlyWikiFile(text,storeAreaMarkerRegExp.lastIndex,!!match[1],fields);
// Then any system tiddlers
var systemAreaMarkerRegExp = /<div id=["']?systemArea['"]?( style=["']?display:none;["']?)?>/gi,
sysMatch = systemAreaMarkerRegExp.exec(text);
if(sysMatch) {
results.push.apply(results,deserializeTiddlyWikiFile(text,systemAreaMarkerRegExp.lastIndex,!!sysMatch[1],fields));
}
return results;
} else {
// Check whether we've got an encrypted file
var encryptedStoreArea = $tw.utils.extractEncryptedStoreArea(text);
if(encryptedStoreArea) {
// If so, attempt to decrypt it using the current password
return $tw.utils.decryptStoreArea(encryptedStoreArea);
} else {
// It's not a TiddlyWiki so we'll return the entire HTML file as a tiddler
return deserializeHtmlFile(text,fields);
}
}
};
function deserializeHtmlFile(text,fields) {
var result = {};
$tw.utils.each(fields,function(value,name) {
result[name] = value;
});
result.text = text;
result.type = "text/html";
return [result];
}
function deserializeTiddlyWikiFile(text,storeAreaEnd,isTiddlyWiki5,fields) {
var results = [],
endOfDivRegExp = /(<\/div>\s*)/gi,
startPos = storeAreaEnd,
defaultType = isTiddlyWiki5 ? undefined : "text/x-tiddlywiki";
endOfDivRegExp.lastIndex = startPos;
var match = endOfDivRegExp.exec(text);
while(match) {
var endPos = endOfDivRegExp.lastIndex,
tiddlerFields = parseTiddlerDiv(text.substring(startPos,endPos),fields,{type: defaultType});
if(!tiddlerFields) {
break;
}
$tw.utils.each(tiddlerFields,function(value,name) {
if(typeof value === "string") {
tiddlerFields[name] = $tw.utils.htmlDecode(value);
}
});
if(tiddlerFields.text !== null) {
results.push(tiddlerFields);
}
startPos = endPos;
match = endOfDivRegExp.exec(text);
}
return results;
}
})();
/*\
title: $:/core/modules/filters.js
type: application/javascript
module-type: wikimethod
Adds tiddler filtering methods to the $tw.Wiki object.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Parses an operation (i.e. a run) within a filter string
operators: Array of array of operator nodes into which results should be inserted
filterString: filter string
p: start position within the string
Returns the new start position, after the parsed operation
*/
function parseFilterOperation(operators,filterString,p) {
var operator, operand, bracketPos, curlyBracketPos;
// Skip the starting square bracket
if(filterString.charAt(p++) !== "[") {
throw "Missing [ in filter expression";
}
// Process each operator in turn
do {
operator = {};
// Check for an operator prefix
if(filterString.charAt(p) === "!") {
operator.prefix = filterString.charAt(p++);
}
// Get the operator name
var nextBracketPos = filterString.substring(p).search(/[\[\{<\/]/);
if(nextBracketPos === -1) {
throw "Missing [ in filter expression";
}
nextBracketPos += p;
var bracket = filterString.charAt(nextBracketPos);
operator.operator = filterString.substring(p,nextBracketPos);
// Any suffix?
var colon = operator.operator.indexOf(':');
if(colon > -1) {
operator.suffix = operator.operator.substring(colon + 1);
operator.operator = operator.operator.substring(0,colon) || "field";
}
// Empty operator means: title
else if(operator.operator === "") {
operator.operator = "title";
}
p = nextBracketPos + 1;
switch (bracket) {
case "{": // Curly brackets
operator.indirect = true;
nextBracketPos = filterString.indexOf("}",p);
break;
case "[": // Square brackets
nextBracketPos = filterString.indexOf("]",p);
break;
case "<": // Angle brackets
operator.variable = true;
nextBracketPos = filterString.indexOf(">",p);
break;
case "/": // regexp brackets
var rex = /^((?:[^\\\/]*|\\.)*)\/(?:\(([mygi]+)\))?/g,
rexMatch = rex.exec(filterString.substring(p));
if(rexMatch) {
operator.regexp = new RegExp(rexMatch[1], rexMatch[2]);
// DEPRECATION WARNING
console.log("WARNING: Filter",operator.operator,"has a deprecated regexp operand",operator.regexp);
nextBracketPos = p + rex.lastIndex - 1;
}
else {
throw "Unterminated regular expression in filter expression";
}
break;
}
if(nextBracketPos === -1) {
throw "Missing closing bracket in filter expression";
}
if(!operator.regexp) {
operator.operand = filterString.substring(p,nextBracketPos);
}
p = nextBracketPos + 1;
// Push this operator
operators.push(operator);
} while(filterString.charAt(p) !== "]");
// Skip the ending square bracket
if(filterString.charAt(p++) !== "]") {
throw "Missing ] in filter expression";
}
// Return the parsing position
return p;
}
/*
Parse a filter string
*/
exports.parseFilter = function(filterString) {
filterString = filterString || "";
var results = [], // Array of arrays of operator nodes {operator:,operand:}
p = 0, // Current position in the filter string
match;
var whitespaceRegExp = /(\s+)/mg,
operandRegExp = /((?:\+|\-)?)(?:(\[)|(?:"([^"]*)")|(?:'([^']*)')|([^\s\[\]]+))/mg;
while(p < filterString.length) {
// Skip any whitespace
whitespaceRegExp.lastIndex = p;
match = whitespaceRegExp.exec(filterString);
if(match && match.index === p) {
p = p + match[0].length;
}
// Match the start of the operation
if(p < filterString.length) {
operandRegExp.lastIndex = p;
match = operandRegExp.exec(filterString);
if(!match || match.index !== p) {
throw "Syntax error in filter expression";
}
var operation = {
prefix: "",
operators: []
};
if(match[1]) {
operation.prefix = match[1];
p++;
}
if(match[2]) { // Opening square bracket
p = parseFilterOperation(operation.operators,filterString,p);
} else {
p = match.index + match[0].length;
}
if(match[3] || match[4] || match[5]) { // Double quoted string, single quoted string or unquoted title
operation.operators.push(
{operator: "title", operand: match[3] || match[4] || match[5]}
);
}
results.push(operation);
}
}
return results;
};
exports.getFilterOperators = function() {
if(!this.filterOperators) {
$tw.Wiki.prototype.filterOperators = {};
$tw.modules.applyMethods("filteroperator",this.filterOperators);
}
return this.filterOperators;
};
exports.filterTiddlers = function(filterString,widget,source) {
var fn = this.compileFilter(filterString);
return fn.call(this,source,widget);
};
/*
Compile a filter into a function with the signature fn(source,widget) where:
source: an iterator function for the source tiddlers, called source(iterator), where iterator is called as iterator(tiddler,title)
widget: an optional widget node for retrieving the current tiddler etc.
*/
exports.compileFilter = function(filterString) {
var filterParseTree;
try {
filterParseTree = this.parseFilter(filterString);
} catch(e) {
return function(source,widget) {
return ["Filter error: " + e];
};
}
// Get the hashmap of filter operator functions
var filterOperators = this.getFilterOperators();
// Assemble array of functions, one for each operation
var operationFunctions = [];
// Step through the operations
var self = this;
$tw.utils.each(filterParseTree,function(operation) {
// Create a function for the chain of operators in the operation
var operationSubFunction = function(source,widget) {
var accumulator = source,
results = [],
currTiddlerTitle = widget && widget.getVariable("currentTiddler");
$tw.utils.each(operation.operators,function(operator) {
var operand = operator.operand,
operatorFunction;
if(!operator.operator) {
operatorFunction = filterOperators.title;
} else if(!filterOperators[operator.operator]) {
operatorFunction = filterOperators.field;
} else {
operatorFunction = filterOperators[operator.operator];
}
if(operator.indirect) {
operand = self.getTextReference(operator.operand,"",currTiddlerTitle);
}
if(operator.variable) {
operand = widget.getVariable(operator.operand,{defaultValue: ""});
}
// Invoke the appropriate filteroperator module
results = operatorFunction(accumulator,{
operator: operator.operator,
operand: operand,
prefix: operator.prefix,
suffix: operator.suffix,
regexp: operator.regexp
},{
wiki: self,
widget: widget
});
if($tw.utils.isArray(results)) {
accumulator = self.makeTiddlerIterator(results);
} else {
accumulator = results;
}
});
if($tw.utils.isArray(results)) {
return results;
} else {
var resultArray = [];
results(function(tiddler,title) {
resultArray.push(title);
});
return resultArray;
}
};
// Wrap the operator functions in a wrapper function that depends on the prefix
operationFunctions.push((function() {
switch(operation.prefix || "") {
case "": // No prefix means that the operation is unioned into the result
return function(results,source,widget) {
$tw.utils.pushTop(results,operationSubFunction(source,widget));
};
case "-": // The results of this operation are removed from the main result
return function(results,source,widget) {
$tw.utils.removeArrayEntries(results,operationSubFunction(source,widget));
};
case "+": // This operation is applied to the main results so far
return function(results,source,widget) {
// This replaces all the elements of the array, but keeps the actual array so that references to it are preserved
source = self.makeTiddlerIterator(results);
results.splice(0,results.length);
$tw.utils.pushTop(results,operationSubFunction(source,widget));
};
}
})());
});
// Return a function that applies the operations to a source iterator of tiddler titles
return $tw.perf.measure("filter",function filterFunction(source,widget) {
if(!source) {
source = self.each;
} else if(typeof source === "object") { // Array or hashmap
source = self.makeTiddlerIterator(source);
}
var results = [];
$tw.utils.each(operationFunctions,function(operationFunction) {
operationFunction(results,source,widget);
});
return results;
});
};
})();
/*\
title: $:/core/modules/filters/addprefix.js
type: application/javascript
module-type: filteroperator
Filter operator for adding a prefix to each title in the list. This is
especially useful in contexts where only a filter expression is allowed
and macro substitution isn't available.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.addprefix = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
results.push(operator.operand + title);
});
return results;
};
})();
/*\
title: $:/core/modules/filters/addsuffix.js
type: application/javascript
module-type: filteroperator
Filter operator for adding a suffix to each title in the list. This is
especially useful in contexts where only a filter expression is allowed
and macro substitution isn't available.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.addsuffix = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
results.push(title + operator.operand);
});
return results;
};
})();
/*\
title: $:/core/modules/filters/after.js
type: application/javascript
module-type: filteroperator
Filter operator returning the tiddler from the current list that is after the tiddler named in the operand.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.after = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
results.push(title);
});
var index = results.indexOf(operator.operand);
if(index === -1 || index > (results.length - 2)) {
return [];
} else {
return [results[index + 1]];
}
};
})();
/*\
title: $:/core/modules/filters/all.js
type: application/javascript
module-type: filteroperator
Filter operator for selecting tiddlers
[all[shadows+tiddlers]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var allFilterOperators;
function getAllFilterOperators() {
if(!allFilterOperators) {
allFilterOperators = {};
$tw.modules.applyMethods("allfilteroperator",allFilterOperators);
}
return allFilterOperators;
}
/*
Export our filter function
*/
exports.all = function(source,operator,options) {
// Get our suboperators
var allFilterOperators = getAllFilterOperators();
// Cycle through the suboperators accumulating their results
var results = [],
subops = operator.operand.split("+");
// Check for common optimisations
if(subops.length === 1 && subops[0] === "") {
return source;
} else if(subops.length === 1 && subops[0] === "tiddlers") {
return options.wiki.each;
} else if(subops.length === 1 && subops[0] === "shadows") {
return options.wiki.eachShadow;
} else if(subops.length === 2 && subops[0] === "tiddlers" && subops[1] === "shadows") {
return options.wiki.eachTiddlerPlusShadows;
} else if(subops.length === 2 && subops[0] === "shadows" && subops[1] === "tiddlers") {
return options.wiki.eachShadowPlusTiddlers;
}
// Do it the hard way
for(var t=0; t<subops.length; t++) {
var subop = allFilterOperators[subops[t]];
if(subop) {
$tw.utils.pushTop(results,subop(source,operator.prefix,options));
}
}
return results;
};
})();
/*\
title: $:/core/modules/filters/all/current.js
type: application/javascript
module-type: allfilteroperator
Filter function for [all[current]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.current = function(source,prefix,options) {
var currTiddlerTitle = options.widget && options.widget.getVariable("currentTiddler");
if(currTiddlerTitle) {
return [currTiddlerTitle];
} else {
return [];
}
};
})();
/*\
title: $:/core/modules/filters/all/missing.js
type: application/javascript
module-type: allfilteroperator
Filter function for [all[missing]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.missing = function(source,prefix,options) {
return options.wiki.getMissingTitles();
};
})();
/*\
title: $:/core/modules/filters/all/orphans.js
type: application/javascript
module-type: allfilteroperator
Filter function for [all[orphans]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.orphans = function(source,prefix,options) {
return options.wiki.getOrphanTitles();
};
})();
/*\
title: $:/core/modules/filters/all/shadows.js
type: application/javascript
module-type: allfilteroperator
Filter function for [all[shadows]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.shadows = function(source,prefix,options) {
return options.wiki.allShadowTitles();
};
})();
/*\
title: $:/core/modules/filters/all/tiddlers.js
type: application/javascript
module-type: allfilteroperator
Filter function for [all[tiddlers]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.tiddlers = function(source,prefix,options) {
return options.wiki.allTitles();
};
})();
/*\
title: $:/core/modules/filters/backlinks.js
type: application/javascript
module-type: filteroperator
Filter operator for returning all the backlinks from a tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.backlinks = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
$tw.utils.pushTop(results,options.wiki.getTiddlerBacklinks(title));
});
return results;
};
})();
/*\
title: $:/core/modules/filters/before.js
type: application/javascript
module-type: filteroperator
Filter operator returning the tiddler from the current list that is before the tiddler named in the operand.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.before = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
results.push(title);
});
var index = results.indexOf(operator.operand);
if(index <= 0) {
return [];
} else {
return [results[index - 1]];
}
};
})();
/*\
title: $:/core/modules/filters/commands.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the names of the commands available in this wiki
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.commands = function(source,operator,options) {
var results = [];
$tw.utils.each($tw.commands,function(commandInfo,name) {
results.push(name);
});
results.sort();
return results;
};
})();
/*\
title: $:/core/modules/filters/days.js
type: application/javascript
module-type: filteroperator
Filter operator that selects tiddlers with a specified date field within a specified date interval.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.days = function(source,operator,options) {
var results = [],
fieldName = operator.suffix || "modified",
dayInterval = (parseInt(operator.operand,10)||0),
dayIntervalSign = $tw.utils.sign(dayInterval),
targetTimeStamp = (new Date()).setHours(0,0,0,0) + 1000*60*60*24*dayInterval,
isWithinDays = function(dateField) {
var sign = $tw.utils.sign(targetTimeStamp - (new Date(dateField)).setHours(0,0,0,0));
return sign === 0 || sign === dayIntervalSign;
};
if(operator.prefix === "!") {
source(function(tiddler,title) {
if(tiddler && tiddler.fields[fieldName]) {
if(!isWithinDays($tw.utils.parseDate(tiddler.fields[fieldName]))) {
results.push(title);
}
}
});
} else {
source(function(tiddler,title) {
if(tiddler && tiddler.fields[fieldName]) {
if(isWithinDays($tw.utils.parseDate(tiddler.fields[fieldName]))) {
results.push(title);
}
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/each.js
type: application/javascript
module-type: filteroperator
Filter operator that selects one tiddler for each unique value of the specified field.
With suffix "list", selects all tiddlers that are values in a specified list field.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.each = function(source,operator,options) {
var results =[] ,
value,values = {},
field = operator.operand || "title";
if(operator.suffix !== "list-item") {
source(function(tiddler,title) {
if(tiddler) {
value = (field === "title") ? title : tiddler.getFieldString(field);
if(!$tw.utils.hop(values,value)) {
values[value] = true;
results.push(title);
}
}
});
} else {
source(function(tiddler,title) {
if(tiddler) {
$tw.utils.each(
options.wiki.getTiddlerList(title,field),
function(value) {
if(!$tw.utils.hop(values,value)) {
values[value] = true;
results.push(value);
}
}
);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/eachday.js
type: application/javascript
module-type: filteroperator
Filter operator that selects one tiddler for each unique day covered by the specified date field
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.eachday = function(source,operator,options) {
var results = [],
values = [],
fieldName = operator.operand || "modified";
// Function to convert a date/time to a date integer
var toDate = function(value) {
value = (new Date(value)).setHours(0,0,0,0);
return value+0;
};
source(function(tiddler,title) {
if(tiddler && tiddler.fields[fieldName]) {
var value = toDate($tw.utils.parseDate(tiddler.fields[fieldName]));
if(values.indexOf(value) === -1) {
values.push(value);
results.push(title);
}
}
});
return results;
};
})();
/*\
title: $:/core/modules/filters/editiondescription.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the descriptions of the specified edition names
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.editiondescription = function(source,operator,options) {
var results = [],
editionInfo = $tw.utils.getEditionInfo();
if(editionInfo) {
source(function(tiddler,title) {
if($tw.utils.hop(editionInfo,title)) {
results.push(editionInfo[title].description || "");
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/editions.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the names of the available editions in this wiki
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.editions = function(source,operator,options) {
var results = [],
editionInfo = $tw.utils.getEditionInfo();
if(editionInfo) {
$tw.utils.each(editionInfo,function(info,name) {
results.push(name);
});
}
results.sort();
return results;
};
})();
/*\
title: $:/core/modules/filters/field.js
type: application/javascript
module-type: filteroperator
Filter operator for comparing fields for equality
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.field = function(source,operator,options) {
var results = [],
fieldname = (operator.suffix || operator.operator || "title").toLowerCase();
if(operator.prefix === "!") {
if(operator.regexp) {
source(function(tiddler,title) {
if(tiddler) {
var text = tiddler.getFieldString(fieldname);
if(text !== null && !operator.regexp.exec(text)) {
results.push(title);
}
} else {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(tiddler) {
var text = tiddler.getFieldString(fieldname);
if(text !== null && text !== operator.operand) {
results.push(title);
}
} else {
results.push(title);
}
});
}
} else {
if(operator.regexp) {
source(function(tiddler,title) {
if(tiddler) {
var text = tiddler.getFieldString(fieldname);
if(text !== null && !!operator.regexp.exec(text)) {
results.push(title);
}
}
});
} else {
source(function(tiddler,title) {
if(tiddler) {
var text = tiddler.getFieldString(fieldname);
if(text !== null && text === operator.operand) {
results.push(title);
}
}
});
}
}
return results;
};
})();
/*\
title: $:/core/modules/filters/fields.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the names of the fields on the selected tiddlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.fields = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
if(tiddler) {
for(var fieldName in tiddler.fields) {
$tw.utils.pushTop(results,fieldName);
}
}
});
return results;
};
})();
/*\
title: $:/core/modules/filters/get.js
type: application/javascript
module-type: filteroperator
Filter operator for replacing tiddler titles by the value of the field specified in the operand.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.get = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
if(tiddler) {
var value = tiddler.getFieldString(operator.operand);
if(value) {
results.push(value);
}
}
});
return results;
};
})();
/*\
title: $:/core/modules/filters/getindex.js
type: application/javascript
module-type: filteroperator
returns the value at a given index of datatiddlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.getindex = function(source,operator,options) {
var data,title,results = [];
if(operator.operand){
source(function(tiddler,title) {
title = tiddler ? tiddler.fields.title : title;
data = options.wiki.extractTiddlerDataItem(tiddler,operator.operand);
if(data) {
results.push(data);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/has.js
type: application/javascript
module-type: filteroperator
Filter operator for checking if a tiddler has the specified field
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.has = function(source,operator,options) {
var results = [];
if(operator.prefix === "!") {
source(function(tiddler,title) {
if(!tiddler || (tiddler && (!$tw.utils.hop(tiddler.fields,operator.operand) || tiddler.fields[operator.operand] === ""))) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(tiddler && $tw.utils.hop(tiddler.fields,operator.operand) && tiddler.fields[operator.operand] !== "") {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/haschanged.js
type: application/javascript
module-type: filteroperator
Filter operator returns tiddlers from the list that have a non-zero changecount.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.haschanged = function(source,operator,options) {
var results = [];
if(operator.prefix === "!") {
source(function(tiddler,title) {
if(options.wiki.getChangeCount(title) === 0) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(options.wiki.getChangeCount(title) > 0) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/indexes.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the indexes of a data tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.indexes = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
var data = options.wiki.getTiddlerDataCached(title);
if(data) {
$tw.utils.pushTop(results,Object.keys(data));
}
});
results.sort();
return results;
};
})();
/*\
title: $:/core/modules/filters/is.js
type: application/javascript
module-type: filteroperator
Filter operator for checking tiddler properties
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var isFilterOperators;
function getIsFilterOperators() {
if(!isFilterOperators) {
isFilterOperators = {};
$tw.modules.applyMethods("isfilteroperator",isFilterOperators);
}
return isFilterOperators;
}
/*
Export our filter function
*/
exports.is = function(source,operator,options) {
// Dispatch to the correct isfilteroperator
var isFilterOperators = getIsFilterOperators();
var isFilterOperator = isFilterOperators[operator.operand];
if(isFilterOperator) {
return isFilterOperator(source,operator.prefix,options);
} else {
return ["Filter Error: Unknown operand for the 'is' filter operator"];
}
};
})();
/*\
title: $:/core/modules/filters/is/current.js
type: application/javascript
module-type: isfilteroperator
Filter function for [is[current]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.current = function(source,prefix,options) {
var results = [],
currTiddlerTitle = options.widget && options.widget.getVariable("currentTiddler");
if(prefix === "!") {
source(function(tiddler,title) {
if(title !== currTiddlerTitle) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(title === currTiddlerTitle) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/is/image.js
type: application/javascript
module-type: isfilteroperator
Filter function for [is[image]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.image = function(source,prefix,options) {
var results = [];
if(prefix === "!") {
source(function(tiddler,title) {
if(!options.wiki.isImageTiddler(title)) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(options.wiki.isImageTiddler(title)) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/is/missing.js
type: application/javascript
module-type: isfilteroperator
Filter function for [is[missing]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.missing = function(source,prefix,options) {
var results = [];
if(prefix === "!") {
source(function(tiddler,title) {
if(options.wiki.tiddlerExists(title)) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(!options.wiki.tiddlerExists(title)) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/is/orphan.js
type: application/javascript
module-type: isfilteroperator
Filter function for [is[orphan]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.orphan = function(source,prefix,options) {
var results = [],
orphanTitles = options.wiki.getOrphanTitles();
if(prefix === "!") {
source(function(tiddler,title) {
if(orphanTitles.indexOf(title) === -1) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(orphanTitles.indexOf(title) !== -1) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/is/shadow.js
type: application/javascript
module-type: isfilteroperator
Filter function for [is[shadow]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.shadow = function(source,prefix,options) {
var results = [];
if(prefix === "!") {
source(function(tiddler,title) {
if(!options.wiki.isShadowTiddler(title)) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(options.wiki.isShadowTiddler(title)) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/is/system.js
type: application/javascript
module-type: isfilteroperator
Filter function for [is[system]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.system = function(source,prefix,options) {
var results = [];
if(prefix === "!") {
source(function(tiddler,title) {
if(!options.wiki.isSystemTiddler(title)) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(options.wiki.isSystemTiddler(title)) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/is/tag.js
type: application/javascript
module-type: isfilteroperator
Filter function for [is[tag]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.tag = function(source,prefix,options) {
var results = [],
tagMap = options.wiki.getTagMap();
if(prefix === "!") {
source(function(tiddler,title) {
if(!$tw.utils.hop(tagMap,title)) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if($tw.utils.hop(tagMap,title)) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/is/tiddler.js
type: application/javascript
module-type: isfilteroperator
Filter function for [is[tiddler]]
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.tiddler = function(source,prefix,options) {
var results = [];
if(prefix === "!") {
source(function(tiddler,title) {
if(!options.wiki.tiddlerExists(title)) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(options.wiki.tiddlerExists(title)) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/limit.js
type: application/javascript
module-type: filteroperator
Filter operator for chopping the results to a specified maximum number of entries
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.limit = function(source,operator,options) {
var results = [];
// Convert to an array
source(function(tiddler,title) {
results.push(title);
});
// Slice the array if necessary
var limit = Math.min(results.length,parseInt(operator.operand,10));
if(operator.prefix === "!") {
results = results.slice(-limit);
} else {
results = results.slice(0,limit);
}
return results;
};
})();
/*\
title: $:/core/modules/filters/links.js
type: application/javascript
module-type: filteroperator
Filter operator for returning all the links from a tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.links = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
$tw.utils.pushTop(results,options.wiki.getTiddlerLinks(title));
});
return results;
};
})();
/*\
title: $:/core/modules/filters/list.js
type: application/javascript
module-type: filteroperator
Filter operator returning the tiddlers whose title is listed in the operand tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.list = function(source,operator,options) {
var results = [],
tr = $tw.utils.parseTextReference(operator.operand),
currTiddlerTitle = options.widget && options.widget.getVariable("currentTiddler"),
list = options.wiki.getTiddlerList(tr.title || currTiddlerTitle,tr.field,tr.index);
if(operator.prefix === "!") {
source(function(tiddler,title) {
if(list.indexOf(title) === -1) {
results.push(title);
}
});
} else {
results = list;
}
return results;
};
})();
/*\
title: $:/core/modules/filters/listed.js
type: application/javascript
module-type: filteroperator
Filter operator returning all tiddlers that have the selected tiddlers in a list
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.listed = function(source,operator,options) {
var field = operator.operand || "list",
results = [];
source(function(tiddler,title) {
$tw.utils.pushTop(results,options.wiki.findListingsOfTiddler(title,field));
});
return results;
};
})();
/*\
title: $:/core/modules/filters/listops.js
type: application/javascript
module-type: filteroperator
Filter operators for manipulating the current selection list
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Reverse list
*/
exports.reverse = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
results.unshift(title);
});
return results;
};
/*
First entry/entries in list
*/
exports.first = function(source,operator,options) {
var count = parseInt(operator.operand) || 1,
results = [];
source(function(tiddler,title) {
results.push(title);
});
return results.slice(0,count);
};
/*
Last entry/entries in list
*/
exports.last = function(source,operator,options) {
var count = parseInt(operator.operand) || 1,
results = [];
source(function(tiddler,title) {
results.push(title);
});
return results.slice(-count);
};
/*
All but the first entry/entries of the list
*/
exports.rest = function(source,operator,options) {
var count = parseInt(operator.operand) || 1,
results = [];
source(function(tiddler,title) {
results.push(title);
});
return results.slice(count);
};
exports.butfirst = exports.rest;
exports.bf = exports.rest;
/*
All but the last entry/entries of the list
*/
exports.butlast = function(source,operator,options) {
var count = parseInt(operator.operand) || 1,
results = [];
source(function(tiddler,title) {
results.push(title);
});
return results.slice(0,-count);
};
exports.bl = exports.butlast;
/*
The nth member of the list
*/
exports.nth = function(source,operator,options) {
var count = parseInt(operator.operand) || 1,
results = [];
source(function(tiddler,title) {
results.push(title);
});
return results.slice(count - 1,count);
};
})();
/*\
title: $:/core/modules/filters/modules.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the titles of the modules of a given type in this wiki
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.modules = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
$tw.utils.each($tw.modules.types[title],function(moduleInfo,moduleName) {
results.push(moduleName);
});
});
results.sort();
return results;
};
})();
/*\
title: $:/core/modules/filters/moduletypes.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the names of the module types in this wiki
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.moduletypes = function(source,operator,options) {
var results = [];
$tw.utils.each($tw.modules.types,function(moduleInfo,type) {
results.push(type);
});
results.sort();
return results;
};
})();
/*\
title: $:/core/modules/filters/next.js
type: application/javascript
module-type: filteroperator
Filter operator returning the tiddler whose title occurs next in the list supplied in the operand tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.next = function(source,operator,options) {
var results = [],
list = options.wiki.getTiddlerList(operator.operand);
source(function(tiddler,title) {
var match = list.indexOf(title);
// increment match and then test if result is in range
match++;
if(match > 0 && match < list.length) {
results.push(list[match]);
}
});
return results;
};
})();
/*\
title: $:/core/modules/filters/plugintiddlers.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the titles of the shadow tiddlers within a plugin
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.plugintiddlers = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
var pluginInfo = options.wiki.getPluginInfo(title) || options.wiki.getTiddlerDataCached(title,{tiddlers:[]});
if(pluginInfo && pluginInfo.tiddlers) {
$tw.utils.each(pluginInfo.tiddlers,function(fields,title) {
results.push(title);
});
}
});
results.sort();
return results;
};
})();
/*\
title: $:/core/modules/filters/prefix.js
type: application/javascript
module-type: filteroperator
Filter operator for checking if a title starts with a prefix
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.prefix = function(source,operator,options) {
var results = [];
if(operator.prefix === "!") {
source(function(tiddler,title) {
if(title.substr(0,operator.operand.length) !== operator.operand) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(title.substr(0,operator.operand.length) === operator.operand) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/previous.js
type: application/javascript
module-type: filteroperator
Filter operator returning the tiddler whose title occurs immediately prior in the list supplied in the operand tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.previous = function(source,operator,options) {
var results = [],
list = options.wiki.getTiddlerList(operator.operand);
source(function(tiddler,title) {
var match = list.indexOf(title);
// increment match and then test if result is in range
match--;
if(match >= 0) {
results.push(list[match]);
}
});
return results;
};
})();
/*\
title: $:/core/modules/filters/regexp.js
type: application/javascript
module-type: filteroperator
Filter operator for regexp matching
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.regexp = function(source,operator,options) {
var results = [],
fieldname = (operator.suffix || "title").toLowerCase(),
regexpString, regexp, flags = "", match,
getFieldString = function(tiddler,title) {
if(tiddler) {
return tiddler.getFieldString(fieldname);
} else if(fieldname === "title") {
return title;
} else {
return null;
}
};
// Process flags and construct regexp
regexpString = operator.operand;
match = /^\(\?([gim]+)\)/.exec(regexpString);
if(match) {
flags = match[1];
regexpString = regexpString.substr(match[0].length);
} else {
match = /\(\?([gim]+)\)$/.exec(regexpString);
if(match) {
flags = match[1];
regexpString = regexpString.substr(0,regexpString.length - match[0].length);
}
}
try {
regexp = new RegExp(regexpString,flags);
} catch(e) {
return ["" + e];
}
// Process the incoming tiddlers
if(operator.prefix === "!") {
source(function(tiddler,title) {
var text = getFieldString(tiddler,title);
if(text !== null) {
if(!regexp.exec(text)) {
results.push(title);
}
}
});
} else {
source(function(tiddler,title) {
var text = getFieldString(tiddler,title);
if(text !== null) {
if(!!regexp.exec(text)) {
results.push(title);
}
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/removeprefix.js
type: application/javascript
module-type: filteroperator
Filter operator for removing a prefix from each title in the list. Titles that do not start with the prefix are removed.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.removeprefix = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
if(title.substr(0,operator.operand.length) === operator.operand) {
results.push(title.substr(operator.operand.length));
}
});
return results;
};
})();
/*\
title: $:/core/modules/filters/removesuffix.js
type: application/javascript
module-type: filteroperator
Filter operator for removing a suffix from each title in the list. Titles that do not end with the suffix are removed.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.removesuffix = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
if(title.substr(-operator.operand.length) === operator.operand) {
results.push(title.substr(0,title.length - operator.operand.length));
}
});
return results;
};
})();
/*\
title: $:/core/modules/filters/sameday.js
type: application/javascript
module-type: filteroperator
Filter operator that selects tiddlers with a modified date field on the same day as the provided value.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.sameday = function(source,operator,options) {
var results = [],
fieldName = operator.suffix || "modified",
targetDate = (new Date($tw.utils.parseDate(operator.operand))).setHours(0,0,0,0);
// Function to convert a date/time to a date integer
var isSameDay = function(dateField) {
return (new Date(dateField)).setHours(0,0,0,0) === targetDate;
};
source(function(tiddler,title) {
if(tiddler && tiddler.fields[fieldName]) {
if(isSameDay($tw.utils.parseDate(tiddler.fields[fieldName]))) {
results.push(title);
}
}
});
return results;
};
})();
/*\
title: $:/core/modules/filters/search.js
type: application/javascript
module-type: filteroperator
Filter operator for searching for the text in the operand tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.search = function(source,operator,options) {
var invert = operator.prefix === "!";
if(operator.suffix) {
return options.wiki.search(operator.operand,{
source: source,
invert: invert,
field: operator.suffix
});
} else {
return options.wiki.search(operator.operand,{
source: source,
invert: invert
});
}
};
})();
/*\
title: $:/core/modules/filters/shadowsource.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the source plugins for shadow tiddlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.shadowsource = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
var source = options.wiki.getShadowSource(title);
if(source) {
$tw.utils.pushTop(results,source);
}
});
results.sort();
return results;
};
})();
/*\
title: $:/core/modules/filters/sort.js
type: application/javascript
module-type: filteroperator
Filter operator for sorting
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.sort = function(source,operator,options) {
var results = prepare_results(source);
options.wiki.sortTiddlers(results,operator.operand || "title",operator.prefix === "!",false,false);
return results;
};
exports.nsort = function(source,operator,options) {
var results = prepare_results(source);
options.wiki.sortTiddlers(results,operator.operand || "title",operator.prefix === "!",false,true);
return results;
};
exports.sortcs = function(source,operator,options) {
var results = prepare_results(source);
options.wiki.sortTiddlers(results,operator.operand || "title",operator.prefix === "!",true,false);
return results;
};
exports.nsortcs = function(source,operator,options) {
var results = prepare_results(source);
options.wiki.sortTiddlers(results,operator.operand || "title",operator.prefix === "!",true,true);
return results;
};
var prepare_results = function (source) {
var results = [];
source(function(tiddler,title) {
results.push(title);
});
return results;
};
})();
/*\
title: $:/core/modules/filters/splitbefore.js
type: application/javascript
module-type: filteroperator
Filter operator that splits each result on the first occurance of the specified separator and returns the unique values.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.splitbefore = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
var parts = title.split(operator.operand);
if(parts.length === 1) {
$tw.utils.pushTop(results,parts[0]);
} else {
$tw.utils.pushTop(results,parts[0] + operator.operand);
}
});
return results;
};
})();
/*\
title: $:/core/modules/filters/storyviews.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the names of the story views in this wiki
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.storyviews = function(source,operator,options) {
var results = [],
storyviews = {};
$tw.modules.applyMethods("storyview",storyviews);
$tw.utils.each(storyviews,function(info,name) {
results.push(name);
});
results.sort();
return results;
};
})();
/*\
title: $:/core/modules/filters/suffix.js
type: application/javascript
module-type: filteroperator
Filter operator for checking if a title ends with a suffix
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.suffix = function(source,operator,options) {
var results = [];
if(operator.prefix === "!") {
source(function(tiddler,title) {
if(title.substr(-operator.operand.length) !== operator.operand) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(title.substr(-operator.operand.length) === operator.operand) {
results.push(title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/tag.js
type: application/javascript
module-type: filteroperator
Filter operator for checking for the presence of a tag
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.tag = function(source,operator,options) {
var results = [];
if(operator.prefix === "!") {
source(function(tiddler,title) {
if(tiddler && !tiddler.hasTag(operator.operand)) {
results.push(title);
}
});
} else {
source(function(tiddler,title) {
if(tiddler && tiddler.hasTag(operator.operand)) {
results.push(title);
}
});
results = options.wiki.sortByList(results,operator.operand);
}
return results;
};
})();
/*\
title: $:/core/modules/filters/tagging.js
type: application/javascript
module-type: filteroperator
Filter operator returning all tiddlers that are tagged with the selected tiddlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.tagging = function(source,operator,options) {
var results = [];
source(function(tiddler,title) {
$tw.utils.pushTop(results,options.wiki.getTiddlersWithTag(title));
});
return results;
};
})();
/*\
title: $:/core/modules/filters/tags.js
type: application/javascript
module-type: filteroperator
Filter operator returning all the tags of the selected tiddlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.tags = function(source,operator,options) {
var tags = {};
source(function(tiddler,title) {
var t, length;
if(tiddler && tiddler.fields.tags) {
for(t=0, length=tiddler.fields.tags.length; t<length; t++) {
tags[tiddler.fields.tags[t]] = true;
}
}
});
return Object.keys(tags);
};
})();
/*\
title: $:/core/modules/filters/title.js
type: application/javascript
module-type: filteroperator
Filter operator for comparing title fields for equality
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.title = function(source,operator,options) {
var results = [];
if(operator.prefix === "!") {
source(function(tiddler,title) {
if(tiddler && tiddler.fields.title !== operator.operand) {
results.push(title);
}
});
} else {
results.push(operator.operand);
}
return results;
};
})();
/*\
title: $:/core/modules/filters/untagged.js
type: application/javascript
module-type: filteroperator
Filter operator returning all the selected tiddlers that are untagged
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.untagged = function(source,operator,options) {
var results = [];
if(operator.prefix === "!") {
source(function(tiddler,title) {
if(tiddler && $tw.utils.isArray(tiddler.fields.tags) && tiddler.fields.tags.length > 0) {
$tw.utils.pushTop(results,title);
}
});
} else {
source(function(tiddler,title) {
if(!tiddler || !tiddler.hasField("tags") || ($tw.utils.isArray(tiddler.fields.tags) && tiddler.fields.tags.length === 0)) {
$tw.utils.pushTop(results,title);
}
});
}
return results;
};
})();
/*\
title: $:/core/modules/filters/wikiparserrules.js
type: application/javascript
module-type: filteroperator
Filter operator for returning the names of the wiki parser rules in this wiki
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Export our filter function
*/
exports.wikiparserrules = function(source,operator,options) {
var results = [];
$tw.utils.each($tw.modules.types.wikirule,function(mod) {
var exp = mod.exports;
if(exp.types[operator.operand]) {
results.push(exp.name);
}
});
results.sort();
return results;
};
})();
/*\
title: $:/core/modules/filters/x-listops.js
type: application/javascript
module-type: filteroperator
Extended filter operators to manipulate the current list.
\*/
(function () {
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Fetch titles from the current list
*/
var prepare_results = function (source) {
var results = [];
source(function (tiddler, title) {
results.push(title);
});
return results;
};
/*
Moves a number of items from the tail of the current list before the item named in the operand
*/
exports.putbefore = function (source, operator) {
var results = prepare_results(source),
index = results.indexOf(operator.operand),
count = parseInt(operator.suffix) || 1;
return (index === -1) ?
results.slice(0, -1) :
results.slice(0, index).concat(results.slice(-count)).concat(results.slice(index, -count));
};
/*
Moves a number of items from the tail of the current list after the item named in the operand
*/
exports.putafter = function (source, operator) {
var results = prepare_results(source),
index = results.indexOf(operator.operand),
count = parseInt(operator.suffix) || 1;
return (index === -1) ?
results.slice(0, -1) :
results.slice(0, index + 1).concat(results.slice(-count)).concat(results.slice(index + 1, -count));
};
/*
Replaces the item named in the operand with a number of items from the tail of the current list
*/
exports.replace = function (source, operator) {
var results = prepare_results(source),
index = results.indexOf(operator.operand),
count = parseInt(operator.suffix) || 1;
return (index === -1) ?
results.slice(0, -count) :
results.slice(0, index).concat(results.slice(-count)).concat(results.slice(index + 1, -count));
};
/*
Moves a number of items from the tail of the current list to the head of the list
*/
exports.putfirst = function (source, operator) {
var results = prepare_results(source),
count = parseInt(operator.suffix) || 1;
return results.slice(-count).concat(results.slice(0, -count));
};
/*
Moves a number of items from the head of the current list to the tail of the list
*/
exports.putlast = function (source, operator) {
var results = prepare_results(source),
count = parseInt(operator.suffix) || 1;
return results.slice(count).concat(results.slice(0, count));
};
/*
Moves the item named in the operand a number of places forward or backward in the list
*/
exports.move = function (source, operator) {
var results = prepare_results(source),
index = results.indexOf(operator.operand),
count = parseInt(operator.suffix) || 1,
marker = results.splice(index, 1);
return results.slice(0, index + count).concat(marker).concat(results.slice(index + count));
};
/*
Returns the items from the current list that are after the item named in the operand
*/
exports.allafter = function (source, operator) {
var results = prepare_results(source),
index = results.indexOf(operator.operand);
return (index === -1 || index > (results.length - 2)) ? [] :
(operator.suffix) ? results.slice(index) :
results.slice(index + 1);
};
/*
Returns the items from the current list that are before the item named in the operand
*/
exports.allbefore = function (source, operator) {
var results = prepare_results(source),
index = results.indexOf(operator.operand);
return (index <= 0) ? [] :
(operator.suffix) ? results.slice(0, index + 1) :
results.slice(0, index);
};
/*
Appends the items listed in the operand array to the tail of the current list
*/
exports.append = function (source, operator) {
var append = $tw.utils.parseStringArray(operator.operand, "true"),
results = prepare_results(source),
count = parseInt(operator.suffix) || append.length;
return (append.length === 0) ? results :
(operator.prefix) ? results.concat(append.slice(-count)) :
results.concat(append.slice(0, count));
};
/*
Prepends the items listed in the operand array to the head of the current list
*/
exports.prepend = function (source, operator) {
var prepend = $tw.utils.parseStringArray(operator.operand, "true"),
results = prepare_results(source),
count = parseInt(operator.suffix) || prepend.length;
return (prepend.length === 0) ? results :
(operator.prefix) ? prepend.slice(-count).concat(results) :
prepend.slice(0, count).concat(results);
};
/*
Returns all items from the current list except the items listed in the operand array
*/
exports.remove = function (source, operator) {
var array = $tw.utils.parseStringArray(operator.operand, "true"),
results = prepare_results(source),
count = parseInt(operator.suffix) || array.length,
p,
len,
index;
len = array.length - 1;
for (p = 0; p < count; ++p) {
if (operator.prefix) {
index = results.indexOf(array[len - p]);
} else {
index = results.indexOf(array[p]);
}
if (index !== -1) {
results.splice(index, 1);
}
}
return results;
};
/*
Returns all items from the current list sorted in the order of the items in the operand array
*/
exports.sortby = function (source, operator) {
var results = prepare_results(source);
if (!results || results.length < 2) {
return results;
}
var lookup = $tw.utils.parseStringArray(operator.operand, "true");
results.sort(function (a, b) {
return lookup.indexOf(a) - lookup.indexOf(b);
});
return results;
};
/*
Removes all duplicate items from the current list
*/
exports.unique = function (source, operator) {
var results = prepare_results(source);
var set = results.reduce(function (a, b) {
if (a.indexOf(b) < 0) {
a.push(b);
}
return a;
}, []);
return set;
};
})();
/*\
title: $:/core/modules/info/platform.js
type: application/javascript
module-type: info
Initialise basic platform $:/info/ tiddlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.getInfoTiddlerFields = function() {
var mapBoolean = function(value) {return value ? "yes" : "no";},
infoTiddlerFields = [];
// Basics
infoTiddlerFields.push({title: "$:/info/browser", text: mapBoolean(!!$tw.browser)});
infoTiddlerFields.push({title: "$:/info/node", text: mapBoolean(!!$tw.node)});
return infoTiddlerFields;
};
})();
/*\
title: $:/core/modules/language.js
type: application/javascript
module-type: global
The $tw.Language() manages translateable strings
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Create an instance of the language manager. Options include:
wiki: wiki from which to retrieve translation tiddlers
*/
function Language(options) {
options = options || "";
this.wiki = options.wiki || $tw.wiki;
}
/*
Return a wikified translateable string. The title is automatically prefixed with "$:/language/"
Options include:
variables: optional hashmap of variables to supply to the language wikification
*/
Language.prototype.getString = function(title,options) {
options = options || {};
title = "$:/language/" + title;
return this.wiki.renderTiddler("text/plain",title,{variables: options.variables});
};
/*
Return a raw, unwikified translateable string. The title is automatically prefixed with "$:/language/"
*/
Language.prototype.getRawString = function(title) {
title = "$:/language/" + title;
return this.wiki.getTiddlerText(title);
};
exports.Language = Language;
})();
/*\
title: $:/core/modules/macros/changecount.js
type: application/javascript
module-type: macro
Macro to return the changecount for the current tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "changecount";
exports.params = [];
/*
Run the macro
*/
exports.run = function() {
return this.wiki.getChangeCount(this.getVariable("currentTiddler")) + "";
};
})();
/*\
title: $:/core/modules/macros/contrastcolour.js
type: application/javascript
module-type: macro
Macro to choose which of two colours has the highest contrast with a base colour
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "contrastcolour";
exports.params = [
{name: "target"},
{name: "fallbackTarget"},
{name: "colourA"},
{name: "colourB"}
];
/*
Run the macro
*/
exports.run = function(target,fallbackTarget,colourA,colourB) {
var rgbTarget = $tw.utils.parseCSSColor(target) || $tw.utils.parseCSSColor(fallbackTarget);
if(!rgbTarget) {
return colourA;
}
var rgbColourA = $tw.utils.parseCSSColor(colourA),
rgbColourB = $tw.utils.parseCSSColor(colourB);
if(rgbColourA && !rgbColourB) {
return rgbColourA;
}
if(rgbColourB && !rgbColourA) {
return rgbColourB;
}
if(!rgbColourA && !rgbColourB) {
// If neither colour is readable, return a crude inverse of the target
return [255 - rgbTarget[0],255 - rgbTarget[1],255 - rgbTarget[2],rgbTarget[3]];
}
// Colour brightness formula derived from http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
var brightnessTarget = rgbTarget[0] * 0.299 + rgbTarget[1] * 0.587 + rgbTarget[2] * 0.114,
brightnessA = rgbColourA[0] * 0.299 + rgbColourA[1] * 0.587 + rgbColourA[2] * 0.114,
brightnessB = rgbColourB[0] * 0.299 + rgbColourB[1] * 0.587 + rgbColourB[2] * 0.114;
return Math.abs(brightnessTarget - brightnessA) > Math.abs(brightnessTarget - brightnessB) ? colourA : colourB;
};
})();
/*\
title: $:/core/modules/macros/csvtiddlers.js
type: application/javascript
module-type: macro
Macro to output tiddlers matching a filter to CSV
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "csvtiddlers";
exports.params = [
{name: "filter"},
{name: "format"},
];
/*
Run the macro
*/
exports.run = function(filter,format) {
var self = this,
tiddlers = this.wiki.filterTiddlers(filter),
tiddler,
fields = [],
t,f;
// Collect all the fields
for(t=0;t<tiddlers.length; t++) {
tiddler = this.wiki.getTiddler(tiddlers[t]);
for(f in tiddler.fields) {
if(fields.indexOf(f) === -1) {
fields.push(f);
}
}
}
// Sort the fields and bring the standard ones to the front
fields.sort();
"title text modified modifier created creator".split(" ").reverse().forEach(function(value,index) {
var p = fields.indexOf(value);
if(p !== -1) {
fields.splice(p,1);
fields.unshift(value)
}
});
// Output the column headings
var output = [], row = [];
fields.forEach(function(value) {
row.push(quoteAndEscape(value))
});
output.push(row.join(","));
// Output each tiddler
for(var t=0;t<tiddlers.length; t++) {
row = [];
tiddler = this.wiki.getTiddler(tiddlers[t]);
for(f=0; f<fields.length; f++) {
row.push(quoteAndEscape(tiddler ? tiddler.getFieldString(fields[f]) || "" : ""));
}
output.push(row.join(","));
}
return output.join("\n");
};
function quoteAndEscape(value) {
return "\"" + value.replace(/"/mg,"\"\"") + "\"";
}
})();
/*\
title: $:/core/modules/macros/dumpvariables.js
type: application/javascript
module-type: macro
Macro to dump all active variable values
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "dumpvariables";
exports.params = [
];
/*
Run the macro
*/
exports.run = function() {
var output = ["|!Variable |!Value |"],
variables = [], variable;
for(variable in this.variables) {
variables.push(variable);
}
variables.sort();
for(var index=0; index<variables.length; index++) {
var variable = variables[index];
output.push("|" + variable + " |<input size=50 value=<<" + variable + ">>/> |")
}
return output.join("\n");
};
})();
/*\
title: $:/core/modules/macros/jsontiddlers.js
type: application/javascript
module-type: macro
Macro to output tiddlers matching a filter to JSON
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "jsontiddlers";
exports.params = [
{name: "filter"}
];
/*
Run the macro
*/
exports.run = function(filter) {
var tiddlers = this.wiki.filterTiddlers(filter),
data = [];
for(var t=0;t<tiddlers.length; t++) {
var tiddler = this.wiki.getTiddler(tiddlers[t]);
if(tiddler) {
var fields = new Object();
for(var field in tiddler.fields) {
fields[field] = tiddler.getFieldString(field);
}
data.push(fields);
}
}
return JSON.stringify(data,null,$tw.config.preferences.jsonSpaces);
};
})();
/*\
title: $:/core/modules/macros/makedatauri.js
type: application/javascript
module-type: macro
Macro to convert the content of a tiddler to a data URI
<<makedatauri text:"Text to be converted" type:"text/vnd.tiddlywiki">>
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "makedatauri";
exports.params = [
{name: "text"},
{name: "type"}
];
/*
Run the macro
*/
exports.run = function(text,type) {
return $tw.utils.makeDataUri(text,type);
};
})();
/*\
title: $:/core/modules/macros/now.js
type: application/javascript
module-type: macro
Macro to return a formatted version of the current time
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "now";
exports.params = [
{name: "format"}
];
/*
Run the macro
*/
exports.run = function(format) {
return $tw.utils.formatDateString(new Date(),format || "0hh:0mm, DDth MMM YYYY");
};
})();
/*\
title: $:/core/modules/macros/qualify.js
type: application/javascript
module-type: macro
Macro to qualify a state tiddler title according
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "qualify";
exports.params = [
{name: "title"}
];
/*
Run the macro
*/
exports.run = function(title) {
return title + "-" + this.getStateQualifier();
};
})();
/*\
title: $:/core/modules/macros/resolvepath.js
type: application/javascript
module-type: macro
Resolves a relative path for an absolute rootpath.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "resolvepath";
exports.params = [
{name: "source"},
{name: "root"}
];
/*
Run the macro
*/
exports.run = function(source, root) {
return $tw.utils.resolvePath(source, root);
};
})();
/*\
title: $:/core/modules/macros/version.js
type: application/javascript
module-type: macro
Macro to return the TiddlyWiki core version number
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "version";
exports.params = [];
/*
Run the macro
*/
exports.run = function() {
return $tw.version;
};
})();
/*\
title: $:/core/modules/parsers/audioparser.js
type: application/javascript
module-type: parser
The audio parser parses an audio tiddler into an embeddable HTML element
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var AudioParser = function(type,text,options) {
var element = {
type: "element",
tag: "audio",
attributes: {
controls: {type: "string", value: "controls"}
}
},
src;
if(options._canonical_uri) {
element.attributes.src = {type: "string", value: options._canonical_uri};
} else if(text) {
element.attributes.src = {type: "string", value: "data:" + type + ";base64," + text};
}
this.tree = [element];
};
exports["audio/ogg"] = AudioParser;
exports["audio/mpeg"] = AudioParser;
exports["audio/mp3"] = AudioParser;
exports["audio/mp4"] = AudioParser;
})();
/*\
title: $:/core/modules/parsers/csvparser.js
type: application/javascript
module-type: parser
The CSV text parser processes CSV files into a table wrapped in a scrollable widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var CsvParser = function(type,text,options) {
// Table framework
this.tree = [{
"type": "scrollable", "children": [{
"type": "element", "tag": "table", "children": [{
"type": "element", "tag": "tbody", "children": []
}], "attributes": {
"class": {"type": "string", "value": "tc-csv-table"}
}
}]
}];
// Split the text into lines
var lines = text.split(/\r?\n/mg),
tag = "th";
for(var line=0; line<lines.length; line++) {
var lineText = lines[line];
if(lineText) {
var row = {
"type": "element", "tag": "tr", "children": []
};
var columns = lineText.split(",");
for(var column=0; column<columns.length; column++) {
row.children.push({
"type": "element", "tag": tag, "children": [{
"type": "text",
"text": columns[column]
}]
});
}
tag = "td";
this.tree[0].children[0].children[0].children.push(row);
}
}
};
exports["text/csv"] = CsvParser;
})();
/*\
title: $:/core/modules/parsers/htmlparser.js
type: application/javascript
module-type: parser
The HTML parser displays text as raw HTML
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var HtmlParser = function(type,text,options) {
var src,sandbox;
if(options._canonical_uri) {
src = options._canonical_uri;
} else if(text) {
src = "data:text/html;charset=utf-8," + encodeURIComponent(text);
}
if (options.parserrules && options.parserrules.sandbox) {
sandbox = options.parserrules.sandbox;
}
else {
sandbox = "sandbox";
}
this.tree = [{
type: "element",
tag: "iframe",
attributes: {
src: {type: "string", value: src},
sandbox: {type: "string", value: sandbox}
}
}];
};
exports["text/html"] = HtmlParser;
})();
/*\
title: $:/core/modules/parsers/imageparser.js
type: application/javascript
module-type: parser
The image parser parses an image into an embeddable HTML element
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var ImageParser = function(type,text,options) {
var element = {
type: "element",
tag: "img",
attributes: {}
},
src;
if(options._canonical_uri) {
element.attributes.src = {type: "string", value: options._canonical_uri};
if(type === "application/pdf" || type === ".pdf") {
element.tag = "embed";
}
} else if(text) {
if(type === "application/pdf" || type === ".pdf") {
element.attributes.src = {type: "string", value: "data:application/pdf;base64," + text};
element.tag = "embed";
} else if(type === "image/svg+xml" || type === ".svg") {
element.attributes.src = {type: "string", value: "data:image/svg+xml," + encodeURIComponent(text)};
} else {
element.attributes.src = {type: "string", value: "data:" + type + ";base64," + text};
}
}
this.tree = [element];
};
exports["image/svg+xml"] = ImageParser;
exports["image/jpg"] = ImageParser;
exports["image/jpeg"] = ImageParser;
exports["image/png"] = ImageParser;
exports["image/gif"] = ImageParser;
exports["application/pdf"] = ImageParser;
exports["image/x-icon"] = ImageParser;
})();
/*\
title: $:/core/modules/parsers/textparser.js
type: application/javascript
module-type: parser
The plain text parser processes blocks of source text into a degenerate parse tree consisting of a single text node
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var TextParser = function(type,text,options) {
this.tree = [{
type: "codeblock",
attributes: {
code: {type: "string", value: text},
language: {type: "string", value: type}
}
}];
};
exports["text/plain"] = TextParser;
exports["text/x-tiddlywiki"] = TextParser;
exports["application/javascript"] = TextParser;
exports["application/json"] = TextParser;
exports["text/css"] = TextParser;
exports["application/x-tiddler-dictionary"] = TextParser;
})();
/*\
title: $:/core/modules/parsers/videoparser.js
type: application/javascript
module-type: parser
The video parser parses a video tiddler into an embeddable HTML element
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var AudioParser = function(type,text,options) {
var element = {
type: "element",
tag: "video",
attributes: {
controls: {type: "string", value: "controls"}
}
},
src;
if(options._canonical_uri) {
element.attributes.src = {type: "string", value: options._canonical_uri};
} else if(text) {
element.attributes.src = {type: "string", value: "data:" + type + ";base64," + text};
}
this.tree = [element];
};
exports["video/mp4"] = AudioParser;
})();
/*\
title: $:/core/modules/parsers/wikiparser/abstractwikiparser.js
type: application/javascript
module-type: global
base class- individual wikiparser inherit from this class
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var AbstrWikiParser = function(specifier) {
this.type = specifier.type;
this.source = specifier.source;
this.options =specifier.options;
this.wiki = this.options.wiki;
this.pragmaRuleClasses=specifier.pragmaRuleClasses;
this.blockRuleClasses=specifier.blockRuleClasses;
this.inlineRuleClasses=specifier.inlineRuleClasses;
this.sourceLength = this.source.length;
// Set current parse position
this.pos = 0;
// Instantiate the pragma parse rules
this.pragmaRules = this.instantiateRules(this.pragmaRuleClasses,"pragma",0);
// Instantiate the parser block and inline rules
this.blockRules = this.instantiateRules(this.blockRuleClasses,"block",0);
this.inlineRules = this.instantiateRules(this.inlineRuleClasses,"inline",0);
// Parse any pragmas
this.tree = [];
var topBranch = this.parsePragmas();
// Parse the text into inline runs or blocks
if(this.options.parseAsInline) {
topBranch.push.apply(topBranch,this.parseInlineRun());
} else {
topBranch.push.apply(topBranch,this.parseBlocks());
}
// Return the parse tree
};
AbstrWikiParser.prototype =Object.create(
require("$:/core/modules/parsers/wikiparser/wikiparser.js")["text/vnd.tiddlywiki"].prototype);
exports["AbstrWikiParser"] = AbstrWikiParser;
})();
/*\
title: $:/core/modules/parsers/wikiparser/basewikiparser.js
type: application/javascript
module-type: parser
The base wiki text parser
This implementation is sub-optional, it 'steals' its defintion from the text/vnd.tiddlywiki,
it would be better that the text/vnd.tiddlywiki was split into an abstract base and a realisation
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
function override(a, b) {
var hash = {};
return a.concat(b).filter(function (val) {
return hash[val] ? 0 : hash[val] = 1;
});
}
var createClassesList= function (ruleList,userlist,nativelist) {
var temp ={};
for (var i=0;i<ruleList.length;i++) {
var rule = ruleList[i];
var found = false;
if (!!userlist)
if (Object.prototype.hasOwnProperty.call(userlist,rule)) {
temp[rule] = userlist[rule];
found = true;
}
if (!found)
if (Object.prototype.hasOwnProperty.call(nativelist,rule)) {
temp[rule] = nativelist[rule];
}
}
return temp;
};
var ParserPrimer = function(type,text,options) {
//BJ meditation if I pass in the complete type here, then I could use this to cache the
//Parser objects.
if(!this.pragmaRuleClasses) {
ParserPrimer.prototype.pragmaRuleClasses = $tw.modules.createClassesFromModules("wikirule","pragma",$tw.WikiRuleBase);
}
if(!this.blockRuleClasses) {
ParserPrimer.prototype.blockRuleClasses = $tw.modules.createClassesFromModules("wikirule","block",$tw.WikiRuleBase);
}
if(!this.inlineRuleClasses) {
ParserPrimer.prototype.inlineRuleClasses = $tw.modules.createClassesFromModules("wikirule","inline",$tw.WikiRuleBase);
}
if(!this.userClasses) {
ParserPrimer.prototype.userClasses = $tw.modules.createClassesFromModules("wikirule","user",$tw.WikiRuleBase);
}
if (!!options.parserrules) {//if($tw.browser)alert("createrules");
if (!!options.parserrules.pragmaRuleList)this.pragmaRuleClasses=createClassesList(options.parserrules.pragmaRuleList, this.userClasses, this.pragmaRuleClasses);
if (!!options.parserrules.blockRuleList)this.blockRuleClasses=createClassesList(options.parserrules.blockRuleList, this.userClasses, this.blockRuleClasses);
if (!!options.parserrules.inlineRuleList)this.inlineRuleClasses=createClassesList(options.parserrules.inlineRuleList, this.userClasses, this.inlineRuleClasses);
}
for (var i = 0;i<this.blockRuleClasses.length;i++) alert (this.blockRuleClasses[i].rule.name);
// Save the parse text
this.type = type || "text/vnd.twbase";
this.source = text || "";
this.options = options;
};
//realise the parser from the abstr parser
var BaseWikiParser5= function (type,text,options) {
require("$:/core/modules/parsers/wikiparser/abstractwikiparser.js")["AbstrWikiParser"].
call(this,new ParserPrimer(type,text,options));
}
BaseWikiParser5.prototype =Object.create(
require("$:/core/modules/parsers/wikiparser/abstractwikiparser.js")["AbstrWikiParser"].prototype);
exports["text/vnd.twbase"] = BaseWikiParser5;
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/codeblock.js
type: application/javascript
module-type: wikirule
Wiki text rule for code blocks. For example:
```
```
This text will not be //wikified//
```
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "codeblock";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match and get language if defined
this.matchRegExp = /```([\w-]*)\r?\n/mg;
};
exports.parse = function() {
var reEnd = /(\r?\n```$)/mg;
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Look for the end of the block
reEnd.lastIndex = this.parser.pos;
var match = reEnd.exec(this.parser.source),
text;
// Process the block
if(match) {
text = this.parser.source.substring(this.parser.pos,match.index);
this.parser.pos = match.index + match[0].length;
} else {
text = this.parser.source.substr(this.parser.pos);
this.parser.pos = this.parser.sourceLength;
}
// Return the $codeblock widget
return [{
type: "codeblock",
attributes: {
code: {type: "string", value: text},
language: {type: "string", value: this.match[1]}
}
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/codeinline.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for code runs. For example:
```
This is a `code run`.
This is another ``code run``
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "codeinline";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /(``?)/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
var reEnd = new RegExp(this.match[1], "mg");
// Look for the end marker
reEnd.lastIndex = this.parser.pos;
var match = reEnd.exec(this.parser.source),
text;
// Process the text
if(match) {
text = this.parser.source.substring(this.parser.pos,match.index);
this.parser.pos = match.index + match[0].length;
} else {
text = this.parser.source.substr(this.parser.pos);
this.parser.pos = this.parser.sourceLength;
}
return [{
type: "element",
tag: "code",
children: [{
type: "text",
text: text
}]
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/commentblock.js
type: application/javascript
module-type: wikirule
Wiki text block rule for HTML comments. For example:
```
<!-- This is a comment -->
```
Note that the syntax for comments is simplified to an opening "<!--" sequence and a closing "-->" sequence -- HTML itself implements a more complex format (see http://ostermiller.org/findhtmlcomment.html)
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "commentblock";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
this.matchRegExp = /<!--/mg;
this.endMatchRegExp = /-->/mg;
};
exports.findNextMatch = function(startPos) {
this.matchRegExp.lastIndex = startPos;
this.match = this.matchRegExp.exec(this.parser.source);
if(this.match) {
this.endMatchRegExp.lastIndex = startPos + this.match[0].length;
this.endMatch = this.endMatchRegExp.exec(this.parser.source);
if(this.endMatch) {
return this.match.index;
}
}
return undefined;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.endMatchRegExp.lastIndex;
// Don't return any elements
return [];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/commentinline.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for HTML comments. For example:
```
<!-- This is a comment -->
```
Note that the syntax for comments is simplified to an opening "<!--" sequence and a closing "-->" sequence -- HTML itself implements a more complex format (see http://ostermiller.org/findhtmlcomment.html)
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "commentinline";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
this.matchRegExp = /<!--/mg;
this.endMatchRegExp = /-->/mg;
};
exports.findNextMatch = function(startPos) {
this.matchRegExp.lastIndex = startPos;
this.match = this.matchRegExp.exec(this.parser.source);
if(this.match) {
this.endMatchRegExp.lastIndex = startPos + this.match[0].length;
this.endMatch = this.endMatchRegExp.exec(this.parser.source);
if(this.endMatch) {
return this.match.index;
}
}
return undefined;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.endMatchRegExp.lastIndex;
// Don't return any elements
return [];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/dash.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for dashes. For example:
```
This is an en-dash: --
This is an em-dash: ---
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "dash";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /-{2,3}(?!-)/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
var dash = this.match[0].length === 2 ? "–" : "—";
return [{
type: "entity",
entity: dash
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/emphasis/bold.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for emphasis - bold. For example:
```
This is ''bold'' text
```
This wikiparser can be modified using the rules eg:
```
\rules except bold
\rules only bold
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "bold";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /''/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Parse the run including the terminator
var tree = this.parser.parseInlineRun(/''/mg,{eatTerminator: true});
// Return the classed span
return [{
type: "element",
tag: "strong",
children: tree
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/emphasis/italic.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for emphasis - italic. For example:
```
This is //italic// text
```
This wikiparser can be modified using the rules eg:
```
\rules except italic
\rules only italic
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "italic";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /\/\//mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Parse the run including the terminator
var tree = this.parser.parseInlineRun(/\/\//mg,{eatTerminator: true});
// Return the classed span
return [{
type: "element",
tag: "em",
children: tree
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/emphasis/strikethrough.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for emphasis - strikethrough. For example:
```
This is ~~strikethrough~~ text
```
This wikiparser can be modified using the rules eg:
```
\rules except strikethrough
\rules only strikethrough
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "strikethrough";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /~~/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Parse the run including the terminator
var tree = this.parser.parseInlineRun(/~~/mg,{eatTerminator: true});
// Return the classed span
return [{
type: "element",
tag: "strike",
children: tree
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/emphasis/subscript.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for emphasis - subscript. For example:
```
This is ,,subscript,, text
```
This wikiparser can be modified using the rules eg:
```
\rules except subscript
\rules only subscript
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "subscript";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /,,/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Parse the run including the terminator
var tree = this.parser.parseInlineRun(/,,/mg,{eatTerminator: true});
// Return the classed span
return [{
type: "element",
tag: "sub",
children: tree
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/emphasis/superscript.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for emphasis - superscript. For example:
```
This is ^^superscript^^ text
```
This wikiparser can be modified using the rules eg:
```
\rules except superscript
\rules only superscript
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "superscript";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /\^\^/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Parse the run including the terminator
var tree = this.parser.parseInlineRun(/\^\^/mg,{eatTerminator: true});
// Return the classed span
return [{
type: "element",
tag: "sup",
children: tree
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/emphasis/underscore.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for emphasis - underscore. For example:
```
This is __underscore__ text
```
This wikiparser can be modified using the rules eg:
```
\rules except underscore
\rules only underscore
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "underscore";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /__/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Parse the run including the terminator
var tree = this.parser.parseInlineRun(/__/mg,{eatTerminator: true});
// Return the classed span
return [{
type: "element",
tag: "u",
children: tree
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/entity.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for HTML entities. For example:
```
This is a copyright symbol: ©
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "entity";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /(&#?[a-zA-Z0-9]{2,8};)/mg;
};
/*
Parse the most recent match
*/
exports.parse = function() {
// Get all the details of the match
var entityString = this.match[1];
// Move past the macro call
this.parser.pos = this.matchRegExp.lastIndex;
// Return the entity
return [{type: "entity", entity: this.match[0]}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/extlink.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for external links. For example:
```
An external link: http://www.tiddlywiki.com/
A suppressed external link: ~http://www.tiddlyspace.com/
```
External links can be suppressed by preceding them with `~`.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "extlink";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /~?(?:file|http|https|mailto|ftp|irc|news|data|skype):[^\s<>{}\[\]`|'"\\^~]+(?:\/|\b)/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Create the link unless it is suppressed
if(this.match[0].substr(0,1) === "~") {
return [{type: "text", text: this.match[0].substr(1)}];
} else {
return [{
type: "element",
tag: "a",
attributes: {
href: {type: "string", value: this.match[0]},
"class": {type: "string", value: "tc-tiddlylink-external"},
target: {type: "string", value: "_blank"}
},
children: [{
type: "text", text: this.match[0]
}]
}];
}
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/filteredtranscludeblock.js
type: application/javascript
module-type: wikirule
Wiki text rule for block-level filtered transclusion. For example:
```
{{{ [tag[docs]] }}}
{{{ [tag[docs]] |tooltip}}}
{{{ [tag[docs]] ||TemplateTitle}}}
{{{ [tag[docs]] |tooltip||TemplateTitle}}}
{{{ [tag[docs]] }}width:40;height:50;}.class.class
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "filteredtranscludeblock";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /\{\{\{([^\|]+?)(?:\|([^\|\{\}]+))?(?:\|\|([^\|\{\}]+))?\}\}([^\}]*)\}(?:\.(\S+))?(?:\r?\n|$)/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Get the match details
var filter = this.match[1],
tooltip = this.match[2],
template = $tw.utils.trim(this.match[3]),
style = this.match[4],
classes = this.match[5];
// Return the list widget
var node = {
type: "list",
attributes: {
filter: {type: "string", value: filter}
},
isBlock: true
};
if(tooltip) {
node.attributes.tooltip = {type: "string", value: tooltip};
}
if(template) {
node.attributes.template = {type: "string", value: template};
}
if(style) {
node.attributes.style = {type: "string", value: style};
}
if(classes) {
node.attributes.itemClass = {type: "string", value: classes.split(".").join(" ")};
}
return [node];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/filteredtranscludeinline.js
type: application/javascript
module-type: wikirule
Wiki text rule for inline filtered transclusion. For example:
```
{{{ [tag[docs]] }}}
{{{ [tag[docs]] |tooltip}}}
{{{ [tag[docs]] ||TemplateTitle}}}
{{{ [tag[docs]] |tooltip||TemplateTitle}}}
{{{ [tag[docs]] }}width:40;height:50;}.class.class
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "filteredtranscludeinline";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /\{\{\{([^\|]+?)(?:\|([^\|\{\}]+))?(?:\|\|([^\|\{\}]+))?\}\}([^\}]*)\}(?:\.(\S+))?/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Get the match details
var filter = this.match[1],
tooltip = this.match[2],
template = $tw.utils.trim(this.match[3]),
style = this.match[4],
classes = this.match[5];
// Return the list widget
var node = {
type: "list",
attributes: {
filter: {type: "string", value: filter}
}
};
if(tooltip) {
node.attributes.tooltip = {type: "string", value: tooltip};
}
if(template) {
node.attributes.template = {type: "string", value: template};
}
if(style) {
node.attributes.style = {type: "string", value: style};
}
if(classes) {
node.attributes.itemClass = {type: "string", value: classes.split(".").join(" ")};
}
return [node];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/hardlinebreaks.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for marking areas with hard line breaks. For example:
```
"""
This is some text
That is set like
It is a Poem
When it is
Clearly
Not
"""
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "hardlinebreaks";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /"""(?:\r?\n)?/mg;
};
exports.parse = function() {
var reEnd = /(""")|(\r?\n)/mg,
tree = [],
match;
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
do {
// Parse the run up to the terminator
tree.push.apply(tree,this.parser.parseInlineRun(reEnd,{eatTerminator: false}));
// Redo the terminator match
reEnd.lastIndex = this.parser.pos;
match = reEnd.exec(this.parser.source);
if(match) {
this.parser.pos = reEnd.lastIndex;
// Add a line break if the terminator was a line break
if(match[2]) {
tree.push({type: "element", tag: "br"});
}
}
} while(match && !match[1]);
// Return the nodes
return tree;
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/heading.js
type: application/javascript
module-type: wikirule
Wiki text block rule for headings
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "heading";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /(!{1,6})/mg;
};
/*
Parse the most recent match
*/
exports.parse = function() {
// Get all the details of the match
var headingLevel = this.match[1].length;
// Move past the !s
this.parser.pos = this.matchRegExp.lastIndex;
// Parse any classes, whitespace and then the heading itself
var classes = this.parser.parseClasses();
this.parser.skipWhitespace({treatNewlinesAsNonWhitespace: true});
var tree = this.parser.parseInlineRun(/(\r?\n)/mg);
// Return the heading
return [{
type: "element",
tag: "h" + headingLevel,
attributes: {
"class": {type: "string", value: classes.join(" ")}
},
children: tree
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/horizrule.js
type: application/javascript
module-type: wikirule
Wiki text block rule for rules. For example:
```
---
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "horizrule";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /-{3,}\r?(?:\n|$)/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
return [{type: "element", tag: "hr"}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/html.js
type: application/javascript
module-type: wikirule
Wiki rule for HTML elements and widgets. For example:
{{{
<aside>
This is an HTML5 aside element
</aside>
<$slider target="MyTiddler">
This is a widget invocation
</$slider>
}}}
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "html";
exports.types = {inline: true, block: true};
exports.init = function(parser) {
this.parser = parser;
};
exports.findNextMatch = function(startPos) {
// Find the next tag
this.nextTag = this.findNextTag(this.parser.source,startPos,{
requireLineBreak: this.is.block
});
return this.nextTag ? this.nextTag.start : undefined;
};
/*
Parse the most recent match
*/
exports.parse = function() {
// Retrieve the most recent match so that recursive calls don't overwrite it
var tag = this.nextTag;
this.nextTag = null;
// Advance the parser position to past the tag
this.parser.pos = tag.end;
// Check for an immediately following double linebreak
var hasLineBreak = !tag.isSelfClosing && !!$tw.utils.parseTokenRegExp(this.parser.source,this.parser.pos,/([^\S\n\r]*\r?\n(?:[^\S\n\r]*\r?\n|$))/g);
// Set whether we're in block mode
tag.isBlock = this.is.block || hasLineBreak;
// Parse the body if we need to
if(!tag.isSelfClosing && $tw.config.htmlVoidElements.indexOf(tag.tag) === -1) {
var reEndString = "</" + $tw.utils.escapeRegExp(tag.tag) + ">",
reEnd = new RegExp("(" + reEndString + ")","mg");
if(hasLineBreak) {
tag.children = this.parser.parseBlocks(reEndString);
} else {
tag.children = this.parser.parseInlineRun(reEnd);
}
reEnd.lastIndex = this.parser.pos;
var endMatch = reEnd.exec(this.parser.source);
if(endMatch && endMatch.index === this.parser.pos) {
this.parser.pos = endMatch.index + endMatch[0].length;
}
}
// Return the tag
return [tag];
};
/*
Look for an HTML tag. Returns null if not found, otherwise returns {type: "element", name:, attributes: [], isSelfClosing:, start:, end:,}
*/
exports.parseTag = function(source,pos,options) {
options = options || {};
var token,
node = {
type: "element",
start: pos,
attributes: {}
};
// Define our regexps
var reTagName = /([a-zA-Z0-9\-\$]+)/g;
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for a less than sign
token = $tw.utils.parseTokenString(source,pos,"<");
if(!token) {
return null;
}
pos = token.end;
// Get the tag name
token = $tw.utils.parseTokenRegExp(source,pos,reTagName);
if(!token) {
return null;
}
node.tag = token.match[1];
if(node.tag.charAt(0) === "$") {
node.type = node.tag.substr(1);
}
pos = token.end;
// Process attributes
var attribute = $tw.utils.parseAttribute(source,pos);
while(attribute) {
node.attributes[attribute.name] = attribute;
pos = attribute.end;
// Get the next attribute
attribute = $tw.utils.parseAttribute(source,pos);
}
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for a closing slash
token = $tw.utils.parseTokenString(source,pos,"/");
if(token) {
pos = token.end;
node.isSelfClosing = true;
}
// Look for a greater than sign
token = $tw.utils.parseTokenString(source,pos,">");
if(!token) {
return null;
}
pos = token.end;
// Check for a required line break
if(options.requireLineBreak) {
token = $tw.utils.parseTokenRegExp(source,pos,/([^\S\n\r]*\r?\n(?:[^\S\n\r]*\r?\n|$))/g);
if(!token) {
return null;
}
}
// Update the end position
node.end = pos;
return node;
};
exports.findNextTag = function(source,pos,options) {
// A regexp for finding candidate HTML tags
var reLookahead = /<([a-zA-Z\-\$]+)/g;
// Find the next candidate
reLookahead.lastIndex = pos;
var match = reLookahead.exec(source);
while(match) {
// Try to parse the candidate as a tag
var tag = this.parseTag(source,match.index,options);
// Return success
if(tag && this.isLegalTag(tag)) {
return tag;
}
// Look for the next match
reLookahead.lastIndex = match.index + 1;
match = reLookahead.exec(source);
}
// Failed
return null;
};
exports.isLegalTag = function(tag) {
// Widgets are always OK
if(tag.type !== "element") {
return true;
// If it's an HTML tag that starts with a dash then it's not legal
} else if(tag.tag.charAt(0) === "-") {
return false;
} else {
// Otherwise it's OK
return true;
}
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/image.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for embedding images. For example:
```
[img[http://tiddlywiki.com/fractalveg.jpg]]
[img width=23 height=24 [http://tiddlywiki.com/fractalveg.jpg]]
[img width={{!!width}} height={{!!height}} [http://tiddlywiki.com/fractalveg.jpg]]
[img[Description of image|http://tiddlywiki.com/fractalveg.jpg]]
[img[TiddlerTitle]]
[img[Description of image|TiddlerTitle]]
```
Generates the `<$image>` widget.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "image";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
};
exports.findNextMatch = function(startPos) {
// Find the next tag
this.nextImage = this.findNextImage(this.parser.source,startPos);
return this.nextImage ? this.nextImage.start : undefined;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.nextImage.end;
var node = {
type: "image",
attributes: this.nextImage.attributes
};
return [node];
};
/*
Find the next image from the current position
*/
exports.findNextImage = function(source,pos) {
// A regexp for finding candidate HTML tags
var reLookahead = /(\[img)/g;
// Find the next candidate
reLookahead.lastIndex = pos;
var match = reLookahead.exec(source);
while(match) {
// Try to parse the candidate as a tag
var tag = this.parseImage(source,match.index);
// Return success
if(tag) {
return tag;
}
// Look for the next match
reLookahead.lastIndex = match.index + 1;
match = reLookahead.exec(source);
}
// Failed
return null;
};
/*
Look for an image at the specified position. Returns null if not found, otherwise returns {type: "image", attributes: [], isSelfClosing:, start:, end:,}
*/
exports.parseImage = function(source,pos) {
var token,
node = {
type: "image",
start: pos,
attributes: {}
};
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for the `[img`
token = $tw.utils.parseTokenString(source,pos,"[img");
if(!token) {
return null;
}
pos = token.end;
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Process attributes
if(source.charAt(pos) !== "[") {
var attribute = $tw.utils.parseAttribute(source,pos);
while(attribute) {
node.attributes[attribute.name] = attribute;
pos = attribute.end;
pos = $tw.utils.skipWhiteSpace(source,pos);
if(source.charAt(pos) !== "[") {
// Get the next attribute
attribute = $tw.utils.parseAttribute(source,pos);
} else {
attribute = null;
}
}
}
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for the `[` after the attributes
token = $tw.utils.parseTokenString(source,pos,"[");
if(!token) {
return null;
}
pos = token.end;
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Get the source up to the terminating `]]`
token = $tw.utils.parseTokenRegExp(source,pos,/(?:([^|\]]*?)\|)?([^\]]+?)\]\]/g);
if(!token) {
return null;
}
pos = token.end;
if(token.match[1]) {
node.attributes.tooltip = {type: "string", value: token.match[1].trim()};
}
node.attributes.source = {type: "string", value: (token.match[2] || "").trim()};
// Update the end position
node.end = pos;
return node;
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/list.js
type: application/javascript
module-type: wikirule
Wiki text block rule for lists. For example:
```
* This is an unordered list
* It has two items
# This is a numbered list
## With a subitem
# And a third item
; This is a term that is being defined
: This is the definition of that term
```
Note that lists can be nested arbitrarily:
```
#** One
#* Two
#** Three
#**** Four
#**# Five
#**## Six
## Seven
### Eight
## Nine
```
A CSS class can be applied to a list item as follows:
```
* List item one
*.active List item two has the class `active`
* List item three
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "list";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /([\*#;:>]+)/mg;
};
var listTypes = {
"*": {listTag: "ul", itemTag: "li"},
"#": {listTag: "ol", itemTag: "li"},
";": {listTag: "dl", itemTag: "dt"},
":": {listTag: "dl", itemTag: "dd"},
">": {listTag: "blockquote", itemTag: "p"}
};
/*
Parse the most recent match
*/
exports.parse = function() {
// Array of parse tree nodes for the previous row of the list
var listStack = [];
// Cycle through the items in the list
while(true) {
// Match the list marker
var reMatch = /([\*#;:>]+)/mg;
reMatch.lastIndex = this.parser.pos;
var match = reMatch.exec(this.parser.source);
if(!match || match.index !== this.parser.pos) {
break;
}
// Check whether the list type of the top level matches
var listInfo = listTypes[match[0].charAt(0)];
if(listStack.length > 0 && listStack[0].tag !== listInfo.listTag) {
break;
}
// Move past the list marker
this.parser.pos = match.index + match[0].length;
// Walk through the list markers for the current row
for(var t=0; t<match[0].length; t++) {
listInfo = listTypes[match[0].charAt(t)];
// Remove any stacked up element if we can't re-use it because the list type doesn't match
if(listStack.length > t && listStack[t].tag !== listInfo.listTag) {
listStack.splice(t,listStack.length - t);
}
// Construct the list element or reuse the previous one at this level
if(listStack.length <= t) {
var listElement = {type: "element", tag: listInfo.listTag, children: [
{type: "element", tag: listInfo.itemTag, children: []}
]};
// Link this list element into the last child item of the parent list item
if(t) {
var prevListItem = listStack[t-1].children[listStack[t-1].children.length-1];
prevListItem.children.push(listElement);
}
// Save this element in the stack
listStack[t] = listElement;
} else if(t === (match[0].length - 1)) {
listStack[t].children.push({type: "element", tag: listInfo.itemTag, children: []});
}
}
if(listStack.length > match[0].length) {
listStack.splice(match[0].length,listStack.length - match[0].length);
}
// Process the body of the list item into the last list item
var lastListChildren = listStack[listStack.length-1].children,
lastListItem = lastListChildren[lastListChildren.length-1],
classes = this.parser.parseClasses();
this.parser.skipWhitespace({treatNewlinesAsNonWhitespace: true});
var tree = this.parser.parseInlineRun(/(\r?\n)/mg);
lastListItem.children.push.apply(lastListItem.children,tree);
if(classes.length > 0) {
$tw.utils.addClassToParseTreeNode(lastListItem,classes.join(" "));
}
// Consume any whitespace following the list item
this.parser.skipWhitespace();
}
// Return the root element of the list
return [listStack[0]];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/macrocallblock.js
type: application/javascript
module-type: wikirule
Wiki rule for block macro calls
```
<<name value value2>>
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "macrocallblock";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /<<([^>\s]+)(?:\s*)((?:[^>]|(?:>(?!>)))*?)>>(?:\r?\n|$)/mg;
};
/*
Parse the most recent match
*/
exports.parse = function() {
// Get all the details of the match
var macroName = this.match[1],
paramString = this.match[2];
// Move past the macro call
this.parser.pos = this.matchRegExp.lastIndex;
var params = [],
reParam = /\s*(?:([A-Za-z0-9\-_]+)\s*:)?(?:\s*(?:"""([\s\S]*?)"""|"([^"]*)"|'([^']*)'|\[\[([^\]]*)\]\]|([^"'\s]+)))/mg,
paramMatch = reParam.exec(paramString);
while(paramMatch) {
// Process this parameter
var paramInfo = {
value: paramMatch[2] || paramMatch[3] || paramMatch[4] || paramMatch[5] || paramMatch[6]
};
if(paramMatch[1]) {
paramInfo.name = paramMatch[1];
}
params.push(paramInfo);
// Find the next match
paramMatch = reParam.exec(paramString);
}
return [{
type: "macrocall",
name: macroName,
params: params,
isBlock: true
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/macrocallinline.js
type: application/javascript
module-type: wikirule
Wiki rule for macro calls
```
<<name value value2>>
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "macrocallinline";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /<<([^\s>]+)\s*([\s\S]*?)>>/mg;
};
/*
Parse the most recent match
*/
exports.parse = function() {
// Get all the details of the match
var macroName = this.match[1],
paramString = this.match[2];
// Move past the macro call
this.parser.pos = this.matchRegExp.lastIndex;
var params = [],
reParam = /\s*(?:([A-Za-z0-9\-_]+)\s*:)?(?:\s*(?:"""([\s\S]*?)"""|"([^"]*)"|'([^']*)'|\[\[([^\]]*)\]\]|([^"'\s]+)))/mg,
paramMatch = reParam.exec(paramString);
while(paramMatch) {
// Process this parameter
var paramInfo = {
value: paramMatch[2] || paramMatch[3] || paramMatch[4] || paramMatch[5]|| paramMatch[6]
};
if(paramMatch[1]) {
paramInfo.name = paramMatch[1];
}
params.push(paramInfo);
// Find the next match
paramMatch = reParam.exec(paramString);
}
return [{
type: "macrocall",
name: macroName,
params: params
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/macrodef.js
type: application/javascript
module-type: wikirule
Wiki pragma rule for macro definitions
```
\define name(param:defaultvalue,param2:defaultvalue)
definition text, including $param$ markers
\end
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "macrodef";
exports.types = {pragma: true};
/*
Instantiate parse rule
*/
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /^\\define\s+([^(\s]+)\(\s*([^)]*)\)(\s*\r?\n)?/mg;
};
/*
Parse the most recent match
*/
exports.parse = function() {
// Move past the macro name and parameters
this.parser.pos = this.matchRegExp.lastIndex;
// Parse the parameters
var paramString = this.match[2],
params = [];
if(paramString !== "") {
var reParam = /\s*([A-Za-z0-9\-_]+)(?:\s*:\s*(?:"""([\s\S]*?)"""|"([^"]*)"|'([^']*)'|\[\[([^\]]*)\]\]|([^"'\s]+)))?/mg,
paramMatch = reParam.exec(paramString);
while(paramMatch) {
// Save the parameter details
var paramInfo = {name: paramMatch[1]},
defaultValue = paramMatch[2] || paramMatch[3] || paramMatch[4] || paramMatch[5] || paramMatch[6];
if(defaultValue) {
paramInfo["default"] = defaultValue;
}
params.push(paramInfo);
// Look for the next parameter
paramMatch = reParam.exec(paramString);
}
}
// Is this a multiline definition?
var reEnd;
if(this.match[3]) {
// If so, the end of the body is marked with \end
reEnd = /(\r?\n\\end[^\S\n\r]*(?:$|\r?\n))/mg;
} else {
// Otherwise, the end of the definition is marked by the end of the line
reEnd = /(\r?\n)/mg;
// Move past any whitespace
this.parser.pos = $tw.utils.skipWhiteSpace(this.parser.source,this.parser.pos);
}
// Find the end of the definition
reEnd.lastIndex = this.parser.pos;
var text,
endMatch = reEnd.exec(this.parser.source);
if(endMatch) {
text = this.parser.source.substring(this.parser.pos,endMatch.index);
this.parser.pos = endMatch.index + endMatch[0].length;
} else {
// We didn't find the end of the definition, so we'll make it blank
text = "";
}
// Save the macro definition
return [{
type: "set",
attributes: {
name: {type: "string", value: this.match[1]},
value: {type: "string", value: text}
},
children: [],
params: params
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/prettyextlink.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for external links. For example:
```
[ext[http://tiddlywiki.com/fractalveg.jpg]]
[ext[Tooltip|http://tiddlywiki.com/fractalveg.jpg]]
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "prettyextlink";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
};
exports.findNextMatch = function(startPos) {
// Find the next tag
this.nextLink = this.findNextLink(this.parser.source,startPos);
return this.nextLink ? this.nextLink.start : undefined;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.nextLink.end;
return [this.nextLink];
};
/*
Find the next link from the current position
*/
exports.findNextLink = function(source,pos) {
// A regexp for finding candidate links
var reLookahead = /(\[ext\[)/g;
// Find the next candidate
reLookahead.lastIndex = pos;
var match = reLookahead.exec(source);
while(match) {
// Try to parse the candidate as a link
var link = this.parseLink(source,match.index);
// Return success
if(link) {
return link;
}
// Look for the next match
reLookahead.lastIndex = match.index + 1;
match = reLookahead.exec(source);
}
// Failed
return null;
};
/*
Look for an link at the specified position. Returns null if not found, otherwise returns {type: "element", tag: "a", attributes: [], isSelfClosing:, start:, end:,}
*/
exports.parseLink = function(source,pos) {
var token,
textNode = {
type: "text"
},
node = {
type: "element",
tag: "a",
start: pos,
attributes: {
"class": {type: "string", value: "tc-tiddlylink-external"},
},
children: [textNode]
};
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for the `[ext[`
token = $tw.utils.parseTokenString(source,pos,"[ext[");
if(!token) {
return null;
}
pos = token.end;
// Look ahead for the terminating `]]`
var closePos = source.indexOf("]]",pos);
if(closePos === -1) {
return null;
}
// Look for a `|` separating the tooltip
var splitPos = source.indexOf("|",pos);
if(splitPos === -1 || splitPos > closePos) {
splitPos = null;
}
// Pull out the tooltip and URL
var tooltip, URL;
if(splitPos) {
URL = source.substring(splitPos + 1,closePos).trim();
textNode.text = source.substring(pos,splitPos).trim();
} else {
URL = source.substring(pos,closePos).trim();
textNode.text = URL;
}
node.attributes.href = {type: "string", value: URL};
node.attributes.target = {type: "string", value: "_blank"};
// Update the end position
node.end = closePos + 2;
return node;
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/prettylink.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for pretty links. For example:
```
[[Introduction]]
[[Link description|TiddlerTitle]]
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "prettylink";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /\[\[(.*?)(?:\|(.*?))?\]\]/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Process the link
var text = this.match[1],
link = this.match[2] || text;
if($tw.utils.isLinkExternal(link)) {
return [{
type: "element",
tag: "a",
attributes: {
href: {type: "string", value: link},
"class": {type: "string", value: "tc-tiddlylink-external"},
target: {type: "string", value: "_blank"}
},
children: [{
type: "text", text: text
}]
}];
} else {
return [{
type: "link",
attributes: {
to: {type: "string", value: link}
},
children: [{
type: "text", text: text
}]
}];
}
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/quoteblock.js
type: application/javascript
module-type: wikirule
Wiki text rule for quote blocks. For example:
```
<<<.optionalClass(es) optional cited from
a quote
<<<
<<<.optionalClass(es)
a quote
<<< optional cited from
```
Quotes can be quoted by putting more <s
```
<<<
Quote Level 1
<<<<
QuoteLevel 2
<<<<
<<<
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "quoteblock";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /(<<<+)/mg;
};
exports.parse = function() {
var classes = ["tc-quote"];
// Get all the details of the match
var reEndString = "^" + this.match[1] + "(?!<)";
// Move past the <s
this.parser.pos = this.matchRegExp.lastIndex;
// Parse any classes, whitespace and then the optional cite itself
classes.push.apply(classes, this.parser.parseClasses());
this.parser.skipWhitespace({treatNewlinesAsNonWhitespace: true});
var cite = this.parser.parseInlineRun(/(\r?\n)/mg);
// before handling the cite, parse the body of the quote
var tree= this.parser.parseBlocks(reEndString);
// If we got a cite, put it before the text
if(cite.length > 0) {
tree.unshift({
type: "element",
tag: "cite",
children: cite
});
}
// Parse any optional cite
this.parser.skipWhitespace({treatNewlinesAsNonWhitespace: true});
cite = this.parser.parseInlineRun(/(\r?\n)/mg);
// If we got a cite, push it
if(cite.length > 0) {
tree.push({
type: "element",
tag: "cite",
children: cite
});
}
// Return the blockquote element
return [{
type: "element",
tag: "blockquote",
attributes: {
class: { type: "string", value: classes.join(" ") },
},
children: tree
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/rules.js
type: application/javascript
module-type: wikirule
Wiki pragma rule for rules specifications
```
\rules except ruleone ruletwo rulethree
\rules only ruleone ruletwo rulethree
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "rules";
exports.types = {pragma: true};
/*
Instantiate parse rule
*/
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /^\\rules[^\S\n]/mg;
};
/*
Parse the most recent match
*/
exports.parse = function() {
// Move past the pragma invocation
this.parser.pos = this.matchRegExp.lastIndex;
// Parse whitespace delimited tokens terminated by a line break
var reMatch = /[^\S\n]*(\S+)|(\r?\n)/mg,
tokens = [];
reMatch.lastIndex = this.parser.pos;
var match = reMatch.exec(this.parser.source);
while(match && match.index === this.parser.pos) {
this.parser.pos = reMatch.lastIndex;
// Exit if we've got the line break
if(match[2]) {
break;
}
// Process the token
if(match[1]) {
tokens.push(match[1]);
}
// Match the next token
match = reMatch.exec(this.parser.source);
}
// Process the tokens
if(tokens.length > 0) {
this.parser.amendRules(tokens[0],tokens.slice(1));
}
// No parse tree nodes to return
return [];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/styleblock.js
type: application/javascript
module-type: wikirule
Wiki text block rule for assigning styles and classes to paragraphs and other blocks. For example:
```
@@.myClass
@@background-color:red;
This paragraph will have the CSS class `myClass`.
* The `<ul>` around this list will also have the class `myClass`
* List item 2
@@
```
Note that classes and styles can be mixed subject to the rule that styles must precede classes. For example
```
@@.myFirstClass.mySecondClass
@@width:100px;.myThirdClass
This is a paragraph
@@
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "styleblock";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /@@((?:[^\.\r\n\s:]+:[^\r\n;]+;)+)?(?:\.([^\r\n\s]+))?\r?\n/mg;
};
exports.parse = function() {
var reEndString = "^@@(?:\\r?\\n)?";
var classes = [], styles = [];
do {
// Get the class and style
if(this.match[1]) {
styles.push(this.match[1]);
}
if(this.match[2]) {
classes.push(this.match[2].split(".").join(" "));
}
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Look for another line of classes and styles
this.match = this.matchRegExp.exec(this.parser.source);
} while(this.match && this.match.index === this.parser.pos);
// Parse the body
var tree = this.parser.parseBlocks(reEndString);
for(var t=0; t<tree.length; t++) {
if(classes.length > 0) {
$tw.utils.addClassToParseTreeNode(tree[t],classes.join(" "));
}
if(styles.length > 0) {
$tw.utils.addAttributeToParseTreeNode(tree[t],"style",styles.join(""));
}
}
return tree;
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/styleinline.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for assigning styles and classes to inline runs. For example:
```
@@.myClass This is some text with a class@@
@@background-color:red;This is some text with a background colour@@
@@width:100px;.myClass This is some text with a class and a width@@
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "styleinline";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /@@((?:[^\.\r\n\s:]+:[^\r\n;]+;)+)?(\.(?:[^\r\n\s]+)\s+)?/mg;
};
exports.parse = function() {
var reEnd = /@@/g;
// Get the styles and class
var stylesString = this.match[1],
classString = this.match[2] ? this.match[2].split(".").join(" ") : undefined;
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Parse the run up to the terminator
var tree = this.parser.parseInlineRun(reEnd,{eatTerminator: true});
// Return the classed span
var node = {
type: "element",
tag: "span",
attributes: {
"class": {type: "string", value: "tc-inline-style"}
},
children: tree
};
if(classString) {
$tw.utils.addClassToParseTreeNode(node,classString);
}
if(stylesString) {
$tw.utils.addAttributeToParseTreeNode(node,"style",stylesString);
}
return [node];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/syslink.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for system tiddler links.
Can be suppressed preceding them with `~`.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "syslink";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /~?\$:\/[a-zA-Z0-9/.\-_]+/mg;
};
exports.parse = function() {
var match = this.match[0];
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Create the link unless it is suppressed
if(match.substr(0,1) === "~") {
return [{type: "text", text: match.substr(1)}];
} else {
return [{
type: "link",
attributes: {
to: {type: "string", value: match}
},
children: [{
type: "text",
text: match
}]
}];
}
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/table.js
type: application/javascript
module-type: wikirule
Wiki text block rule for tables.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "table";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /^\|(?:[^\n]*)\|(?:[fhck]?)\r?(?:\n|$)/mg;
};
var processRow = function(prevColumns) {
var cellRegExp = /(?:\|([^\n\|]*)\|)|(\|[fhck]?\r?(?:\n|$))/mg,
cellTermRegExp = /((?:\x20*)\|)/mg,
tree = [],
col = 0,
colSpanCount = 1,
prevCell,
vAlign;
// Match a single cell
cellRegExp.lastIndex = this.parser.pos;
var cellMatch = cellRegExp.exec(this.parser.source);
while(cellMatch && cellMatch.index === this.parser.pos) {
if(cellMatch[1] === "~") {
// Rowspan
var last = prevColumns[col];
if(last) {
last.rowSpanCount++;
$tw.utils.addAttributeToParseTreeNode(last.element,"rowspan",last.rowSpanCount);
vAlign = $tw.utils.getAttributeValueFromParseTreeNode(last.element,"valign","center");
$tw.utils.addAttributeToParseTreeNode(last.element,"valign",vAlign);
if(colSpanCount > 1) {
$tw.utils.addAttributeToParseTreeNode(last.element,"colspan",colSpanCount);
colSpanCount = 1;
}
}
// Move to just before the `|` terminating the cell
this.parser.pos = cellRegExp.lastIndex - 1;
} else if(cellMatch[1] === ">") {
// Colspan
colSpanCount++;
// Move to just before the `|` terminating the cell
this.parser.pos = cellRegExp.lastIndex - 1;
} else if(cellMatch[1] === "<" && prevCell) {
colSpanCount = 1 + $tw.utils.getAttributeValueFromParseTreeNode(prevCell,"colspan",1);
$tw.utils.addAttributeToParseTreeNode(prevCell,"colspan",colSpanCount);
colSpanCount = 1;
// Move to just before the `|` terminating the cell
this.parser.pos = cellRegExp.lastIndex - 1;
} else if(cellMatch[2]) {
// End of row
if(prevCell && colSpanCount > 1) {
if(prevCell.attributes && prevCell.attributes && prevCell.attributes.colspan) {
colSpanCount += prevCell.attributes.colspan.value;
} else {
colSpanCount -= 1;
}
$tw.utils.addAttributeToParseTreeNode(prevCell,"colspan",colSpanCount);
}
this.parser.pos = cellRegExp.lastIndex - 1;
break;
} else {
// For ordinary cells, step beyond the opening `|`
this.parser.pos++;
// Look for a space at the start of the cell
var spaceLeft = false;
vAlign = null;
if(this.parser.source.substr(this.parser.pos).search(/^\^([^\^]|\^\^)/) === 0) {
vAlign = "top";
} else if(this.parser.source.substr(this.parser.pos).search(/^,([^,]|,,)/) === 0) {
vAlign = "bottom";
}
if(vAlign) {
this.parser.pos++;
}
var chr = this.parser.source.substr(this.parser.pos,1);
while(chr === " ") {
spaceLeft = true;
this.parser.pos++;
chr = this.parser.source.substr(this.parser.pos,1);
}
// Check whether this is a heading cell
var cell;
if(chr === "!") {
this.parser.pos++;
cell = {type: "element", tag: "th", children: []};
} else {
cell = {type: "element", tag: "td", children: []};
}
tree.push(cell);
// Record information about this cell
prevCell = cell;
prevColumns[col] = {rowSpanCount:1,element:cell};
// Check for a colspan
if(colSpanCount > 1) {
$tw.utils.addAttributeToParseTreeNode(cell,"colspan",colSpanCount);
colSpanCount = 1;
}
// Parse the cell
cell.children = this.parser.parseInlineRun(cellTermRegExp,{eatTerminator: true});
// Set the alignment for the cell
if(vAlign) {
$tw.utils.addAttributeToParseTreeNode(cell,"valign",vAlign);
}
if(this.parser.source.substr(this.parser.pos - 2,1) === " ") { // spaceRight
$tw.utils.addAttributeToParseTreeNode(cell,"align",spaceLeft ? "center" : "left");
} else if(spaceLeft) {
$tw.utils.addAttributeToParseTreeNode(cell,"align","right");
}
// Move back to the closing `|`
this.parser.pos--;
}
col++;
cellRegExp.lastIndex = this.parser.pos;
cellMatch = cellRegExp.exec(this.parser.source);
}
return tree;
};
exports.parse = function() {
var rowContainerTypes = {"c":"caption", "h":"thead", "":"tbody", "f":"tfoot"},
table = {type: "element", tag: "table", children: []},
rowRegExp = /^\|([^\n]*)\|([fhck]?)\r?(?:\n|$)/mg,
rowTermRegExp = /(\|(?:[fhck]?)\r?(?:\n|$))/mg,
prevColumns = [],
currRowType,
rowContainer,
rowCount = 0;
// Match the row
rowRegExp.lastIndex = this.parser.pos;
var rowMatch = rowRegExp.exec(this.parser.source);
while(rowMatch && rowMatch.index === this.parser.pos) {
var rowType = rowMatch[2];
// Check if it is a class assignment
if(rowType === "k") {
$tw.utils.addClassToParseTreeNode(table,rowMatch[1]);
this.parser.pos = rowMatch.index + rowMatch[0].length;
} else {
// Otherwise, create a new row if this one is of a different type
if(rowType !== currRowType) {
rowContainer = {type: "element", tag: rowContainerTypes[rowType], children: []};
table.children.push(rowContainer);
currRowType = rowType;
}
// Is this a caption row?
if(currRowType === "c") {
// If so, move past the opening `|` of the row
this.parser.pos++;
// Move the caption to the first row if it isn't already
if(table.children.length !== 1) {
table.children.pop(); // Take rowContainer out of the children array
table.children.splice(0,0,rowContainer); // Insert it at the bottom
}
// Set the alignment - TODO: figure out why TW did this
// rowContainer.attributes.align = rowCount === 0 ? "top" : "bottom";
// Parse the caption
rowContainer.children = this.parser.parseInlineRun(rowTermRegExp,{eatTerminator: true});
} else {
// Create the row
var theRow = {type: "element", tag: "tr", children: []};
$tw.utils.addClassToParseTreeNode(theRow,rowCount%2 ? "oddRow" : "evenRow");
rowContainer.children.push(theRow);
// Process the row
theRow.children = processRow.call(this,prevColumns);
this.parser.pos = rowMatch.index + rowMatch[0].length;
// Increment the row count
rowCount++;
}
}
rowMatch = rowRegExp.exec(this.parser.source);
}
return [table];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/transcludeblock.js
type: application/javascript
module-type: wikirule
Wiki text rule for block-level transclusion. For example:
```
{{MyTiddler}}
{{MyTiddler||TemplateTitle}}
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "transcludeblock";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /\{\{([^\{\}\|]*)(?:\|\|([^\|\{\}]+))?\}\}(?:\r?\n|$)/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Get the match details
var template = $tw.utils.trim(this.match[2]),
textRef = $tw.utils.trim(this.match[1]);
// Prepare the transclude widget
var transcludeNode = {
type: "transclude",
attributes: {},
isBlock: true
};
// Prepare the tiddler widget
var tr, targetTitle, targetField, targetIndex, tiddlerNode;
if(textRef) {
tr = $tw.utils.parseTextReference(textRef);
targetTitle = tr.title;
targetField = tr.field;
targetIndex = tr.index;
tiddlerNode = {
type: "tiddler",
attributes: {
tiddler: {type: "string", value: targetTitle}
},
isBlock: true,
children: [transcludeNode]
};
}
if(template) {
transcludeNode.attributes.tiddler = {type: "string", value: template};
if(textRef) {
return [tiddlerNode];
} else {
return [transcludeNode];
}
} else {
if(textRef) {
transcludeNode.attributes.tiddler = {type: "string", value: targetTitle};
if(targetField) {
transcludeNode.attributes.field = {type: "string", value: targetField};
}
if(targetIndex) {
transcludeNode.attributes.index = {type: "string", value: targetIndex};
}
return [tiddlerNode];
} else {
return [transcludeNode];
}
}
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/transcludeinline.js
type: application/javascript
module-type: wikirule
Wiki text rule for inline-level transclusion. For example:
```
{{MyTiddler}}
{{MyTiddler||TemplateTitle}}
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "transcludeinline";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /\{\{([^\{\}\|]*)(?:\|\|([^\|\{\}]+))?\}\}/mg;
};
exports.parse = function() {
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Get the match details
var template = $tw.utils.trim(this.match[2]),
textRef = $tw.utils.trim(this.match[1]);
// Prepare the transclude widget
var transcludeNode = {
type: "transclude",
attributes: {}
};
// Prepare the tiddler widget
var tr, targetTitle, targetField, targetIndex, tiddlerNode;
if(textRef) {
tr = $tw.utils.parseTextReference(textRef);
targetTitle = tr.title;
targetField = tr.field;
targetIndex = tr.index;
tiddlerNode = {
type: "tiddler",
attributes: {
tiddler: {type: "string", value: targetTitle}
},
children: [transcludeNode]
};
}
if(template) {
transcludeNode.attributes.tiddler = {type: "string", value: template};
if(textRef) {
return [tiddlerNode];
} else {
return [transcludeNode];
}
} else {
if(textRef) {
transcludeNode.attributes.tiddler = {type: "string", value: targetTitle};
if(targetField) {
transcludeNode.attributes.field = {type: "string", value: targetField};
}
if(targetIndex) {
transcludeNode.attributes.index = {type: "string", value: targetIndex};
}
return [tiddlerNode];
} else {
return [transcludeNode];
}
}
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/typedblock.js
type: application/javascript
module-type: wikirule
Wiki text rule for typed blocks. For example:
```
$$$.js
This will be rendered as JavaScript
$$$
$$$.svg
<svg xmlns="http://www.w3.org/2000/svg" width="150" height="100">
<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" />
</svg>
$$$
$$$text/vnd.tiddlywiki>text/html
This will be rendered as an //HTML representation// of WikiText
$$$
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var widget = require("$:/core/modules/widgets/widget.js");
exports.name = "typedblock";
exports.types = {block: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = /\$\$\$([^ >\r\n]*)(?: *> *([^ \r\n]+))?\r?\n/mg;
};
exports.parse = function() {
var reEnd = /\r?\n\$\$\$\r?(?:\n|$)/mg;
// Save the type
var parseType = this.match[1],
renderType = this.match[2];
// Move past the match
this.parser.pos = this.matchRegExp.lastIndex;
// Look for the end of the block
reEnd.lastIndex = this.parser.pos;
var match = reEnd.exec(this.parser.source),
text;
// Process the block
if(match) {
text = this.parser.source.substring(this.parser.pos,match.index);
this.parser.pos = match.index + match[0].length;
} else {
text = this.parser.source.substr(this.parser.pos);
this.parser.pos = this.parser.sourceLength;
}
// Parse the block according to the specified type
var parser = this.parser.wiki.parseText(parseType,text,{defaultType: "text/plain"});
// If there's no render type, just return the parse tree
if(!renderType) {
return parser.tree;
} else {
// Otherwise, render to the rendertype and return in a <PRE> tag
var widgetNode = this.parser.wiki.makeWidget(parser),
container = $tw.fakeDocument.createElement("div");
widgetNode.render(container,null);
text = renderType === "text/html" ? container.innerHTML : container.textContent;
return [{
type: "element",
tag: "pre",
children: [{
type: "text",
text: text
}]
}];
}
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/wikilink.js
type: application/javascript
module-type: wikirule
Wiki text inline rule for wiki links. For example:
```
AWikiLink
AnotherLink
~SuppressedLink
```
Precede a camel case word with `~` to prevent it from being recognised as a link.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.name = "wikilink";
exports.types = {inline: true};
exports.init = function(parser) {
this.parser = parser;
// Regexp to match
this.matchRegExp = new RegExp($tw.config.textPrimitives.unWikiLink + "?" + $tw.config.textPrimitives.wikiLink,"mg");
};
/*
Parse the most recent match
*/
exports.parse = function() {
// Get the details of the match
var linkText = this.match[0];
// Move past the macro call
this.parser.pos = this.matchRegExp.lastIndex;
// If the link starts with the unwikilink character then just output it as plain text
if(linkText.substr(0,1) === $tw.config.textPrimitives.unWikiLink) {
return [{type: "text", text: linkText.substr(1)}];
}
// If the link has been preceded with a blocked letter then don't treat it as a link
if(this.match.index > 0) {
var preRegExp = new RegExp($tw.config.textPrimitives.blockPrefixLetters,"mg");
preRegExp.lastIndex = this.match.index-1;
var preMatch = preRegExp.exec(this.parser.source);
if(preMatch && preMatch.index === this.match.index-1) {
return [{type: "text", text: linkText}];
}
}
return [{
type: "link",
attributes: {
to: {type: "string", value: linkText}
},
children: [{
type: "text",
text: linkText
}]
}];
};
})();
/*\
title: $:/core/modules/parsers/wikiparser/rules/wikirulebase.js
type: application/javascript
module-type: global
Base class for wiki parser rules
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
This constructor is always overridden with a blank constructor, and so shouldn't be used
*/
var WikiRuleBase = function() {
};
/*
To be overridden by individual rules
*/
WikiRuleBase.prototype.init = function(parser) {
this.parser = parser;
};
/*
Default implementation of findNextMatch uses RegExp matching
*/
WikiRuleBase.prototype.findNextMatch = function(startPos) {
this.matchRegExp.lastIndex = startPos;
this.match = this.matchRegExp.exec(this.parser.source);
return this.match ? this.match.index : undefined;
};
exports.WikiRuleBase = WikiRuleBase;
})();
/*\
title: $:/core/modules/parsers/wikiparser/wikiadapter.js
type: application/javascript
module-type: global
overrides for wiki.js
\*/
(function(){
var wiki = require("$:/core/modules/wiki.js");
wiki.mergesetting = function(items, adjustitems) {
if (!adjustitems) return;//nothing to do
$tw.utils.each(adjustitems,function(adjustitem, listname) {
if (!!items[listname]) {
if (items[listname] instanceof Array) {//merge lists
var i,baselen=items[listname].length;
for (var j=0; j<adjustitem.length; j++){
for ( i=0; i<baselen; i++) {
if (adjustitem[j]===items[listname][i]) break;
}
if (i===baselen) items[listname].push(adjustitem[j]);
}
} else {
items[listname]=adjustitem;//override item
}
} else items[listname]=adjustitem;//add new item
})
}
/*
recursive function, retrives parseroptions from tiddlers/files
returns preparser, baseparser type and parserrules
*/
wiki.makeparsers=function(type,text,options){
var returns={};
var typeParts = type.split(";flexibility=");
if (typeParts.length >1) {
var typeDialog =typeParts[1];//alert(typeDialog);
var readdata=$tw.wiki.getTiddlerData(typeDialog);
//read json tid (typeDialog )containing:
// one string var of preparser eg text/type>html
// baseparser
// parserdata
// concaternate parserdata with baseparser -recursive
// overload baserparser's preparser with this preparser
if (!!readdata) {
if (!!readdata.baserules)
returns=this.makeparsers(readdata.baserules,text,options);
if (!!readdata.parseAsInline) returns.parseAsInline =readdata.parseAsInline;
if (!returns.parserrules) returns.parserrules = readdata.parserrules;
else this.mergesetting(returns.parserrules,readdata.parserrules);
returns.type = typeParts[0];//overrides basetype of baserules
if (!!readdata.preparser) returns.preparser =readdata.preparser;//override baserule preparser
//alert(parserdata);
} else {
returns.type=type;
returns.parserrules=null;
returns.preparser=null;
}
} else {
returns.type=type;
returns.parserrules=null;
returns.preparser=null;
}
return returns;
}
wiki.prepasstext =function(preparser,text, options) {
var preparserpart = preparser.split(">");
return this.renderText(preparserpart[1],preparserpart[0],text,options);
}
/*
Parse a block of text of a specified MIME type
type: content type of text to be parsed
text: text
options: see below
Options include:
parseAsInline: if true, the text of the tiddler will be parsed as an inline run
*/
wiki.parseText = function(type,text,options) {
options = options || {};
var parserdata;
// Select a parser
if(type !== undefined) { //get type is undefined when built
parserdata=this.makeparsers(type,text,options);
type=parserdata.type;
if (!!parserdata.parseAsInline) options.parseAsInline =parserdata.parseAsInline;
if (!!parserdata.preparser) text = this.prepasstext.call(this,parserdata.preparser,text,options);
}
var Parser = $tw.Wiki.parsers[type];
if(!Parser && $tw.config.fileExtensionInfo[type]) {
Parser = $tw.Wiki.parsers[$tw.config.fileExtensionInfo[type].type];
}
if(!Parser) {
Parser = $tw.Wiki.parsers[options.defaultType || "text/vnd.tiddlywiki"];
}
if(!Parser) {
return null;
}
// Return the parser instance
return new Parser(type,text,{
parseAsInline: options.parseAsInline,
wiki: this,
_canonical_uri: options._canonical_uri,
parserrules:(type !== undefined)?parserdata.parserrules:null
});
};
})();
/*\
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
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
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");
}
// Initialise the 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/");
}
if(!this.blockRuleClasses) {
WikiParser.prototype.blockRuleClasses = $tw.modules.createClassesFromModules("wikirule","block",$tw.WikiRuleBase);
this.setupRules(WikiParser.prototype.blockRuleClasses,"$:/config/WikiParserRules/Block/");
}
if(!this.inlineRuleClasses) {
WikiParser.prototype.inlineRuleClasses = $tw.modules.createClassesFromModules("wikirule","inline",$tw.WikiRuleBase);
this.setupRules(WikiParser.prototype.inlineRuleClasses,"$:/config/WikiParserRules/Inline/");
}
// Save the parse text
this.type = type || "text/vnd.tiddlywiki";
this.source = text || "";
this.sourceLength = this.source.length;
// Set current parse position
this.pos = 0;
// Instantiate the pragma parse rules
this.pragmaRules = this.instantiateRules(this.pragmaRuleClasses,"pragma",0);
// Instantiate the parser block and inline rules
this.blockRules = this.instantiateRules(this.blockRuleClasses,"block",0);
this.inlineRules = this.instantiateRules(this.inlineRuleClasses,"inline",0);
// Parse any pragmas
this.tree = [];
var topBranch = this.parsePragmas();
// Parse the text into inline runs or blocks
if(options.parseAsInline) {
topBranch.push.apply(topBranch,this.parseInlineRun());
} else {
topBranch.push.apply(topBranch,this.parseBlocks());
}
// 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) {
// 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) {
break;
}
// Process the pragma rule
var subTree = nextMatch.rule.parse();
if(subTree.length > 0) {
// 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;
}
}
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) {
return nextMatch.rule.parse();
}
// Treat it as a paragraph if we didn't find a block rule
return [{type: "element", tag: "p", children: this.parseInlineRun(terminatorRegExp)}];
};
/*
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
*/
WikiParser.prototype.parseBlocksTerminated = function(terminatorRegExpString) {
var terminatorRegExp = new RegExp("(" + terminatorRegExpString + ")","mg"),
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);
tree.push.apply(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;
}
return tree;
};
/*
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) {
tree.push({type: "text", text: this.source.substring(this.pos,nextMatch.matchIndex)});
this.pos = nextMatch.matchIndex;
}
// Process the run rule
tree.push.apply(tree,nextMatch.rule.parse());
// Look for the next run rule
nextMatch = this.findNextMatch(this.inlineRules,this.pos);
}
// Process the remaining text
if(this.pos < this.sourceLength) {
tree.push({type: "text", text: this.source.substr(this.pos)});
}
this.pos = this.sourceLength;
return tree;
};
WikiParser.prototype.parseInlineRunTerminated = 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) {
tree.push({type: "text", text: this.source.substring(this.pos,terminatorMatch.index)});
}
this.pos = terminatorMatch.index;
if(options.eatTerminator) {
this.pos += terminatorMatch[0].length;
}
return tree;
}
}
// Process any inline rule, along with the text preceding it
if(inlineRuleMatch) {
// Preceding text
if(inlineRuleMatch.matchIndex > this.pos) {
tree.push({type: "text", text: this.source.substring(this.pos,inlineRuleMatch.matchIndex)});
this.pos = inlineRuleMatch.matchIndex;
}
// Process the inline rule
tree.push.apply(tree,inlineRuleMatch.rule.parse());
// 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) {
tree.push({type: "text", text: this.source.substr(this.pos)});
}
this.pos = this.sourceLength;
return tree;
};
/*
Parse zero or more class specifiers `.classname`
*/
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);
}
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 keepFilter;
if(type === "only") {
keepFilter = function(name) {
return names.indexOf(name) !== -1;
};
} else if(type === "except") {
keepFilter = function(name) {
return names.indexOf(name) === -1;
};
} 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(!keepFilter(ruleArray[t].rule.name)) {
ruleArray.splice(t,1);
}
}
};
// Process each rule array
processRuleArray(this.pragmaRules);
processRuleArray(this.blockRules);
processRuleArray(this.inlineRules);
};
exports["text/vnd.tiddlywiki"] = WikiParser;
})();
/*\
title: $:/core/modules/pluginswitcher.js
type: application/javascript
module-type: global
Manages switching plugins for themes and languages.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
options:
wiki: wiki store to be used
pluginType: type of plugin to be switched
controllerTitle: title of tiddler used to control switching of this resource
defaultPlugins: array of default plugins to be used if nominated plugin isn't found
*/
function PluginSwitcher(options) {
this.wiki = options.wiki;
this.pluginType = options.pluginType;
this.controllerTitle = options.controllerTitle;
this.defaultPlugins = options.defaultPlugins || [];
// Switch to the current plugin
this.switchPlugins();
// Listen for changes to the selected plugin
var self = this;
this.wiki.addEventListener("change",function(changes) {
if($tw.utils.hop(changes,self.controllerTitle)) {
self.switchPlugins();
}
});
}
PluginSwitcher.prototype.switchPlugins = function() {
// Get the name of the current theme
var selectedPluginTitle = this.wiki.getTiddlerText(this.controllerTitle);
// If it doesn't exist, then fallback to one of the default themes
var index = 0;
while(!this.wiki.getTiddler(selectedPluginTitle) && index < this.defaultPlugins.length) {
selectedPluginTitle = this.defaultPlugins[index++];
}
// Accumulate the titles of the plugins that we need to load
var plugins = [],
self = this,
accumulatePlugin = function(title) {
var tiddler = self.wiki.getTiddler(title);
if(tiddler && tiddler.isPlugin() && plugins.indexOf(title) === -1) {
plugins.push(title);
var pluginInfo = JSON.parse(self.wiki.getTiddlerText(title)),
dependents = $tw.utils.parseStringArray(tiddler.fields.dependents || "");
$tw.utils.each(dependents,function(title) {
accumulatePlugin(title);
});
}
};
accumulatePlugin(selectedPluginTitle);
// Unregister any existing theme tiddlers
var unregisteredTiddlers = $tw.wiki.unregisterPluginTiddlers(this.pluginType);
// Register any new theme tiddlers
var registeredTiddlers = $tw.wiki.registerPluginTiddlers(this.pluginType,plugins);
// Unpack the current theme tiddlers
$tw.wiki.unpackPluginTiddlers();
};
exports.PluginSwitcher = PluginSwitcher;
})();
/*\
title: $:/core/modules/saver-handler.js
type: application/javascript
module-type: global
The saver handler tracks changes to the store and handles saving the entire wiki via saver modules.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Instantiate the saver handler with the following options:
wiki: wiki to be synced
dirtyTracking: true if dirty tracking should be performed
*/
function SaverHandler(options) {
var self = this;
this.wiki = options.wiki;
this.dirtyTracking = options.dirtyTracking;
this.pendingAutoSave = false;
// Make a logger
this.logger = new $tw.utils.Logger("saver-handler");
// Initialise our savers
if($tw.browser) {
this.initSavers();
}
// Only do dirty tracking if required
if($tw.browser && this.dirtyTracking) {
// Compile the dirty tiddler filter
this.filterFn = this.wiki.compileFilter(this.wiki.getTiddlerText(this.titleSyncFilter));
// Count of changes that have not yet been saved
this.numChanges = 0;
// Listen out for changes to tiddlers
this.wiki.addEventListener("change",function(changes) {
// Filter the changes so that we only count changes to tiddlers that we care about
var filteredChanges = self.filterFn.call(self.wiki,function(callback) {
$tw.utils.each(changes,function(change,title) {
var tiddler = self.wiki.getTiddler(title);
callback(tiddler,title);
});
});
// Adjust the number of changes
self.numChanges += filteredChanges.length;
self.updateDirtyStatus();
// Do any autosave if one is pending and there's no more change events
if(self.pendingAutoSave && self.wiki.getSizeOfTiddlerEventQueue() === 0) {
// Check if we're dirty
if(self.numChanges > 0) {
self.saveWiki({
method: "autosave",
downloadType: "text/plain"
});
}
self.pendingAutoSave = false;
}
});
// Listen for the autosave event
$tw.rootWidget.addEventListener("tm-auto-save-wiki",function(event) {
// Do the autosave unless there are outstanding tiddler change events
if(self.wiki.getSizeOfTiddlerEventQueue() === 0) {
// Check if we're dirty
if(self.numChanges > 0) {
self.saveWiki({
method: "autosave",
downloadType: "text/plain"
});
}
} else {
// Otherwise put ourselves in the "pending autosave" state and wait for the change event before we do the autosave
self.pendingAutoSave = true;
}
});
// Set up our beforeunload handler
$tw.addUnloadTask(function(event) {
var confirmationMessage;
if(self.isDirty()) {
confirmationMessage = $tw.language.getString("UnsavedChangesWarning");
event.returnValue = confirmationMessage; // Gecko
}
return confirmationMessage;
});
}
// Install the save action handlers
if($tw.browser) {
$tw.rootWidget.addEventListener("tm-save-wiki",function(event) {
self.saveWiki({
template: event.param,
downloadType: "text/plain",
variables: event.paramObject
});
});
$tw.rootWidget.addEventListener("tm-download-file",function(event) {
self.saveWiki({
method: "download",
template: event.param,
downloadType: "text/plain",
variables: event.paramObject
});
});
}
}
SaverHandler.prototype.titleSyncFilter = "$:/config/SaverFilter";
SaverHandler.prototype.titleAutoSave = "$:/config/AutoSave";
SaverHandler.prototype.titleSavedNotification = "$:/language/Notifications/Save/Done";
/*
Select the appropriate saver modules and set them up
*/
SaverHandler.prototype.initSavers = function(moduleType) {
moduleType = moduleType || "saver";
// Instantiate the available savers
this.savers = [];
var self = this;
$tw.modules.forEachModuleOfType(moduleType,function(title,module) {
if(module.canSave(self)) {
self.savers.push(module.create(self.wiki));
}
});
// Sort the savers into priority order
this.savers.sort(function(a,b) {
if(a.info.priority < b.info.priority) {
return -1;
} else {
if(a.info.priority > b.info.priority) {
return +1;
} else {
return 0;
}
}
});
};
/*
Save the wiki contents. Options are:
method: "save", "autosave" or "download"
template: the tiddler containing the template to save
downloadType: the content type for the saved file
*/
SaverHandler.prototype.saveWiki = function(options) {
options = options || {};
var self = this,
method = options.method || "save",
variables = options.variables || {},
template = options.template || "$:/core/save/all",
downloadType = options.downloadType || "text/plain",
text = this.wiki.renderTiddler(downloadType,template,options),
callback = function(err) {
if(err) {
alert("Error while saving:\n\n" + err);
} else {
// Clear the task queue if we're saving (rather than downloading)
if(method !== "download") {
self.numChanges = 0;
self.updateDirtyStatus();
}
$tw.notifier.display(self.titleSavedNotification);
if(options.callback) {
options.callback();
}
}
};
// Ignore autosave if disabled
if(method === "autosave" && this.wiki.getTiddlerText(this.titleAutoSave,"yes") !== "yes") {
return false;
}
// Call the highest priority saver that supports this method
for(var t=this.savers.length-1; t>=0; t--) {
var saver = this.savers[t];
if(saver.info.capabilities.indexOf(method) !== -1 && saver.save(text,method,callback,{variables: {filename: variables.filename}})) {
this.logger.log("Saving wiki with method",method,"through saver",saver.info.name);
return true;
}
}
return false;
};
/*
Checks whether the wiki is dirty (ie the window shouldn't be closed)
*/
SaverHandler.prototype.isDirty = function() {
return this.numChanges > 0;
};
/*
Update the document body with the class "tc-dirty" if the wiki has unsaved/unsynced changes
*/
SaverHandler.prototype.updateDirtyStatus = function() {
if($tw.browser) {
$tw.utils.toggleClass(document.body,"tc-dirty",this.isDirty());
}
};
exports.SaverHandler = SaverHandler;
})();
/*\
title: $:/core/modules/savers/andtidwiki.js
type: application/javascript
module-type: saver1
Handles saving changes via the AndTidWiki Android app
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false, netscape: false, Components: false */
"use strict";
var AndTidWiki = function(wiki) {
};
AndTidWiki.prototype.save = function(text,method,callback) {return true;
// Get the pathname of this document
var pathname = decodeURIComponent(document.location.toString().split("#")[0]);
// Strip the file://
if(pathname.indexOf("file://") === 0) {
pathname = pathname.substr(7);
}
// Strip any query or location part
var p = pathname.indexOf("?");
if(p !== -1) {
pathname = pathname.substr(0,p);
}
p = pathname.indexOf("#");
if(p !== -1) {
pathname = pathname.substr(0,p);
}
// Save the file
window.twi.saveFile(pathname,text);
// Call the callback
callback(null);
return true;
};
/*
Information about this saver
*/
AndTidWiki.prototype.info = {
name: "andtidwiki",
priority: 1600,
capabilities: ["save", "autosave"]
};
/*
Static method that returns true if this saver is capable of working
*/
exports.canSave = function(wiki) {
return !!window.twi && !!window.twi.saveFile;
};
/*
Create an instance of this saver
*/
exports.create = function(wiki) {
return new AndTidWiki(wiki);
};
})();
/*\
title: $:/core/modules/savers/download.js
type: application/javascript
module-type: saver
Handles saving changes via HTML5's download APIs
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Select the appropriate saver module and set it up
*/
var DownloadSaver = function(wiki) {
};
DownloadSaver.prototype.save = function(text,method,callback,options) {
options = options || {};
return true;//BJ mod
// Get the current filename
var filename = options.variables.filename;
if(!filename) {
var p = document.location.pathname.lastIndexOf("/");
if(p !== -1) {
filename = document.location.pathname.substr(p+1);
}
}
if(!filename) {
filename = "tiddlywiki.html";
}
// Set up the link
var link = document.createElement("a");
link.setAttribute("target","_blank");
if(Blob !== undefined) {
var blob = new Blob([text], {type: "text/html"});
link.setAttribute("href", URL.createObjectURL(blob));
} else {
link.setAttribute("href","data:text/html," + encodeURIComponent(text));
}
link.setAttribute("download",filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Callback that we succeeded
callback(null);
return true;
};
/*
Information about this saver
*/
DownloadSaver.prototype.info = {
name: "download",
priority: 100,
capabilities: ["save", "download"]
};
/*
Static method that returns true if this saver is capable of working
*/
exports.canSave = function(wiki) {
return document.createElement("a").download !== undefined;
};
/*
Create an instance of this saver
*/
exports.create = function(wiki) {
return new DownloadSaver(wiki);
};
})();
/*\
title: $:/core/modules/savers/fsosaver.js
type: application/javascript
module-type: saver1
Handles saving changes via MS FileSystemObject ActiveXObject
Note: Since TiddlyWiki's markup contains the MOTW, the FileSystemObject normally won't be available.
However, if the wiki is loaded as an .HTA file (Windows HTML Applications) then the FSO can be used.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Select the appropriate saver module and set it up
*/
var FSOSaver = function(wiki) {
};
FSOSaver.prototype.save = function(text,method,callback) {return true;
// Get the pathname of this document
var pathname = unescape(document.location.pathname);
// Test for a Windows path of the form /x:\blah...
if(/^\/[A-Z]\:\\[^\\]+/i.test(pathname)) { // ie: ^/[a-z]:/[^/]+
// Remove the leading slash
pathname = pathname.substr(1);
} else if(document.location.hostname !== "" && /^\/\\[^\\]+\\[^\\]+/i.test(pathname)) { // test for \\server\share\blah... - ^/[^/]+/[^/]+
// Remove the leading slash
pathname = pathname.substr(1);
// reconstruct UNC path
pathname = "\\\\" + document.location.hostname + pathname;
} else {
return false;
}
// Save the file (as UTF-16)
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(pathname,2,-1,-1);
file.Write(text);
file.Close();
// Callback that we succeeded
callback(null);
return true;
};
/*
Information about this saver
*/
FSOSaver.prototype.info = {
name: "FSOSaver",
priority: 120,
capabilities: ["save", "autosave"]
};
/*
Static method that returns true if this saver is capable of working
*/
exports.canSave = function(wiki) {
try {
return (window.location.protocol === "file:") && !!(new ActiveXObject("Scripting.FileSystemObject"));
} catch(e) { return false; }
};
/*
Create an instance of this saver
*/
exports.create = function(wiki) {
return new FSOSaver(wiki);
};
})();
/*\
title: $:/core/modules/savers/manualdownload.js
type: application/javascript
module-type: saver1
Handles saving changes via HTML5's download APIs
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Title of the tiddler containing the download message
var downloadInstructionsTitle = "$:/language/Modals/Download";
/*
Select the appropriate saver module and set it up
*/
var ManualDownloadSaver = function(wiki) {
};
ManualDownloadSaver.prototype.save = function(text,method,callback) {return true;
$tw.modal.display(downloadInstructionsTitle,{
downloadLink: "data:text/html," + encodeURIComponent(text)
});
// Callback that we succeeded
callback(null);
return true;
};
/*
Information about this saver
*/
ManualDownloadSaver.prototype.info = {
name: "manualdownload",
priority: 0,
capabilities: ["save", "download"]
};
/*
Static method that returns true if this saver is capable of working
*/
exports.canSave = function(wiki) {
return true;
};
/*
Create an instance of this saver
*/
exports.create = function(wiki) {
return new ManualDownloadSaver(wiki);
};
})();
/*\
title: $:/core/modules/savers/msdownload.js
type: application/javascript
module-type: saver1
Handles saving changes via window.navigator.msSaveBlob()
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Select the appropriate saver module and set it up
*/
var MsDownloadSaver = function(wiki) {
};
MsDownloadSaver.prototype.save = function(text,method,callback) {return true;
// Get the current filename
var filename = "tiddlywiki.html",
p = document.location.pathname.lastIndexOf("/");
if(p !== -1) {
filename = document.location.pathname.substr(p+1);
}
// Set up the link
var blob = new Blob([text], {type: "text/html"});
window.navigator.msSaveBlob(blob,filename);
// Callback that we succeeded
callback(null);
return true;
};
/*
Information about this saver
*/
MsDownloadSaver.prototype.info = {
name: "msdownload",
priority: 110,
capabilities: ["save", "download"]
};
/*
Static method that returns true if this saver is capable of working
*/
exports.canSave = function(wiki) {
return !!window.navigator.msSaveBlob;
};
/*
Create an instance of this saver
*/
exports.create = function(wiki) {
return new MsDownloadSaver(wiki);
};
})();
/*\
title: $:/core/modules/savers/tiddlyfox.js
type: application/javascript
module-type: saver1
Handles saving changes via the TiddlyFox file extension
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false, netscape: false, Components: false */
"use strict";
var TiddlyFoxSaver = function(wiki) {
};
TiddlyFoxSaver.prototype.save = function(text,method,callback) {return true;
var messageBox = document.getElementById("tiddlyfox-message-box");
if(messageBox) {
// Get the pathname of this document
var pathname = document.location.toString().split("#")[0];
// Replace file://localhost/ with file:///
if(pathname.indexOf("file://localhost/") === 0) {
pathname = "file://" + pathname.substr(16);
}
// Windows path file:///x:/blah/blah --> x:\blah\blah
if(/^file\:\/\/\/[A-Z]\:\//i.test(pathname)) {
// Remove the leading slash and convert slashes to backslashes
pathname = pathname.substr(8).replace(/\//g,"\\");
// Firefox Windows network path file://///server/share/blah/blah --> //server/share/blah/blah
} else if(pathname.indexOf("file://///") === 0) {
pathname = "\\\\" + unescape(pathname.substr(10)).replace(/\//g,"\\");
// Mac/Unix local path file:///path/path --> /path/path
} else if(pathname.indexOf("file:///") === 0) {
pathname = unescape(pathname.substr(7));
// Mac/Unix local path file:/path/path --> /path/path
} else if(pathname.indexOf("file:/") === 0) {
pathname = unescape(pathname.substr(5));
// Otherwise Windows networth path file://server/share/path/path --> \\server\share\path\path
} else {
pathname = "\\\\" + unescape(pathname.substr(7)).replace(new RegExp("/","g"),"\\");
}
// Create the message element and put it in the message box
var message = document.createElement("div");
message.setAttribute("data-tiddlyfox-path",decodeURIComponent(pathname));
message.setAttribute("data-tiddlyfox-content",text);
messageBox.appendChild(message);
// Add an event handler for when the file has been saved
message.addEventListener("tiddlyfox-have-saved-file",function(event) {
callback(null);
}, false);
// Create and dispatch the custom event to the extension
var event = document.createEvent("Events");
event.initEvent("tiddlyfox-save-file",true,false);
message.dispatchEvent(event);
return true;
} else {
return false;
}
};
/*
Information about this saver
*/
TiddlyFoxSaver.prototype.info = {
name: "tiddlyfox",
priority: 1500,
capabilities: ["save", "autosave"]
};
/*
Static method that returns true if this saver is capable of working
*/
exports.canSave = function(wiki) {
return (window.location.protocol === "file:");
};
/*
Create an instance of this saver
*/
exports.create = function(wiki) {
return new TiddlyFoxSaver(wiki);
};
})();
/*\
title: $:/core/modules/savers/tiddlyie.js
type: application/javascript
module-type: saver1
Handles saving changes via Internet Explorer BHO extenion (TiddlyIE)
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Select the appropriate saver module and set it up
*/
var TiddlyIESaver = function(wiki) {
};
TiddlyIESaver.prototype.save = function(text,method,callback) {return true;
// Check existence of TiddlyIE BHO extension (note: only works after document is complete)
if(typeof(window.TiddlyIE) != "undefined") {
// Get the pathname of this document
var pathname = unescape(document.location.pathname);
// Test for a Windows path of the form /x:/blah...
if(/^\/[A-Z]\:\/[^\/]+/i.test(pathname)) { // ie: ^/[a-z]:/[^/]+ (is this better?: ^/[a-z]:/[^/]+(/[^/]+)*\.[^/]+ )
// Remove the leading slash
pathname = pathname.substr(1);
// Convert slashes to backslashes
pathname = pathname.replace(/\//g,"\\");
} else if(document.hostname !== "" && /^\/[^\/]+\/[^\/]+/i.test(pathname)) { // test for \\server\share\blah... - ^/[^/]+/[^/]+
// Convert slashes to backslashes
pathname = pathname.replace(/\//g,"\\");
// reconstruct UNC path
pathname = "\\\\" + document.location.hostname + pathname;
} else return false;
// Prompt the user to save the file
window.TiddlyIE.save(pathname, text);
// Callback that we succeeded
callback(null);
return true;
} else {
return false;
}
};
/*
Information about this saver
*/
TiddlyIESaver.prototype.info = {
name: "tiddlyiesaver",
priority: 1500,
capabilities: ["save"]
};
/*
Static method that returns true if this saver is capable of working
*/
exports.canSave = function(wiki) {
return (window.location.protocol === "file:");
};
/*
Create an instance of this saver
*/
exports.create = function(wiki) {
return new TiddlyIESaver(wiki);
};
})();
/*\
title: $:/core/modules/savers/twedit.js
type: application/javascript
module-type: saver1
Handles saving changes via the TWEdit iOS app
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false, netscape: false, Components: false */
"use strict";
var TWEditSaver = function(wiki) {
};
TWEditSaver.prototype.save = function(text,method,callback) {return true;
// Bail if we're not running under TWEdit
if(typeof DeviceInfo !== "object") {
return false;
}
// Get the pathname of this document
var pathname = decodeURIComponent(document.location.pathname);
// Strip any query or location part
var p = pathname.indexOf("?");
if(p !== -1) {
pathname = pathname.substr(0,p);
}
p = pathname.indexOf("#");
if(p !== -1) {
pathname = pathname.substr(0,p);
}
// Remove the leading "/Documents" from path
var prefix = "/Documents";
if(pathname.indexOf(prefix) === 0) {
pathname = pathname.substr(prefix.length);
}
// Error handler
var errorHandler = function(event) {
// Error
callback("Error saving to TWEdit: " + event.target.error.code);
};
// Get the file system
window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(fileSystem) {
// Now we've got the filesystem, get the fileEntry
fileSystem.root.getFile(pathname, {create: true}, function(fileEntry) {
// Now we've got the fileEntry, create the writer
fileEntry.createWriter(function(writer) {
writer.onerror = errorHandler;
writer.onwrite = function() {
callback(null);
};
writer.position = 0;
writer.write(text);
},errorHandler);
}, errorHandler);
}, errorHandler);
return true;
};
/*
Information about this saver
*/
TWEditSaver.prototype.info = {
name: "twedit",
priority: 1600,
capabilities: ["save", "autosave"]
};
/*
Static method that returns true if this saver is capable of working
*/
exports.canSave = function(wiki) {
return true;
};
/*
Create an instance of this saver
*/
exports.create = function(wiki) {
return new TWEditSaver(wiki);
};
/////////////////////////// Hack
// HACK: This ensures that TWEdit recognises us as a TiddlyWiki document
if($tw.browser) {
window.version = {title: "TiddlyWiki"};
}
})();
/*\
title: $:/core/modules/savers/upload.js
type: application/javascript
module-type: saver1
Handles saving changes via upload to a server.
Designed to be compatible with BidiX's UploadPlugin at http://tiddlywiki.bidix.info/#UploadPlugin
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Select the appropriate saver module and set it up
*/
var UploadSaver = function(wiki) {
this.wiki = wiki;
};
UploadSaver.prototype.save = function(text,method,callback) {return true;
// Get the various parameters we need
var backupDir = this.wiki.getTextReference("$:/UploadBackupDir") || ".",
username = this.wiki.getTextReference("$:/UploadName"),
password = $tw.utils.getPassword("upload"),
uploadDir = this.wiki.getTextReference("$:/UploadDir") || ".",
uploadFilename = this.wiki.getTextReference("$:/UploadFilename") || "index.html",
url = this.wiki.getTextReference("$:/UploadURL");
// Bail out if we don't have the bits we need
if(!username || username.toString().trim() === "" || !password || password.toString().trim() === "") {
return false;
}
// Construct the url if not provided
if(!url) {
url = "http://" + username + ".tiddlyspot.com/store.cgi";
}
// Assemble the header
var boundary = "---------------------------" + "AaB03x";
var uploadFormName = "UploadPlugin";
var head = [];
head.push("--" + boundary + "\r\nContent-disposition: form-data; name=\"UploadPlugin\"\r\n");
head.push("backupDir=" + backupDir + ";user=" + username + ";password=" + password + ";uploaddir=" + uploadDir + ";;");
head.push("\r\n" + "--" + boundary);
head.push("Content-disposition: form-data; name=\"userfile\"; filename=\"" + uploadFilename + "\"");
head.push("Content-Type: text/html;charset=UTF-8");
head.push("Content-Length: " + text.length + "\r\n");
head.push("");
// Assemble the tail and the data itself
var tail = "\r\n--" + boundary + "--\r\n",
data = head.join("\r\n") + text + tail;
// Do the HTTP post
var http = new XMLHttpRequest();
http.open("POST",url,true,username,password);
http.setRequestHeader("Content-Type","multipart/form-data; ;charset=UTF-8; boundary=" + boundary);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
if(http.responseText.substr(0,4) === "0 - ") {
callback(null);
} else {
callback(http.responseText);
}
}
};
try {
http.send(data);
} catch(ex) {
return callback("Error:" + ex);
}
$tw.notifier.display("$:/language/Notifications/Save/Starting");
return true;
};
/*
Information about this saver
*/
UploadSaver.prototype.info = {
name: "upload",
priority: 2000,
capabilities: ["save", "autosave"]
};
/*
Static method that returns true if this saver is capable of working
*/
exports.canSave = function(wiki) {
return true;
};
/*
Create an instance of this saver
*/
exports.create = function(wiki) {
return new UploadSaver(wiki);
};
})();
/*\
title: $:/core/modules/startup.js
type: application/javascript
module-type: startup
Miscellaneous startup logic for both the client and server.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "startup";
exports.after = ["load-modules"];
exports.synchronous = true;
// Set to `true` to enable performance instrumentation
var PERFORMANCE_INSTRUMENTATION_CONFIG_TITLE = "$:/config/Performance/Instrumentation";
var widget = require("$:/core/modules/widgets/widget.js");
exports.startup = function() {
var modules,n,m,f;
if($tw.browser) {
$tw.browser.isIE = (/msie|trident/i.test(navigator.userAgent));
}
$tw.version = $tw.utils.extractVersionInfo();
// Set up the performance framework
$tw.perf = new $tw.Performance($tw.wiki.getTiddlerText(PERFORMANCE_INSTRUMENTATION_CONFIG_TITLE,"no") === "yes");
// Kick off the language manager and switcher
$tw.language = new $tw.Language();
$tw.languageSwitcher = new $tw.PluginSwitcher({
wiki: $tw.wiki,
pluginType: "language",
controllerTitle: "$:/language",
defaultPlugins: [
"$:/languages/en-US"
]
});
// Kick off the theme manager
$tw.themeManager = new $tw.PluginSwitcher({
wiki: $tw.wiki,
pluginType: "theme",
controllerTitle: "$:/theme",
defaultPlugins: [
"$:/themes/tiddlywiki/snowwhite",
"$:/themes/tiddlywiki/vanilla"
]
});
// Clear outstanding tiddler store change events to avoid an unnecessary refresh cycle at startup
$tw.wiki.clearTiddlerEventQueue();
// Create a root widget for attaching event handlers. By using it as the parentWidget for another widget tree, one can reuse the event handlers
if($tw.browser) {
$tw.rootWidget = new widget.widget({
type: "widget",
children: []
},{
wiki: $tw.wiki,
document: document
});
}
// Find a working syncadaptor
$tw.syncadaptor = undefined;
$tw.modules.forEachModuleOfType("syncadaptor",function(title,module) {
if(!$tw.syncadaptor && module.adaptorClass) {
$tw.syncadaptor = new module.adaptorClass({wiki: $tw.wiki});
}
});
// Set up the syncer object if we've got a syncadaptor
if($tw.syncadaptor) {
$tw.syncer = new $tw.Syncer({wiki: $tw.wiki, syncadaptor: $tw.syncadaptor});
}
// Setup the saver handler
$tw.saverHandler = new $tw.SaverHandler({wiki: $tw.wiki, dirtyTracking: !$tw.syncadaptor});
// Host-specific startup
if($tw.browser) {
// Install the popup manager
$tw.popup = new $tw.utils.Popup();
// Install the animator
$tw.anim = new $tw.utils.Animator();
}
};
})();
/*\
title: $:/core/modules/startup/commands.js
type: application/javascript
module-type: startup
Command processing
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "commands";
exports.platforms = ["node"];
exports.after = ["story"];
exports.synchronous = false;
exports.startup = function(callback) {
// On the server, start a commander with the command line arguments
var commander = new $tw.Commander(
$tw.boot.argv,
function(err) {
if(err) {
return $tw.utils.error("Error: " + err);
}
callback();
},
$tw.wiki,
{output: process.stdout, error: process.stderr}
);
commander.execute();
};
})();
/*\
title: $:/core/modules/startup/favicon.js
type: application/javascript
module-type: startup
Favicon handling
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "favicon";
exports.platforms = ["browser"];
exports.after = ["startup"];
exports.synchronous = true;
// Favicon tiddler
var FAVICON_TITLE = "$:/favicon.ico";
exports.startup = function() {
// Set up the favicon
setFavicon();
// Reset the favicon when the tiddler changes
$tw.wiki.addEventListener("change",function(changes) {
if($tw.utils.hop(changes,FAVICON_TITLE)) {
setFavicon();
}
});
};
function setFavicon() {
var tiddler = $tw.wiki.getTiddler(FAVICON_TITLE);
if(tiddler) {
var faviconLink = document.getElementById("faviconLink");
faviconLink.setAttribute("href","data:" + tiddler.fields.type + ";base64," + tiddler.fields.text);
}
}
})();
/*\
title: $:/core/modules/startup/info.js
type: application/javascript
module-type: startup
Initialise $:/info tiddlers via $:/temp/info-plugin pseudo-plugin
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "info";
exports.before = ["startup"];
exports.after = ["load-modules"];
exports.synchronous = true;
exports.startup = function() {
// Collect up the info tiddlers
var infoTiddlerFields = {};
// Give each info module a chance to fill in as many info tiddlers as they want
$tw.modules.forEachModuleOfType("info",function(title,moduleExports) {
if(moduleExports && moduleExports.getInfoTiddlerFields) {
var tiddlerFieldsArray = moduleExports.getInfoTiddlerFields(infoTiddlerFields);
$tw.utils.each(tiddlerFieldsArray,function(fields) {
if(fields) {
infoTiddlerFields[fields.title] = fields;
}
});
}
});
// Bake the info tiddlers into a plugin
var fields = {
title: "$:/temp/info-plugin",
type: "application/json",
"plugin-type": "info",
text: JSON.stringify({tiddlers: infoTiddlerFields},null,$tw.config.preferences.jsonSpaces)
};
$tw.wiki.addTiddler(new $tw.Tiddler(fields));
$tw.wiki.readPluginInfo();
$tw.wiki.registerPluginTiddlers("info");
$tw.wiki.unpackPluginTiddlers();
};
})();
/*\
title: $:/core/modules/startup/load-modules.js
type: application/javascript
module-type: startup
Load core modules
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "load-modules";
exports.synchronous = true;
exports.startup = function() {
// Load modules
$tw.modules.applyMethods("utils",$tw.utils);
if($tw.node) {
$tw.modules.applyMethods("utils-node",$tw.utils);
}
$tw.modules.applyMethods("global",$tw);
$tw.modules.applyMethods("config",$tw.config);
$tw.Tiddler.fieldModules = $tw.modules.getModulesByTypeAsHashmap("tiddlerfield");
$tw.modules.applyMethods("tiddlermethod",$tw.Tiddler.prototype);
$tw.modules.applyMethods("wikimethod",$tw.Wiki.prototype);
$tw.modules.applyMethods("tiddlerdeserializer",$tw.Wiki.tiddlerDeserializerModules);
$tw.macros = $tw.modules.getModulesByTypeAsHashmap("macro");
$tw.wiki.initParsers();
$tw.Commander.initCommands();
};
})();
/*\
title: $:/core/modules/startup/password.js
type: application/javascript
module-type: startup
Password handling
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "password";
exports.platforms = ["browser"];
exports.after = ["startup"];
exports.synchronous = true;
exports.startup = function() {
$tw.rootWidget.addEventListener("tm-set-password",function(event) {
$tw.passwordPrompt.createPrompt({
serviceName: $tw.language.getString("Encryption/PromptSetPassword"),
noUserName: true,
submitText: $tw.language.getString("Encryption/SetPassword"),
canCancel: true,
repeatPassword: true,
callback: function(data) {
if(data) {
$tw.crypto.setPassword(data.password);
}
return true; // Get rid of the password prompt
}
});
});
$tw.rootWidget.addEventListener("tm-clear-password",function(event) {
if($tw.browser) {
if(!confirm($tw.language.getString("Encryption/ConfirmClearPassword"))) {
return;
}
}
$tw.crypto.setPassword(null);
});
// Ensure that $:/isEncrypted is maintained properly
$tw.wiki.addEventListener("change",function(changes) {
if($tw.utils.hop(changes,"$:/isEncrypted")) {
$tw.crypto.updateCryptoStateTiddler();
}
});
};
})();
/*\
title: $:/core/modules/startup/render.js
type: application/javascript
module-type: startup
Title, stylesheet and page rendering
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "render";
exports.platforms = ["browser"];
exports.after = ["story"];
exports.synchronous = true;
// Default story and history lists
var PAGE_TITLE_TITLE = "$:/core/wiki/title";
var PAGE_STYLESHEET_TITLE = "$:/core/ui/PageStylesheet";
var PAGE_TEMPLATE_TITLE = "$:/core/ui/PageTemplate";
// Time (in ms) that we defer refreshing changes to draft tiddlers
var DRAFT_TIDDLER_TIMEOUT_TITLE = "$:/config/Drafts/TypingTimeout";
var DRAFT_TIDDLER_TIMEOUT = 400;
exports.startup = function() {
// Set up the title
$tw.titleWidgetNode = $tw.wiki.makeTranscludeWidget(PAGE_TITLE_TITLE,{document: $tw.fakeDocument, parseAsInline: true});
$tw.titleContainer = $tw.fakeDocument.createElement("div");
$tw.titleWidgetNode.render($tw.titleContainer,null);
document.title = $tw.titleContainer.textContent;
$tw.wiki.addEventListener("change",function(changes) {
if($tw.titleWidgetNode.refresh(changes,$tw.titleContainer,null)) {
document.title = $tw.titleContainer.textContent;
}
});
// Set up the styles
$tw.styleWidgetNode = $tw.wiki.makeTranscludeWidget(PAGE_STYLESHEET_TITLE,{document: $tw.fakeDocument});
$tw.styleContainer = $tw.fakeDocument.createElement("style");
$tw.styleWidgetNode.render($tw.styleContainer,null);
$tw.styleElement = document.createElement("style");
$tw.styleElement.innerHTML = $tw.styleContainer.textContent;
document.head.insertBefore($tw.styleElement,document.head.firstChild);
$tw.wiki.addEventListener("change",$tw.perf.report("styleRefresh",function(changes) {
if($tw.styleWidgetNode.refresh(changes,$tw.styleContainer,null)) {
$tw.styleElement.innerHTML = $tw.styleContainer.textContent;
}
}));
// Display the $:/core/ui/PageTemplate tiddler to kick off the display
$tw.perf.report("mainRender",function() {
$tw.pageWidgetNode = $tw.wiki.makeTranscludeWidget(PAGE_TEMPLATE_TITLE,{document: document, parentWidget: $tw.rootWidget});
$tw.pageContainer = document.createElement("div");
$tw.utils.addClass($tw.pageContainer,"tc-page-container-wrapper");
document.body.insertBefore($tw.pageContainer,document.body.firstChild);
$tw.pageWidgetNode.render($tw.pageContainer,null);
})();
// Prepare refresh mechanism
var deferredChanges = Object.create(null),
timerId;
function refresh() {
// Process the refresh
$tw.pageWidgetNode.refresh(deferredChanges);
deferredChanges = Object.create(null);
}
// Add the change event handler
$tw.wiki.addEventListener("change",$tw.perf.report("mainRefresh",function(changes) {
// Check if only drafts have changed
var onlyDraftsHaveChanged = true;
for(var title in changes) {
var tiddler = $tw.wiki.getTiddler(title);
if(!tiddler || !tiddler.hasField("draft.of")) {
onlyDraftsHaveChanged = false;
}
}
// Defer the change if only drafts have changed
if(timerId) {
clearTimeout(timerId);
}
timerId = null;
if(onlyDraftsHaveChanged) {
var timeout = parseInt($tw.wiki.getTiddlerText(DRAFT_TIDDLER_TIMEOUT_TITLE,""),10);
if(isNaN(timeout)) {
timeout = DRAFT_TIDDLER_TIMEOUT;
}
timerId = setTimeout(refresh,timeout);
$tw.utils.extend(deferredChanges,changes);
} else {
$tw.utils.extend(deferredChanges,changes);
refresh();
}
}));
// Fix up the link between the root widget and the page container
$tw.rootWidget.domNodes = [$tw.pageContainer];
$tw.rootWidget.children = [$tw.pageWidgetNode];
};
})();
/*\
title: $:/core/modules/startup/rootwidget.js
type: application/javascript
module-type: startup
Setup the root widget and the core root widget handlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "rootwidget";
exports.platforms = ["browser"];
exports.after = ["startup"];
exports.before = ["story"];
exports.synchronous = true;
exports.startup = function() {
// Install the modal message mechanism
$tw.modal = new $tw.utils.Modal($tw.wiki);
$tw.rootWidget.addEventListener("tm-modal",function(event) {
$tw.modal.display(event.param,{variables: event.paramObject});
});
// Install the notification mechanism
$tw.notifier = new $tw.utils.Notifier($tw.wiki);
$tw.rootWidget.addEventListener("tm-notify",function(event) {
$tw.notifier.display(event.param);
});
// Install the scroller
$tw.pageScroller = new $tw.utils.PageScroller();
$tw.rootWidget.addEventListener("tm-scroll",function(event) {
$tw.pageScroller.handleEvent(event);
});
var fullscreen = $tw.utils.getFullScreenApis();
if(fullscreen) {
$tw.rootWidget.addEventListener("tm-full-screen",function(event) {
if(document[fullscreen._fullscreenElement]) {
document[fullscreen._exitFullscreen]();
} else {
document.documentElement[fullscreen._requestFullscreen](Element.ALLOW_KEYBOARD_INPUT);
}
});
}
// If we're being viewed on a data: URI then give instructions for how to save
if(document.location.protocol === "data:") {
$tw.rootWidget.dispatchEvent({
type: "tm-modal",
param: "$:/language/Modals/SaveInstructions"
});
}
};
})();
/*\
title: $:/core/modules/startup/story.js
type: application/javascript
module-type: startup
Load core modules
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "story";
exports.after = ["startup"];
exports.synchronous = true;
// Default story and history lists
var DEFAULT_STORY_TITLE = "$:/StoryList";
var DEFAULT_HISTORY_TITLE = "$:/HistoryList";
// Default tiddlers
var DEFAULT_TIDDLERS_TITLE = "$:/DefaultTiddlers";
// Config
var CONFIG_UPDATE_ADDRESS_BAR = "$:/config/Navigation/UpdateAddressBar"; // Can be "no", "permalink", "permaview"
var CONFIG_UPDATE_HISTORY = "$:/config/Navigation/UpdateHistory"; // Can be "yes" or "no"
exports.startup = function() {
// Open startup tiddlers
openStartupTiddlers();
if($tw.browser) {
// Set up location hash update
$tw.wiki.addEventListener("change",function(changes) {
if($tw.utils.hop(changes,DEFAULT_STORY_TITLE) || $tw.utils.hop(changes,DEFAULT_HISTORY_TITLE)) {
updateLocationHash({
updateAddressBar: $tw.wiki.getTiddlerText(CONFIG_UPDATE_ADDRESS_BAR,"permaview").trim(),
updateHistory: $tw.wiki.getTiddlerText(CONFIG_UPDATE_HISTORY,"no").trim()
});
}
});
// Listen for changes to the browser location hash
window.addEventListener("hashchange",function() {
var hash = $tw.utils.getLocationHash();
if(hash !== $tw.locationHash) {
$tw.locationHash = hash;
openStartupTiddlers({defaultToCurrentStory: true});
}
},false);
// Listen for the tm-browser-refresh message
$tw.rootWidget.addEventListener("tm-browser-refresh",function(event) {
window.location.reload(true);
});
// Listen for the tm-home message
$tw.rootWidget.addEventListener("tm-home",function(event) {
window.location.hash = "";
var storyFilter = $tw.wiki.getTiddlerText(DEFAULT_TIDDLERS_TITLE),
storyList = $tw.wiki.filterTiddlers(storyFilter);
//invoke any hooks that might change the default story list
storyList = $tw.hooks.invokeHook("th-opening-default-tiddlers-list",storyList);
$tw.wiki.addTiddler({title: DEFAULT_STORY_TITLE, text: "", list: storyList},$tw.wiki.getModificationFields());
if(storyList[0]) {
$tw.wiki.addToHistory(storyList[0]);
}
});
// Listen for the tm-permalink message
$tw.rootWidget.addEventListener("tm-permalink",function(event) {
updateLocationHash({
updateAddressBar: "permalink",
updateHistory: $tw.wiki.getTiddlerText(CONFIG_UPDATE_HISTORY,"no").trim(),
targetTiddler: event.param || event.tiddlerTitle
});
});
// Listen for the tm-permaview message
$tw.rootWidget.addEventListener("tm-permaview",function(event) {
updateLocationHash({
updateAddressBar: "permaview",
updateHistory: $tw.wiki.getTiddlerText(CONFIG_UPDATE_HISTORY,"no").trim(),
targetTiddler: event.param || event.tiddlerTitle
});
});
}
};
/*
Process the location hash to open the specified tiddlers. Options:
defaultToCurrentStory: If true, the current story is retained as the default, instead of opening the default tiddlers
*/
function openStartupTiddlers(options) {
options = options || {};
// Work out the target tiddler and the story filter. "null" means "unspecified"
var target = null,
storyFilter = null;
if($tw.locationHash.length > 1) {
var hash = $tw.locationHash.substr(1),
split = hash.indexOf(":");
if(split === -1) {
target = decodeURIComponent(hash.trim());
} else {
target = decodeURIComponent(hash.substr(0,split).trim());
storyFilter = decodeURIComponent(hash.substr(split + 1).trim());
}
}
// If the story wasn't specified use the current tiddlers or a blank story
if(storyFilter === null) {
if(options.defaultToCurrentStory) {
var currStoryList = $tw.wiki.getTiddlerList(DEFAULT_STORY_TITLE);
storyFilter = $tw.utils.stringifyList(currStoryList);
} else {
if(target && target !== "") {
storyFilter = "";
} else {
storyFilter = $tw.wiki.getTiddlerText(DEFAULT_TIDDLERS_TITLE);
}
}
}
// Process the story filter to get the story list
var storyList = $tw.wiki.filterTiddlers(storyFilter);
// Invoke any hooks that want to change the default story list
storyList = $tw.hooks.invokeHook("th-opening-default-tiddlers-list",storyList);
// If the target tiddler isn't included then splice it in at the top
if(target && storyList.indexOf(target) === -1) {
storyList.unshift(target);
}
// Save the story list
$tw.wiki.addTiddler({title: DEFAULT_STORY_TITLE, text: "", list: storyList},$tw.wiki.getModificationFields());
// If a target tiddler was specified add it to the history stack
if(target && target !== "") {
// The target tiddler doesn't need double square brackets, but we'll silently remove them if they're present
if(target.indexOf("[[") === 0 && target.substr(-2) === "]]") {
target = target.substr(2,target.length - 4);
}
$tw.wiki.addToHistory(target);
} else if(storyList.length > 0) {
$tw.wiki.addToHistory(storyList[0]);
}
}
/*
options: See below
options.updateAddressBar: "permalink", "permaview" or "no" (defaults to "permaview")
options.updateHistory: "yes" or "no" (defaults to "no")
options.targetTiddler: optional title of target tiddler for permalink
*/
function updateLocationHash(options) {
if(options.updateAddressBar !== "no") {
// Get the story and the history stack
var storyList = $tw.wiki.getTiddlerList(DEFAULT_STORY_TITLE),
historyList = $tw.wiki.getTiddlerData(DEFAULT_HISTORY_TITLE,[]),
targetTiddler = "";
if(options.targetTiddler) {
targetTiddler = options.targetTiddler;
} else {
// The target tiddler is the one at the top of the stack
if(historyList.length > 0) {
targetTiddler = historyList[historyList.length-1].title;
}
// Blank the target tiddler if it isn't present in the story
if(storyList.indexOf(targetTiddler) === -1) {
targetTiddler = "";
}
}
// Assemble the location hash
if(options.updateAddressBar === "permalink") {
$tw.locationHash = "#" + encodeURIComponent(targetTiddler);
} else {
$tw.locationHash = "#" + encodeURIComponent(targetTiddler) + ":" + encodeURIComponent($tw.utils.stringifyList(storyList));
}
// Only change the location hash if we must, thus avoiding unnecessary onhashchange events
if($tw.utils.getLocationHash() !== $tw.locationHash) {
if(options.updateHistory === "yes") {
// Assign the location hash so that history is updated
window.location.hash = $tw.locationHash;
} else {
// We use replace so that browser history isn't affected
window.location.replace(window.location.toString().split("#")[0] + $tw.locationHash);
}
}
}
}
})();
/*\
title: $:/core/modules/startup/windows.js
type: application/javascript
module-type: startup
Setup root widget handlers for the messages concerned with opening external browser windows
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "windows";
exports.platforms = ["browser"];
exports.after = ["startup"];
exports.synchronous = true;
// Global to keep track of open windows (hashmap by title)
var windows = {};
exports.startup = function() {
// Handle open window message
$tw.rootWidget.addEventListener("tm-open-window",function(event) {
// Get the parameters
var refreshHandler,
title = event.param || event.tiddlerTitle,
paramObject = event.paramObject || {},
template = paramObject.template || "$:/core/templates/single.tiddler.window",
width = paramObject.width || "700",
height = paramObject.height || "600",
variables = $tw.utils.extend({},paramObject,{currentTiddler: title});
// Open the window
var srcWindow = window.open("","external-" + title,"scrollbars,width=" + width + ",height=" + height),
srcDocument = srcWindow.document;
windows[title] = srcWindow;
// Check for reopening the same window
if(srcWindow.haveInitialisedWindow) {
return;
}
// Initialise the document
srcDocument.write("<html><head></head><body class='tc-body tc-single-tiddler-window'></body></html>");
srcDocument.close();
srcDocument.title = title;
srcWindow.addEventListener("beforeunload",function(event) {
delete windows[title];
$tw.wiki.removeEventListener("change",refreshHandler);
},false);
// Set up the styles
var styleWidgetNode = $tw.wiki.makeTranscludeWidget("$:/core/ui/PageStylesheet",{document: $tw.fakeDocument, variables: variables}),
styleContainer = $tw.fakeDocument.createElement("style");
styleWidgetNode.render(styleContainer,null);
var styleElement = srcDocument.createElement("style");
styleElement.innerHTML = styleContainer.textContent;
srcDocument.head.insertBefore(styleElement,srcDocument.head.firstChild);
// Render the text of the tiddler
var parser = $tw.wiki.parseTiddler(template),
widgetNode = $tw.wiki.makeWidget(parser,{document: srcDocument, parentWidget: $tw.rootWidget, variables: variables});
widgetNode.render(srcDocument.body,srcDocument.body.firstChild);
// Function to handle refreshes
refreshHandler = function(changes) {
if(styleWidgetNode.refresh(changes,styleContainer,null)) {
styleElement.innerHTML = styleContainer.textContent;
}
widgetNode.refresh(changes);
};
$tw.wiki.addEventListener("change",refreshHandler);
srcWindow.haveInitialisedWindow = true;
});
// Close open windows when unloading main window
$tw.addUnloadTask(function() {
$tw.utils.each(windows,function(win) {
win.close();
});
});
};
})();
/*\
title: $:/core/modules/story.js
type: application/javascript
module-type: global
Lightweight object for managing interactions with the story and history lists.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Construct Story object with options:
wiki: reference to wiki object to use to resolve tiddler titles
storyTitle: title of story list tiddler
historyTitle: title of history list tiddler
*/
function Story(options) {
options = options || {};
this.wiki = options.wiki || $tw.wiki;
this.storyTitle = options.storyTitle || "$:/StoryList";
this.historyTitle = options.historyTitle || "$:/HistoryList";
};
Story.prototype.navigateTiddler = function(navigateTo,navigateFromTitle,navigateFromClientRect) {
this.addToStory(navigateTo,navigateFromTitle);
this.addToHistory(navigateTo,navigateFromClientRect);
};
Story.prototype.getStoryList = function() {
return this.wiki.getTiddlerList(this.storyTitle) || [];
};
Story.prototype.addToStory = function(navigateTo,navigateFromTitle,options) {
options = options || {};
var storyList = this.getStoryList();
// See if the tiddler is already there
var slot = storyList.indexOf(navigateTo);
// Quit if it already exists in the story river
if(slot >= 0) {
return;
}
// First we try to find the position of the story element we navigated from
var fromIndex = storyList.indexOf(navigateFromTitle);
if(fromIndex >= 0) {
// The tiddler is added from inside the river
// Determine where to insert the tiddler; Fallback is "below"
switch(options.openLinkFromInsideRiver) {
case "top":
slot = 0;
break;
case "bottom":
slot = storyList.length;
break;
case "above":
slot = fromIndex;
break;
case "below": // Intentional fall-through
default:
slot = fromIndex + 1;
break;
}
} else {
// The tiddler is opened from outside the river. Determine where to insert the tiddler; default is "top"
if(options.openLinkFromOutsideRiver === "bottom") {
// Insert at bottom
slot = storyList.length;
} else {
// Insert at top
slot = 0;
}
}
// Add the tiddler
storyList.splice(slot,0,navigateTo);
// Save the story
this.saveStoryList(storyList);
};
Story.prototype.saveStoryList = function(storyList) {
var storyTiddler = this.wiki.getTiddler(this.storyTitle);
this.wiki.addTiddler(new $tw.Tiddler(
this.wiki.getCreationFields(),
{title: this.storyTitle},
storyTiddler,
{list: storyList},
this.wiki.getModificationFields()
));
};
Story.prototype.addToHistory = function(navigateTo,navigateFromClientRect) {
var titles = $tw.utils.isArray(navigateTo) ? navigateTo : [navigateTo];
// Add a new record to the top of the history stack
var historyList = this.wiki.getTiddlerData(this.historyTitle,[]);
$tw.utils.each(titles,function(title) {
historyList.push({title: title, fromPageRect: navigateFromClientRect});
});
this.wiki.setTiddlerData(this.historyTitle,historyList,{"current-tiddler": titles[titles.length-1]});
};
Story.prototype.storyCloseTiddler = function(targetTitle) {
// TBD
};
Story.prototype.storyCloseAllTiddlers = function() {
// TBD
};
Story.prototype.storyCloseOtherTiddlers = function(targetTitle) {
// TBD
};
Story.prototype.storyEditTiddler = function(targetTitle) {
// TBD
};
Story.prototype.storyDeleteTiddler = function(targetTitle) {
// TBD
};
Story.prototype.storySaveTiddler = function(targetTitle) {
// TBD
};
Story.prototype.storyCancelTiddler = function(targetTitle) {
// TBD
};
Story.prototype.storyNewTiddler = function(targetTitle) {
// TBD
};
exports.Story = Story;
})();
/*\
title: $:/core/modules/storyviews/classic.js
type: application/javascript
module-type: storyview
Views the story as a linear sequence
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var easing = "cubic-bezier(0.645, 0.045, 0.355, 1)"; // From http://easings.net/#easeInOutCubic
var ClassicStoryView = function(listWidget) {
this.listWidget = listWidget;
};
ClassicStoryView.prototype.navigateTo = function(historyInfo) {
var listElementIndex = this.listWidget.findListItem(0,historyInfo.title);
if(listElementIndex === undefined) {
return;
}
var listItemWidget = this.listWidget.children[listElementIndex],
targetElement = listItemWidget.findFirstDomNode();
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(targetElement instanceof Element)) {
return;
}
// Scroll the node into view
this.listWidget.dispatchEvent({type: "tm-scroll", target: targetElement});
};
ClassicStoryView.prototype.insert = function(widget) {
var targetElement = widget.findFirstDomNode(),
duration = $tw.utils.getAnimationDuration();
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(targetElement instanceof Element)) {
return;
}
// Get the current height of the tiddler
var computedStyle = window.getComputedStyle(targetElement),
currMarginBottom = parseInt(computedStyle.marginBottom,10),
currMarginTop = parseInt(computedStyle.marginTop,10),
currHeight = targetElement.offsetHeight + currMarginTop;
// Reset the margin once the transition is over
setTimeout(function() {
$tw.utils.setStyle(targetElement,[
{transition: "none"},
{marginBottom: ""}
]);
},duration);
// Set up the initial position of the element
$tw.utils.setStyle(targetElement,[
{transition: "none"},
{marginBottom: (-currHeight) + "px"},
{opacity: "0.0"}
]);
$tw.utils.forceLayout(targetElement);
// Transition to the final position
$tw.utils.setStyle(targetElement,[
{transition: "opacity " + duration + "ms " + easing + ", " +
"margin-bottom " + duration + "ms " + easing},
{marginBottom: currMarginBottom + "px"},
{opacity: "1.0"}
]);
};
ClassicStoryView.prototype.remove = function(widget) {
var targetElement = widget.findFirstDomNode(),
duration = $tw.utils.getAnimationDuration(),
removeElement = function() {
widget.removeChildDomNodes();
};
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(targetElement instanceof Element)) {
removeElement();
return;
}
// Get the current height of the tiddler
var currWidth = targetElement.offsetWidth,
computedStyle = window.getComputedStyle(targetElement),
currMarginBottom = parseInt(computedStyle.marginBottom,10),
currMarginTop = parseInt(computedStyle.marginTop,10),
currHeight = targetElement.offsetHeight + currMarginTop;
// Remove the dom nodes of the widget at the end of the transition
setTimeout(removeElement,duration);
// Animate the closure
$tw.utils.setStyle(targetElement,[
{transition: "none"},
{transform: "translateX(0px)"},
{marginBottom: currMarginBottom + "px"},
{opacity: "1.0"}
]);
$tw.utils.forceLayout(targetElement);
$tw.utils.setStyle(targetElement,[
{transition: $tw.utils.roundTripPropertyName("transform") + " " + duration + "ms " + easing + ", " +
"opacity " + duration + "ms " + easing + ", " +
"margin-bottom " + duration + "ms " + easing},
{transform: "translateX(-" + currWidth + "px)"},
{marginBottom: (-currHeight) + "px"},
{opacity: "0.0"}
]);
};
exports.classic = ClassicStoryView;
})();
/*\
title: $:/core/modules/storyviews/pop.js
type: application/javascript
module-type: storyview
Animates list insertions and removals
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var PopStoryView = function(listWidget) {
this.listWidget = listWidget;
};
PopStoryView.prototype.navigateTo = function(historyInfo) {
var listElementIndex = this.listWidget.findListItem(0,historyInfo.title);
if(listElementIndex === undefined) {
return;
}
var listItemWidget = this.listWidget.children[listElementIndex],
targetElement = listItemWidget.findFirstDomNode();
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(targetElement instanceof Element)) {
return;
}
// Scroll the node into view
this.listWidget.dispatchEvent({type: "tm-scroll", target: targetElement});
};
PopStoryView.prototype.insert = function(widget) {
var targetElement = widget.findFirstDomNode(),
duration = $tw.utils.getAnimationDuration();
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(targetElement instanceof Element)) {
return;
}
// Reset once the transition is over
setTimeout(function() {
$tw.utils.setStyle(targetElement,[
{transition: "none"},
{transform: "none"}
]);
},duration);
// Set up the initial position of the element
$tw.utils.setStyle(targetElement,[
{transition: "none"},
{transform: "scale(2)"},
{opacity: "0.0"}
]);
$tw.utils.forceLayout(targetElement);
// Transition to the final position
$tw.utils.setStyle(targetElement,[
{transition: $tw.utils.roundTripPropertyName("transform") + " " + duration + "ms ease-in-out, " +
"opacity " + duration + "ms ease-in-out"},
{transform: "scale(1)"},
{opacity: "1.0"}
]);
};
PopStoryView.prototype.remove = function(widget) {
var targetElement = widget.findFirstDomNode(),
duration = $tw.utils.getAnimationDuration(),
removeElement = function() {
if(targetElement.parentNode) {
widget.removeChildDomNodes();
}
};
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(targetElement instanceof Element)) {
removeElement();
return;
}
// Remove the element at the end of the transition
setTimeout(removeElement,duration);
// Animate the closure
$tw.utils.setStyle(targetElement,[
{transition: "none"},
{transform: "scale(1)"},
{opacity: "1.0"}
]);
$tw.utils.forceLayout(targetElement);
$tw.utils.setStyle(targetElement,[
{transition: $tw.utils.roundTripPropertyName("transform") + " " + duration + "ms ease-in-out, " +
"opacity " + duration + "ms ease-in-out"},
{transform: "scale(0.1)"},
{opacity: "0.0"}
]);
};
exports.pop = PopStoryView;
})();
/*\
title: $:/core/modules/storyviews/zoomin.js
type: application/javascript
module-type: storyview
Zooms between individual tiddlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var easing = "cubic-bezier(0.645, 0.045, 0.355, 1)"; // From http://easings.net/#easeInOutCubic
var ZoominListView = function(listWidget) {
var self = this;
this.listWidget = listWidget;
// Get the index of the tiddler that is at the top of the history
var history = this.listWidget.wiki.getTiddlerDataCached(this.listWidget.historyTitle,[]),
targetTiddler;
if(history.length > 0) {
targetTiddler = history[history.length-1].title;
}
// Make all the tiddlers position absolute, and hide all but the top (or first) one
$tw.utils.each(this.listWidget.children,function(itemWidget,index) {
var domNode = itemWidget.findFirstDomNode();
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(domNode instanceof Element)) {
return;
}
if((targetTiddler && targetTiddler !== itemWidget.parseTreeNode.itemTitle) || (!targetTiddler && index)) {
domNode.style.display = "none";
} else {
self.currentTiddlerDomNode = domNode;
}
$tw.utils.addClass(domNode,"tc-storyview-zoomin-tiddler");
});
};
ZoominListView.prototype.navigateTo = function(historyInfo) {
var duration = $tw.utils.getAnimationDuration(),
listElementIndex = this.listWidget.findListItem(0,historyInfo.title);
if(listElementIndex === undefined) {
return;
}
var listItemWidget = this.listWidget.children[listElementIndex],
targetElement = listItemWidget.findFirstDomNode();
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(targetElement instanceof Element)) {
return;
}
// Make the new tiddler be position absolute and visible so that we can measure it
$tw.utils.addClass(targetElement,"tc-storyview-zoomin-tiddler");
$tw.utils.setStyle(targetElement,[
{display: "block"},
{transformOrigin: "0 0"},
{transform: "translateX(0px) translateY(0px) scale(1)"},
{transition: "none"},
{opacity: "0.0"}
]);
// Get the position of the source node, or use the centre of the window as the source position
var sourceBounds = historyInfo.fromPageRect || {
left: window.innerWidth/2 - 2,
top: window.innerHeight/2 - 2,
width: window.innerWidth/8,
height: window.innerHeight/8
};
// Try to find the title node in the target tiddler
var titleDomNode = findTitleDomNode(listItemWidget) || listItemWidget.findFirstDomNode(),
zoomBounds = titleDomNode.getBoundingClientRect();
// Compute the transform for the target tiddler to make the title lie over the source rectange
var targetBounds = targetElement.getBoundingClientRect(),
scale = sourceBounds.width / zoomBounds.width,
x = sourceBounds.left - targetBounds.left - (zoomBounds.left - targetBounds.left) * scale,
y = sourceBounds.top - targetBounds.top - (zoomBounds.top - targetBounds.top) * scale;
// Transform the target tiddler to its starting position
$tw.utils.setStyle(targetElement,[
{transform: "translateX(" + x + "px) translateY(" + y + "px) scale(" + scale + ")"}
]);
// Force layout
$tw.utils.forceLayout(targetElement);
// Apply the ending transitions with a timeout to ensure that the previously applied transformations are applied first
var self = this,
prevCurrentTiddler = this.currentTiddlerDomNode;
this.currentTiddlerDomNode = targetElement;
// Transform the target tiddler to its natural size
$tw.utils.setStyle(targetElement,[
{transition: $tw.utils.roundTripPropertyName("transform") + " " + duration + "ms " + easing + ", opacity " + duration + "ms " + easing},
{opacity: "1.0"},
{transform: "translateX(0px) translateY(0px) scale(1)"},
{zIndex: "500"},
]);
// Transform the previous tiddler out of the way and then hide it
if(prevCurrentTiddler && prevCurrentTiddler !== targetElement) {
scale = zoomBounds.width / sourceBounds.width;
x = zoomBounds.left - targetBounds.left - (sourceBounds.left - targetBounds.left) * scale;
y = zoomBounds.top - targetBounds.top - (sourceBounds.top - targetBounds.top) * scale;
$tw.utils.setStyle(prevCurrentTiddler,[
{transition: $tw.utils.roundTripPropertyName("transform") + " " + duration + "ms " + easing + ", opacity " + duration + "ms " + easing},
{opacity: "0.0"},
{transformOrigin: "0 0"},
{transform: "translateX(" + x + "px) translateY(" + y + "px) scale(" + scale + ")"},
{zIndex: "0"}
]);
// Hide the tiddler when the transition has finished
setTimeout(function() {
if(self.currentTiddlerDomNode !== prevCurrentTiddler) {
prevCurrentTiddler.style.display = "none";
}
},duration);
}
// Scroll the target into view
// $tw.pageScroller.scrollIntoView(targetElement);
};
/*
Find the first child DOM node of a widget that has the class "tc-title"
*/
function findTitleDomNode(widget,targetClass) {
targetClass = targetClass || "tc-title";
var domNode = widget.findFirstDomNode();
if(domNode && domNode.querySelector) {
return domNode.querySelector("." + targetClass);
}
return null;
}
ZoominListView.prototype.insert = function(widget) {
var targetElement = widget.findFirstDomNode();
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(targetElement instanceof Element)) {
return;
}
// Make the newly inserted node position absolute and hidden
$tw.utils.addClass(targetElement,"tc-storyview-zoomin-tiddler");
$tw.utils.setStyle(targetElement,[
{display: "none"}
]);
};
ZoominListView.prototype.remove = function(widget) {
var targetElement = widget.findFirstDomNode(),
duration = $tw.utils.getAnimationDuration(),
removeElement = function() {
widget.removeChildDomNodes();
};
// Abandon if the list entry isn't a DOM element (it might be a text node)
if(!(targetElement instanceof Element)) {
removeElement();
return;
}
// Abandon if hidden
if(targetElement.style.display != "block" ) {
removeElement();
return;
}
// Set up the tiddler that is being closed
$tw.utils.addClass(targetElement,"tc-storyview-zoomin-tiddler");
$tw.utils.setStyle(targetElement,[
{display: "block"},
{transformOrigin: "50% 50%"},
{transform: "translateX(0px) translateY(0px) scale(1)"},
{transition: "none"},
{zIndex: "0"}
]);
// We'll move back to the previous or next element in the story
var toWidget = widget.previousSibling();
if(!toWidget) {
toWidget = widget.nextSibling();
}
var toWidgetDomNode = toWidget && toWidget.findFirstDomNode();
// Set up the tiddler we're moving back in
if(toWidgetDomNode) {
$tw.utils.addClass(toWidgetDomNode,"tc-storyview-zoomin-tiddler");
$tw.utils.setStyle(toWidgetDomNode,[
{display: "block"},
{transformOrigin: "50% 50%"},
{transform: "translateX(0px) translateY(0px) scale(10)"},
{transition: $tw.utils.roundTripPropertyName("transform") + " " + duration + "ms " + easing + ", opacity " + duration + "ms " + easing},
{opacity: "0"},
{zIndex: "500"}
]);
this.currentTiddlerDomNode = toWidgetDomNode;
}
// Animate them both
// Force layout
$tw.utils.forceLayout(this.listWidget.parentDomNode);
// First, the tiddler we're closing
$tw.utils.setStyle(targetElement,[
{transformOrigin: "50% 50%"},
{transform: "translateX(0px) translateY(0px) scale(0.1)"},
{transition: $tw.utils.roundTripPropertyName("transform") + " " + duration + "ms " + easing + ", opacity " + duration + "ms " + easing},
{opacity: "0"},
{zIndex: "0"}
]);
setTimeout(removeElement,duration);
// Now the tiddler we're going back to
if(toWidgetDomNode) {
$tw.utils.setStyle(toWidgetDomNode,[
{transform: "translateX(0px) translateY(0px) scale(1)"},
{opacity: "1"}
]);
}
return true; // Indicate that we'll delete the DOM node
};
exports.zoomin = ZoominListView;
})();
/*\
title: $:/core/modules/syncer.js
type: application/javascript
module-type: global
The syncer tracks changes to the store. If a syncadaptor is used then individual tiddlers are synchronised through it. If there is no syncadaptor then the entire wiki is saved via saver modules.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Instantiate the syncer with the following options:
syncadaptor: reference to syncadaptor to be used
wiki: wiki to be synced
*/
function Syncer(options) {
var self = this;
this.wiki = options.wiki;
this.syncadaptor = options.syncadaptor;
// Make a logger
this.logger = new $tw.utils.Logger("syncer" + ($tw.browser ? "-browser" : "") + ($tw.node ? "-server" : ""));
// Compile the dirty tiddler filter
this.filterFn = this.wiki.compileFilter(this.wiki.getTiddlerText(this.titleSyncFilter));
// Record information for known tiddlers
this.readTiddlerInfo();
// Tasks are {type: "load"/"save"/"delete", title:, queueTime:, lastModificationTime:}
this.taskQueue = {}; // Hashmap of tasks yet to be performed
this.taskInProgress = {}; // Hash of tasks in progress
this.taskTimerId = null; // Timer for task dispatch
this.pollTimerId = null; // Timer for polling server
// Listen out for changes to tiddlers
this.wiki.addEventListener("change",function(changes) {
self.syncToServer(changes);
});
// Browser event handlers
if($tw.browser) {
// Set up our beforeunload handler
$tw.addUnloadTask(function(event) {
var confirmationMessage;
if(self.isDirty()) {
confirmationMessage = $tw.language.getString("UnsavedChangesWarning");
event.returnValue = confirmationMessage; // Gecko
}
return confirmationMessage;
});
// Listen out for login/logout/refresh events in the browser
$tw.rootWidget.addEventListener("tm-login",function() {
self.handleLoginEvent();
});
$tw.rootWidget.addEventListener("tm-logout",function() {
self.handleLogoutEvent();
});
$tw.rootWidget.addEventListener("tm-server-refresh",function() {
self.handleRefreshEvent();
});
}
// Listen out for lazyLoad events
this.wiki.addEventListener("lazyLoad",function(title) {
self.handleLazyLoadEvent(title);
});
// Get the login status
this.getStatus(function(err,isLoggedIn) {
// Do a sync from the server
self.syncFromServer();
});
}
/*
Constants
*/
Syncer.prototype.titleIsLoggedIn = "$:/status/IsLoggedIn";
Syncer.prototype.titleUserName = "$:/status/UserName";
Syncer.prototype.titleSyncFilter = "$:/config/SyncFilter";
Syncer.prototype.titleSavedNotification = "$:/language/Notifications/Save/Done";
Syncer.prototype.taskTimerInterval = 1 * 1000; // Interval for sync timer
Syncer.prototype.throttleInterval = 1 * 1000; // Defer saving tiddlers if they've changed in the last 1s...
Syncer.prototype.fallbackInterval = 10 * 1000; // Unless the task is older than 10s
Syncer.prototype.pollTimerInterval = 60 * 1000; // Interval for polling for changes from the adaptor
/*
Read (or re-read) the latest tiddler info from the store
*/
Syncer.prototype.readTiddlerInfo = function() {
// Hashmap by title of {revision:,changeCount:,adaptorInfo:}
this.tiddlerInfo = {};
// Record information for known tiddlers
var self = this,
tiddlers = this.filterFn.call(this.wiki);
$tw.utils.each(tiddlers,function(title) {
var tiddler = self.wiki.getTiddler(title);
self.tiddlerInfo[title] = {
revision: tiddler.fields.revision,
adaptorInfo: self.syncadaptor && self.syncadaptor.getTiddlerInfo(tiddler),
changeCount: self.wiki.getChangeCount(title)
};
});
};
/*
Checks whether the wiki is dirty (ie the window shouldn't be closed)
*/
Syncer.prototype.isDirty = function() {
return (this.numTasksInQueue() > 0) || (this.numTasksInProgress() > 0);
};
/*
Update the document body with the class "tc-dirty" if the wiki has unsaved/unsynced changes
*/
Syncer.prototype.updateDirtyStatus = function() {
if($tw.browser) {
$tw.utils.toggleClass(document.body,"tc-dirty",this.isDirty());
}
};
/*
Save an incoming tiddler in the store, and updates the associated tiddlerInfo
*/
Syncer.prototype.storeTiddler = function(tiddlerFields) {
// Save the tiddler
var tiddler = new $tw.Tiddler(this.wiki.getTiddler(tiddlerFields.title),tiddlerFields);
this.wiki.addTiddler(tiddler);
// Save the tiddler revision and changeCount details
this.tiddlerInfo[tiddlerFields.title] = {
revision: tiddlerFields.revision,
adaptorInfo: this.syncadaptor.getTiddlerInfo(tiddler),
changeCount: this.wiki.getChangeCount(tiddlerFields.title)
};
};
Syncer.prototype.getStatus = function(callback) {
var self = this;
// Check if the adaptor supports getStatus()
if(this.syncadaptor && this.syncadaptor.getStatus) {
// Mark us as not logged in
this.wiki.addTiddler({title: this.titleIsLoggedIn,text: "no"});
// Get login status
this.syncadaptor.getStatus(function(err,isLoggedIn,username) {
if(err) {
self.logger.alert(err);
return;
}
// Set the various status tiddlers
self.wiki.addTiddler({title: self.titleIsLoggedIn,text: isLoggedIn ? "yes" : "no"});
if(isLoggedIn) {
self.wiki.addTiddler({title: self.titleUserName,text: username || ""});
} else {
self.wiki.deleteTiddler(self.titleUserName);
}
// Invoke the callback
if(callback) {
callback(err,isLoggedIn,username);
}
});
} else {
callback(null,true,"UNAUTHENTICATED");
}
};
/*
Synchronise from the server by reading the skinny tiddler list and queuing up loads for any tiddlers that we don't already have up to date
*/
Syncer.prototype.syncFromServer = function() {
if(this.syncadaptor && this.syncadaptor.getSkinnyTiddlers) {
this.logger.log("Retrieving skinny tiddler list");
var self = this;
if(this.pollTimerId) {
clearTimeout(this.pollTimerId);
this.pollTimerId = null;
}
this.syncadaptor.getSkinnyTiddlers(function(err,tiddlers) {
// Trigger the next sync
self.pollTimerId = setTimeout(function() {
self.pollTimerId = null;
self.syncFromServer.call(self);
},self.pollTimerInterval);
// Check for errors
if(err) {
self.logger.alert("Error retrieving skinny tiddler list:",err);
return;
}
// Process each incoming tiddler
for(var t=0; t<tiddlers.length; t++) {
// Get the incoming tiddler fields, and the existing tiddler
var tiddlerFields = tiddlers[t],
incomingRevision = tiddlerFields.revision + "",
tiddler = self.wiki.getTiddler(tiddlerFields.title),
tiddlerInfo = self.tiddlerInfo[tiddlerFields.title],
currRevision = tiddlerInfo ? tiddlerInfo.revision : null;
// Ignore the incoming tiddler if it's the same as the revision we've already got
if(currRevision !== incomingRevision) {
// Do a full load if we've already got a fat version of the tiddler
if(tiddler && tiddler.fields.text !== undefined) {
// Do a full load of this tiddler
self.enqueueSyncTask({
type: "load",
title: tiddlerFields.title
});
} else {
// Load the skinny version of the tiddler
self.storeTiddler(tiddlerFields);
}
}
}
});
}
};
/*
Synchronise a set of changes to the server
*/
Syncer.prototype.syncToServer = function(changes) {
var self = this,
now = Date.now(),
filteredChanges = this.filterFn.call(this.wiki,function(callback) {
$tw.utils.each(changes,function(change,title) {
var tiddler = self.wiki.getTiddler(title);
callback(tiddler,title);
});
});
$tw.utils.each(changes,function(change,title,object) {
// Process the change if it is a deletion of a tiddler we're already syncing, or is on the filtered change list
if((change.deleted && $tw.utils.hop(self.tiddlerInfo,title)) || filteredChanges.indexOf(title) !== -1) {
// Queue a task to sync this tiddler
self.enqueueSyncTask({
type: change.deleted ? "delete" : "save",
title: title
});
}
});
};
/*
Lazily load a skinny tiddler if we can
*/
Syncer.prototype.handleLazyLoadEvent = function(title) {
// Queue up a sync task to load this tiddler
this.enqueueSyncTask({
type: "load",
title: title
});
};
/*
Dispay a password prompt and allow the user to login
*/
Syncer.prototype.handleLoginEvent = function() {
var self = this;
this.getStatus(function(err,isLoggedIn,username) {
if(!isLoggedIn) {
$tw.passwordPrompt.createPrompt({
serviceName: "Login to TiddlySpace",
callback: function(data) {
self.login(data.username,data.password,function(err,isLoggedIn) {
self.syncFromServer();
});
return true; // Get rid of the password prompt
}
});
}
});
};
/*
Attempt to login to TiddlyWeb.
username: username
password: password
callback: invoked with arguments (err,isLoggedIn)
*/
Syncer.prototype.login = function(username,password,callback) {
this.logger.log("Attempting to login as",username);
var self = this;
if(this.syncadaptor.login) {
this.syncadaptor.login(username,password,function(err) {
if(err) {
return callback(err);
}
self.getStatus(function(err,isLoggedIn,username) {
if(callback) {
callback(null,isLoggedIn);
}
});
});
} else {
callback(null,true);
}
};
/*
Attempt to log out of TiddlyWeb
*/
Syncer.prototype.handleLogoutEvent = function() {
this.logger.log("Attempting to logout");
var self = this;
if(this.syncadaptor.logout) {
this.syncadaptor.logout(function(err) {
if(err) {
self.logger.alert(err);
} else {
self.getStatus();
}
});
}
};
/*
Immediately refresh from the server
*/
Syncer.prototype.handleRefreshEvent = function() {
this.syncFromServer();
};
/*
Queue up a sync task. If there is already a pending task for the tiddler, just update the last modification time
*/
Syncer.prototype.enqueueSyncTask = function(task) {
var self = this,
now = Date.now();
// Set the timestamps on this task
task.queueTime = now;
task.lastModificationTime = now;
// Fill in some tiddlerInfo if the tiddler is one we haven't seen before
if(!$tw.utils.hop(this.tiddlerInfo,task.title)) {
this.tiddlerInfo[task.title] = {
revision: null,
adaptorInfo: {},
changeCount: -1
};
}
// Bail if this is a save and the tiddler is already at the changeCount that the server has
if(task.type === "save" && this.wiki.getChangeCount(task.title) <= this.tiddlerInfo[task.title].changeCount) {
return;
}
// Check if this tiddler is already in the queue
if($tw.utils.hop(this.taskQueue,task.title)) {
// this.logger.log("Re-queueing up sync task with type:",task.type,"title:",task.title);
var existingTask = this.taskQueue[task.title];
// If so, just update the last modification time
existingTask.lastModificationTime = task.lastModificationTime;
// If the new task is a save then we upgrade the existing task to a save. Thus a pending load is turned into a save if the tiddler changes locally in the meantime. But a pending save is not modified to become a load
if(task.type === "save" || task.type === "delete") {
existingTask.type = task.type;
}
} else {
// this.logger.log("Queuing up sync task with type:",task.type,"title:",task.title);
// If it is not in the queue, insert it
this.taskQueue[task.title] = task;
this.updateDirtyStatus();
}
// Process the queue
$tw.utils.nextTick(function() {self.processTaskQueue.call(self);});
};
/*
Return the number of tasks in progress
*/
Syncer.prototype.numTasksInProgress = function() {
return $tw.utils.count(this.taskInProgress);
};
/*
Return the number of tasks in the queue
*/
Syncer.prototype.numTasksInQueue = function() {
return $tw.utils.count(this.taskQueue);
};
/*
Trigger a timeout if one isn't already outstanding
*/
Syncer.prototype.triggerTimeout = function() {
var self = this;
if(!this.taskTimerId) {
this.taskTimerId = setTimeout(function() {
self.taskTimerId = null;
self.processTaskQueue.call(self);
},self.taskTimerInterval);
}
};
/*
Process the task queue, performing the next task if appropriate
*/
Syncer.prototype.processTaskQueue = function() {
var self = this;
// Only process a task if we're not already performing a task. If we are already performing a task then we'll dispatch the next one when it completes
if(this.numTasksInProgress() === 0) {
// Choose the next task to perform
var task = this.chooseNextTask();
// Perform the task if we had one
if(task) {
// Remove the task from the queue and add it to the in progress list
delete this.taskQueue[task.title];
this.taskInProgress[task.title] = task;
this.updateDirtyStatus();
// Dispatch the task
this.dispatchTask(task,function(err) {
if(err) {
self.logger.alert("Sync error while processing '" + task.title + "':\n" + err);
}
// Mark that this task is no longer in progress
delete self.taskInProgress[task.title];
self.updateDirtyStatus();
// Process the next task
self.processTaskQueue.call(self);
});
} else {
// Make sure we've set a time if there wasn't a task to perform, but we've still got tasks in the queue
if(this.numTasksInQueue() > 0) {
this.triggerTimeout();
}
}
}
};
/*
Choose the next applicable task
*/
Syncer.prototype.chooseNextTask = function() {
var self = this,
candidateTask = null,
now = Date.now();
// Select the best candidate task
$tw.utils.each(this.taskQueue,function(task,title) {
// Exclude the task if there's one of the same name in progress
if($tw.utils.hop(self.taskInProgress,title)) {
return;
}
// Exclude the task if it is a save and the tiddler has been modified recently, but not hit the fallback time
if(task.type === "save" && (now - task.lastModificationTime) < self.throttleInterval &&
(now - task.queueTime) < self.fallbackInterval) {
return;
}
// Exclude the task if it is newer than the current best candidate
if(candidateTask && candidateTask.queueTime < task.queueTime) {
return;
}
// Now this is our best candidate
candidateTask = task;
});
return candidateTask;
};
/*
Dispatch a task and invoke the callback
*/
Syncer.prototype.dispatchTask = function(task,callback) {
var self = this;
if(task.type === "save") {
var changeCount = this.wiki.getChangeCount(task.title),
tiddler = this.wiki.getTiddler(task.title);
this.logger.log("Dispatching 'save' task:",task.title);
if(tiddler) {
this.syncadaptor.saveTiddler(tiddler,function(err,adaptorInfo,revision) {
if(err) {
return callback(err);
}
// Adjust the info stored about this tiddler
self.tiddlerInfo[task.title] = {
changeCount: changeCount,
adaptorInfo: adaptorInfo,
revision: revision
};
// Invoke the callback
callback(null);
},{
tiddlerInfo: self.tiddlerInfo[task.title]
});
} else {
this.logger.log(" Not Dispatching 'save' task:",task.title,"tiddler does not exist");
return callback(null);
}
} else if(task.type === "load") {
// Load the tiddler
this.logger.log("Dispatching 'load' task:",task.title);
this.syncadaptor.loadTiddler(task.title,function(err,tiddlerFields) {
if(err) {
return callback(err);
}
// Store the tiddler
if(tiddlerFields) {
self.storeTiddler(tiddlerFields);
}
// Invoke the callback
callback(null);
});
} else if(task.type === "delete") {
// Delete the tiddler
this.logger.log("Dispatching 'delete' task:",task.title);
this.syncadaptor.deleteTiddler(task.title,function(err) {
if(err) {
return callback(err);
}
delete self.tiddlerInfo[task.title];
// Invoke the callback
callback(null);
},{
tiddlerInfo: self.tiddlerInfo[task.title]
});
}
};
exports.Syncer = Syncer;
})();
/*\
title: $:/core/modules/tiddler.js
type: application/javascript
module-type: tiddlermethod
Extension methods for the $tw.Tiddler object (constructor and methods required at boot time are in boot/boot.js)
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.hasTag = function(tag) {
return this.fields.tags && this.fields.tags.indexOf(tag) !== -1;
};
exports.isPlugin = function() {
return this.fields.type === "application/json" && this.hasField("plugin-type");
};
exports.isDraft = function() {
return this.hasField("draft.of");
};
exports.getFieldString = function(field) {
var value = this.fields[field];
// Check for a missing field
if(value === undefined || value === null) {
return "";
}
// Parse the field with the associated module (if any)
var fieldModule = $tw.Tiddler.fieldModules[field];
if(fieldModule && fieldModule.stringify) {
return fieldModule.stringify.call(this,value);
} else {
return value.toString();
}
};
/*
Get all the fields as a name:value block. Options:
exclude: an array of field names to exclude
*/
exports.getFieldStringBlock = function(options) {
options = options || {};
var exclude = options.exclude || [];
var fields = [];
for(var field in this.fields) {
if($tw.utils.hop(this.fields,field)) {
if(exclude.indexOf(field) === -1) {
fields.push(field + ": " + this.getFieldString(field));
}
}
}
return fields.join("\n");
};
/*
Compare two tiddlers for equality
tiddler: the tiddler to compare
excludeFields: array of field names to exclude from the comparison
*/
exports.isEqual = function(tiddler,excludeFields) {
if(!(tiddler instanceof $tw.Tiddler)) {
return false;
}
excludeFields = excludeFields || [];
var self = this,
differences = []; // Fields that have differences
// Add to the differences array
function addDifference(fieldName) {
// Check for this field being excluded
if(excludeFields.indexOf(fieldName) === -1) {
// Save the field as a difference
$tw.utils.pushTop(differences,fieldName);
}
}
// Returns true if the two values of this field are equal
function isFieldValueEqual(fieldName) {
var valueA = self.fields[fieldName],
valueB = tiddler.fields[fieldName];
// Check for identical string values
if(typeof(valueA) === "string" && typeof(valueB) === "string" && valueA === valueB) {
return true;
}
// Check for identical array values
if($tw.utils.isArray(valueA) && $tw.utils.isArray(valueB) && $tw.utils.isArrayEqual(valueA,valueB)) {
return true;
}
// Otherwise the fields must be different
return false;
}
// Compare our fields
for(var fieldName in this.fields) {
if(!isFieldValueEqual(fieldName)) {
addDifference(fieldName);
}
}
// There's a difference for every field in the other tiddler that we don't have
for(fieldName in tiddler.fields) {
if(!(fieldName in this.fields)) {
addDifference(fieldName);
}
}
// Return whether there were any differences
return differences.length === 0;
};
})();
/*\
title: $:/core/modules/upgraders/plugins.js
type: application/javascript
module-type: upgrader
Upgrader module that checks that plugins are newer than any already installed version
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var UPGRADE_LIBRARY_TITLE = "$:/UpgradeLibrary";
var BLOCKED_PLUGINS = {
"$:/themes/tiddlywiki/stickytitles": {
versions: ["*"]
},
"$:/plugins/tiddlywiki/fullscreen": {
versions: ["*"]
}
};
exports.upgrade = function(wiki,titles,tiddlers) {
var self = this,
messages = {},
upgradeLibrary,
getLibraryTiddler = function(title) {
if(!upgradeLibrary) {
upgradeLibrary = wiki.getTiddlerData(UPGRADE_LIBRARY_TITLE,{});
upgradeLibrary.tiddlers = upgradeLibrary.tiddlers || {};
}
return upgradeLibrary.tiddlers[title];
};
// Go through all the incoming tiddlers
$tw.utils.each(titles,function(title) {
var incomingTiddler = tiddlers[title];
// Check if we're dealing with a plugin
if(incomingTiddler && incomingTiddler["plugin-type"] && incomingTiddler.version) {
// Upgrade the incoming plugin if it is in the upgrade library
var libraryTiddler = getLibraryTiddler(title);
if(libraryTiddler && libraryTiddler["plugin-type"] && libraryTiddler.version) {
tiddlers[title] = libraryTiddler;
messages[title] = $tw.language.getString("Import/Upgrader/Plugins/Upgraded",{variables: {incoming: incomingTiddler.version, upgraded: libraryTiddler.version}});
return;
}
// Suppress the incoming plugin if it is older than the currently installed one
var existingTiddler = wiki.getTiddler(title);
if(existingTiddler && existingTiddler.hasField("plugin-type") && existingTiddler.hasField("version")) {
// Reject the incoming plugin by blanking all its fields
if($tw.utils.checkVersions(existingTiddler.fields.version,incomingTiddler.version)) {
tiddlers[title] = Object.create(null);
messages[title] = $tw.language.getString("Import/Upgrader/Plugins/Suppressed/Version",{variables: {incoming: incomingTiddler.version, existing: existingTiddler.fields.version}});
return;
}
}
}
if(incomingTiddler && incomingTiddler["plugin-type"]) {
// Check whether the plugin is on the blocked list
var blockInfo = BLOCKED_PLUGINS[title];
if(blockInfo) {
if(blockInfo.versions.indexOf("*") !== -1 || (incomingTiddler.version && blockInfo.versions.indexOf(incomingTiddler.version) !== -1)) {
tiddlers[title] = Object.create(null);
messages[title] = $tw.language.getString("Import/Upgrader/Plugins/Suppressed/Incompatible");
return;
}
}
}
});
return messages;
};
})();
/*\
title: $:/core/modules/upgraders/system.js
type: application/javascript
module-type: upgrader
Upgrader module that suppresses certain system tiddlers that shouldn't be imported
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var DONT_IMPORT_LIST = ["$:/StoryList","$:/HistoryList"],
DONT_IMPORT_PREFIX_LIST = ["$:/temp/","$:/state/"];
exports.upgrade = function(wiki,titles,tiddlers) {
var self = this,
messages = {};
// Check for tiddlers on our list
$tw.utils.each(titles,function(title) {
if(DONT_IMPORT_LIST.indexOf(title) !== -1) {
tiddlers[title] = Object.create(null);
messages[title] = $tw.language.getString("Import/Upgrader/System/Suppressed");
} else {
for(var t=0; t<DONT_IMPORT_PREFIX_LIST.length; t++) {
var prefix = DONT_IMPORT_PREFIX_LIST[t];
if(title.substr(0,prefix.length) === prefix) {
tiddlers[title] = Object.create(null);
messages[title] = $tw.language.getString("Import/Upgrader/State/Suppressed");
}
}
}
});
return messages;
};
})();
/*\
title: $:/core/modules/upgraders/themetweaks.js
type: application/javascript
module-type: upgrader
Upgrader module that handles the change in theme tweak storage introduced in 5.0.14-beta.
Previously, theme tweaks were stored in two data tiddlers:
* $:/themes/tiddlywiki/vanilla/metrics
* $:/themes/tiddlywiki/vanilla/settings
Now, each tweak is stored in its own separate tiddler.
This upgrader copies any values from the old format to the new. The old data tiddlers are not deleted in case they have been used to store additional indexes.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var MAPPINGS = {
"$:/themes/tiddlywiki/vanilla/metrics": {
"fontsize": "$:/themes/tiddlywiki/vanilla/metrics/fontsize",
"lineheight": "$:/themes/tiddlywiki/vanilla/metrics/lineheight",
"storyleft": "$:/themes/tiddlywiki/vanilla/metrics/storyleft",
"storytop": "$:/themes/tiddlywiki/vanilla/metrics/storytop",
"storyright": "$:/themes/tiddlywiki/vanilla/metrics/storyright",
"storywidth": "$:/themes/tiddlywiki/vanilla/metrics/storywidth",
"tiddlerwidth": "$:/themes/tiddlywiki/vanilla/metrics/tiddlerwidth"
},
"$:/themes/tiddlywiki/vanilla/settings": {
"fontfamily": "$:/themes/tiddlywiki/vanilla/settings/fontfamily"
}
};
exports.upgrade = function(wiki,titles,tiddlers) {
var self = this,
messages = {};
// Check for tiddlers on our list
$tw.utils.each(titles,function(title) {
var mapping = MAPPINGS[title];
if(mapping) {
var tiddler = new $tw.Tiddler(tiddlers[title]),
tiddlerData = wiki.getTiddlerDataCached(tiddler,{});
for(var index in mapping) {
var mappedTitle = mapping[index];
if(!tiddlers[mappedTitle] || tiddlers[mappedTitle].title !== mappedTitle) {
tiddlers[mappedTitle] = {
title: mappedTitle,
text: tiddlerData[index]
};
messages[mappedTitle] = $tw.language.getString("Import/Upgrader/ThemeTweaks/Created",{variables: {
from: title + "##" + index
}});
}
}
}
});
return messages;
};
})();
/*\
title: $:/core/modules/utils/crypto.js
type: application/javascript
module-type: utils
Utility functions related to crypto.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Look for an encrypted store area in the text of a TiddlyWiki file
*/
exports.extractEncryptedStoreArea = function(text) {
var encryptedStoreAreaStartMarker = "<pre id=\"encryptedStoreArea\" type=\"text/plain\" style=\"display:none;\">",
encryptedStoreAreaStart = text.indexOf(encryptedStoreAreaStartMarker);
if(encryptedStoreAreaStart !== -1) {
var encryptedStoreAreaEnd = text.indexOf("</pre>",encryptedStoreAreaStart);
if(encryptedStoreAreaEnd !== -1) {
return $tw.utils.htmlDecode(text.substring(encryptedStoreAreaStart + encryptedStoreAreaStartMarker.length,encryptedStoreAreaEnd-1));
}
}
return null;
};
/*
Attempt to extract the tiddlers from an encrypted store area using the current password. If the password is not provided then the password in the password store will be used
*/
exports.decryptStoreArea = function(encryptedStoreArea,password) {
var decryptedText = $tw.crypto.decrypt(encryptedStoreArea,password);
if(decryptedText) {
var json = JSON.parse(decryptedText),
tiddlers = [];
for(var title in json) {
if(title !== "$:/isEncrypted") {
tiddlers.push(json[title]);
}
}
return tiddlers;
} else {
return null;
}
};
/*
Attempt to extract the tiddlers from an encrypted store area using the current password. If that fails, the user is prompted for a password.
encryptedStoreArea: text of the TiddlyWiki encrypted store area
callback: function(tiddlers) called with the array of decrypted tiddlers
The following configuration settings are supported:
$tw.config.usePasswordVault: causes any password entered by the user to also be put into the system password vault
*/
exports.decryptStoreAreaInteractive = function(encryptedStoreArea,callback,options) {
// Try to decrypt with the current password
var tiddlers = $tw.utils.decryptStoreArea(encryptedStoreArea);
if(tiddlers) {
callback(tiddlers);
} else {
// Prompt for a new password and keep trying
$tw.passwordPrompt.createPrompt({
serviceName: "Enter a password to decrypt the imported TiddlyWiki",
noUserName: true,
canCancel: true,
submitText: "Decrypt",
callback: function(data) {
// Exit if the user cancelled
if(!data) {
return false;
}
// Attempt to decrypt the tiddlers
var tiddlers = $tw.utils.decryptStoreArea(encryptedStoreArea,data.password);
if(tiddlers) {
if($tw.config.usePasswordVault) {
$tw.crypto.setPassword(data.password);
}
callback(tiddlers);
// Exit and remove the password prompt
return true;
} else {
// We didn't decrypt everything, so continue to prompt for password
return false;
}
}
});
}
};
})();
/*\
title: $:/core/modules/utils/dom.js
type: application/javascript
module-type: utils
Various static DOM-related utility functions.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Determines whether element 'a' contains element 'b'
Code thanks to John Resig, http://ejohn.org/blog/comparing-document-position/
*/
exports.domContains = function(a,b) {
return a.contains ?
a !== b && a.contains(b) :
!!(a.compareDocumentPosition(b) & 16);
};
exports.removeChildren = function(node) {
while(node.hasChildNodes()) {
node.removeChild(node.firstChild);
}
};
exports.hasClass = function(el,className) {
return el && el.className && el.className.toString().split(" ").indexOf(className) !== -1;
};
exports.addClass = function(el,className) {
var c = el.className.split(" ");
if(c.indexOf(className) === -1) {
c.push(className);
}
el.className = c.join(" ");
};
exports.removeClass = function(el,className) {
var c = el.className.split(" "),
p = c.indexOf(className);
if(p !== -1) {
c.splice(p,1);
el.className = c.join(" ");
}
};
exports.toggleClass = function(el,className,status) {
if(status === undefined) {
status = !exports.hasClass(el,className);
}
if(status) {
exports.addClass(el,className);
} else {
exports.removeClass(el,className);
}
};
/*
Get the scroll position of the viewport
Returns:
{
x: horizontal scroll position in pixels,
y: vertical scroll position in pixels
}
*/
exports.getScrollPosition = function() {
if("scrollX" in window) {
return {x: window.scrollX, y: window.scrollY};
} else {
return {x: document.documentElement.scrollLeft, y: document.documentElement.scrollTop};
}
};
/*
Gets the bounding rectangle of an element in absolute page coordinates
*/
exports.getBoundingPageRect = function(element) {
var scrollPos = $tw.utils.getScrollPosition(),
clientRect = element.getBoundingClientRect();
return {
left: clientRect.left + scrollPos.x,
width: clientRect.width,
right: clientRect.right + scrollPos.x,
top: clientRect.top + scrollPos.y,
height: clientRect.height,
bottom: clientRect.bottom + scrollPos.y
};
};
/*
Saves a named password in the browser
*/
exports.savePassword = function(name,password) {
try {
if(window.localStorage) {
localStorage.setItem("tw5-password-" + name,password);
}
} catch(e) {
}
};
/*
Retrieve a named password from the browser
*/
exports.getPassword = function(name) {
try {
return window.localStorage ? localStorage.getItem("tw5-password-" + name) : "";
} catch(e) {
return "";
}
};
/*
Force layout of a dom node and its descendents
*/
exports.forceLayout = function(element) {
var dummy = element.offsetWidth;
};
/*
Pulse an element for debugging purposes
*/
exports.pulseElement = function(element) {
// Event handler to remove the class at the end
element.addEventListener($tw.browser.animationEnd,function handler(event) {
element.removeEventListener($tw.browser.animationEnd,handler,false);
$tw.utils.removeClass(element,"pulse");
},false);
// Apply the pulse class
$tw.utils.removeClass(element,"pulse");
$tw.utils.forceLayout(element);
$tw.utils.addClass(element,"pulse");
};
/*
Attach specified event handlers to a DOM node
domNode: where to attach the event handlers
events: array of event handlers to be added (see below)
Each entry in the events array is an object with these properties:
handlerFunction: optional event handler function
handlerObject: optional event handler object
handlerMethod: optionally specifies object handler method name (defaults to `handleEvent`)
*/
exports.addEventListeners = function(domNode,events) {
$tw.utils.each(events,function(eventInfo) {
var handler;
if(eventInfo.handlerFunction) {
handler = eventInfo.handlerFunction;
} else if(eventInfo.handlerObject) {
if(eventInfo.handlerMethod) {
handler = function(event) {
eventInfo.handlerObject[eventInfo.handlerMethod].call(eventInfo.handlerObject,event);
};
} else {
handler = eventInfo.handlerObject;
}
}
domNode.addEventListener(eventInfo.name,handler,false);
});
};
})();
/*\
title: $:/core/modules/utils/dom/animations/slide.js
type: application/javascript
module-type: animation
A simple slide animation that varies the height of the element
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
function slideOpen(domNode,options) {
options = options || {};
var duration = options.duration || $tw.utils.getAnimationDuration();
// Get the current height of the domNode
var computedStyle = window.getComputedStyle(domNode),
currMarginBottom = parseInt(computedStyle.marginBottom,10),
currMarginTop = parseInt(computedStyle.marginTop,10),
currPaddingBottom = parseInt(computedStyle.paddingBottom,10),
currPaddingTop = parseInt(computedStyle.paddingTop,10),
currHeight = domNode.offsetHeight;
// Reset the margin once the transition is over
setTimeout(function() {
$tw.utils.setStyle(domNode,[
{transition: "none"},
{marginBottom: ""},
{marginTop: ""},
{paddingBottom: ""},
{paddingTop: ""},
{height: "auto"},
{opacity: ""}
]);
if(options.callback) {
options.callback();
}
},duration);
// Set up the initial position of the element
$tw.utils.setStyle(domNode,[
{transition: "none"},
{marginTop: "0px"},
{marginBottom: "0px"},
{paddingTop: "0px"},
{paddingBottom: "0px"},
{height: "0px"},
{opacity: "0"}
]);
$tw.utils.forceLayout(domNode);
// Transition to the final position
$tw.utils.setStyle(domNode,[
{transition: "margin-top " + duration + "ms ease-in-out, " +
"margin-bottom " + duration + "ms ease-in-out, " +
"padding-top " + duration + "ms ease-in-out, " +
"padding-bottom " + duration + "ms ease-in-out, " +
"height " + duration + "ms ease-in-out, " +
"opacity " + duration + "ms ease-in-out"},
{marginBottom: currMarginBottom + "px"},
{marginTop: currMarginTop + "px"},
{paddingBottom: currPaddingBottom + "px"},
{paddingTop: currPaddingTop + "px"},
{height: currHeight + "px"},
{opacity: "1"}
]);
}
function slideClosed(domNode,options) {
options = options || {};
var duration = options.duration || $tw.utils.getAnimationDuration(),
currHeight = domNode.offsetHeight;
// Clear the properties we've set when the animation is over
setTimeout(function() {
$tw.utils.setStyle(domNode,[
{transition: "none"},
{marginBottom: ""},
{marginTop: ""},
{paddingBottom: ""},
{paddingTop: ""},
{height: "auto"},
{opacity: ""}
]);
if(options.callback) {
options.callback();
}
},duration);
// Set up the initial position of the element
$tw.utils.setStyle(domNode,[
{height: currHeight + "px"},
{opacity: "1"}
]);
$tw.utils.forceLayout(domNode);
// Transition to the final position
$tw.utils.setStyle(domNode,[
{transition: "margin-top " + duration + "ms ease-in-out, " +
"margin-bottom " + duration + "ms ease-in-out, " +
"padding-top " + duration + "ms ease-in-out, " +
"padding-bottom " + duration + "ms ease-in-out, " +
"height " + duration + "ms ease-in-out, " +
"opacity " + duration + "ms ease-in-out"},
{marginTop: "0px"},
{marginBottom: "0px"},
{paddingTop: "0px"},
{paddingBottom: "0px"},
{height: "0px"},
{opacity: "0"}
]);
}
exports.slide = {
open: slideOpen,
close: slideClosed
};
})();
/*\
title: $:/core/modules/utils/dom/animator.js
type: application/javascript
module-type: utils
Orchestrates animations and transitions
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
function Animator() {
// Get the registered animation modules
this.animations = {};
$tw.modules.applyMethods("animation",this.animations);
}
Animator.prototype.perform = function(type,domNode,options) {
options = options || {};
// Find an animation that can handle this type
var chosenAnimation;
$tw.utils.each(this.animations,function(animation,name) {
if($tw.utils.hop(animation,type)) {
chosenAnimation = animation[type];
}
});
if(!chosenAnimation) {
chosenAnimation = function(domNode,options) {
if(options.callback) {
options.callback();
}
};
}
// Call the animation
chosenAnimation(domNode,options);
};
exports.Animator = Animator;
})();
/*\
title: $:/core/modules/utils/dom/browser.js
type: application/javascript
module-type: utils
Browser feature detection
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Set style properties of an element
element: dom node
styles: ordered array of {name: value} pairs
*/
exports.setStyle = function(element,styles) {
if(element.nodeType === 1) { // Element.ELEMENT_NODE
for(var t=0; t<styles.length; t++) {
for(var styleName in styles[t]) {
element.style[$tw.utils.convertStyleNameToPropertyName(styleName)] = styles[t][styleName];
}
}
}
};
/*
Converts a standard CSS property name into the local browser-specific equivalent. For example:
"background-color" --> "backgroundColor"
"transition" --> "webkitTransition"
*/
var styleNameCache = {}; // We'll cache the style name conversions
exports.convertStyleNameToPropertyName = function(styleName) {
// Return from the cache if we can
if(styleNameCache[styleName]) {
return styleNameCache[styleName];
}
// Convert it by first removing any hyphens
var propertyName = $tw.utils.unHyphenateCss(styleName);
// Then check if it needs a prefix
if($tw.browser && document.body.style[propertyName] === undefined) {
var prefixes = ["O","MS","Moz","webkit"];
for(var t=0; t<prefixes.length; t++) {
var prefixedName = prefixes[t] + propertyName.substr(0,1).toUpperCase() + propertyName.substr(1);
if(document.body.style[prefixedName] !== undefined) {
propertyName = prefixedName;
break;
}
}
}
// Put it in the cache too
styleNameCache[styleName] = propertyName;
return propertyName;
};
/*
Converts a JS format CSS property name back into the dashed form used in CSS declarations. For example:
"backgroundColor" --> "background-color"
"webkitTransform" --> "-webkit-transform"
*/
exports.convertPropertyNameToStyleName = function(propertyName) {
// Rehyphenate the name
var styleName = $tw.utils.hyphenateCss(propertyName);
// If there's a webkit prefix, add a dash (other browsers have uppercase prefixes, and so get the dash automatically)
if(styleName.indexOf("webkit") === 0) {
styleName = "-" + styleName;
} else if(styleName.indexOf("-m-s") === 0) {
styleName = "-ms" + styleName.substr(4);
}
return styleName;
};
/*
Round trip a stylename to a property name and back again. For example:
"transform" --> "webkitTransform" --> "-webkit-transform"
*/
exports.roundTripPropertyName = function(propertyName) {
return $tw.utils.convertPropertyNameToStyleName($tw.utils.convertStyleNameToPropertyName(propertyName));
};
/*
Converts a standard event name into the local browser specific equivalent. For example:
"animationEnd" --> "webkitAnimationEnd"
*/
var eventNameCache = {}; // We'll cache the conversions
var eventNameMappings = {
"transitionEnd": {
correspondingCssProperty: "transition",
mappings: {
transition: "transitionend",
OTransition: "oTransitionEnd",
MSTransition: "msTransitionEnd",
MozTransition: "transitionend",
webkitTransition: "webkitTransitionEnd"
}
},
"animationEnd": {
correspondingCssProperty: "animation",
mappings: {
animation: "animationend",
OAnimation: "oAnimationEnd",
MSAnimation: "msAnimationEnd",
MozAnimation: "animationend",
webkitAnimation: "webkitAnimationEnd"
}
}
};
exports.convertEventName = function(eventName) {
if(eventNameCache[eventName]) {
return eventNameCache[eventName];
}
var newEventName = eventName,
mappings = eventNameMappings[eventName];
if(mappings) {
var convertedProperty = $tw.utils.convertStyleNameToPropertyName(mappings.correspondingCssProperty);
if(mappings.mappings[convertedProperty]) {
newEventName = mappings.mappings[convertedProperty];
}
}
// Put it in the cache too
eventNameCache[eventName] = newEventName;
return newEventName;
};
/*
Return the names of the fullscreen APIs
*/
exports.getFullScreenApis = function() {
var d = document,
db = d.body,
result = {
"_requestFullscreen": db.webkitRequestFullscreen !== undefined ? "webkitRequestFullscreen" :
db.mozRequestFullScreen !== undefined ? "mozRequestFullScreen" :
db.msRequestFullscreen !== undefined ? "msRequestFullscreen" :
db.requestFullscreen !== undefined ? "requestFullscreen" : "",
"_exitFullscreen": d.webkitExitFullscreen !== undefined ? "webkitExitFullscreen" :
d.mozCancelFullScreen !== undefined ? "mozCancelFullScreen" :
d.msExitFullscreen !== undefined ? "msExitFullscreen" :
d.exitFullscreen !== undefined ? "exitFullscreen" : "",
"_fullscreenElement": d.webkitFullscreenElement !== undefined ? "webkitFullscreenElement" :
d.mozFullScreenElement !== undefined ? "mozFullScreenElement" :
d.msFullscreenElement !== undefined ? "msFullscreenElement" :
d.fullscreenElement !== undefined ? "fullscreenElement" : "",
"_fullscreenChange": d.webkitFullscreenElement !== undefined ? "webkitfullscreenchange" :
d.mozFullScreenElement !== undefined ? "mozfullscreenchange" :
d.msFullscreenElement !== undefined ? "MSFullscreenChange" :
d.fullscreenElement !== undefined ? "fullscreenchange" : ""
};
if(!result._requestFullscreen || !result._exitFullscreen || !result._fullscreenElement || !result._fullscreenChange) {
return null;
} else {
return result;
}
};
})();
// (c) Dean McNamee <dean@gmail.com>, 2012.
//
// https://github.com/deanm/css-color-parser-js
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// http://www.w3.org/TR/css3-color/
var kCSSColorTable = {
"transparent": [0,0,0,0], "aliceblue": [240,248,255,1],
"antiquewhite": [250,235,215,1], "aqua": [0,255,255,1],
"aquamarine": [127,255,212,1], "azure": [240,255,255,1],
"beige": [245,245,220,1], "bisque": [255,228,196,1],
"black": [0,0,0,1], "blanchedalmond": [255,235,205,1],
"blue": [0,0,255,1], "blueviolet": [138,43,226,1],
"brown": [165,42,42,1], "burlywood": [222,184,135,1],
"cadetblue": [95,158,160,1], "chartreuse": [127,255,0,1],
"chocolate": [210,105,30,1], "coral": [255,127,80,1],
"cornflowerblue": [100,149,237,1], "cornsilk": [255,248,220,1],
"crimson": [220,20,60,1], "cyan": [0,255,255,1],
"darkblue": [0,0,139,1], "darkcyan": [0,139,139,1],
"darkgoldenrod": [184,134,11,1], "darkgray": [169,169,169,1],
"darkgreen": [0,100,0,1], "darkgrey": [169,169,169,1],
"darkkhaki": [189,183,107,1], "darkmagenta": [139,0,139,1],
"darkolivegreen": [85,107,47,1], "darkorange": [255,140,0,1],
"darkorchid": [153,50,204,1], "darkred": [139,0,0,1],
"darksalmon": [233,150,122,1], "darkseagreen": [143,188,143,1],
"darkslateblue": [72,61,139,1], "darkslategray": [47,79,79,1],
"darkslategrey": [47,79,79,1], "darkturquoise": [0,206,209,1],
"darkviolet": [148,0,211,1], "deeppink": [255,20,147,1],
"deepskyblue": [0,191,255,1], "dimgray": [105,105,105,1],
"dimgrey": [105,105,105,1], "dodgerblue": [30,144,255,1],
"firebrick": [178,34,34,1], "floralwhite": [255,250,240,1],
"forestgreen": [34,139,34,1], "fuchsia": [255,0,255,1],
"gainsboro": [220,220,220,1], "ghostwhite": [248,248,255,1],
"gold": [255,215,0,1], "goldenrod": [218,165,32,1],
"gray": [128,128,128,1], "green": [0,128,0,1],
"greenyellow": [173,255,47,1], "grey": [128,128,128,1],
"honeydew": [240,255,240,1], "hotpink": [255,105,180,1],
"indianred": [205,92,92,1], "indigo": [75,0,130,1],
"ivory": [255,255,240,1], "khaki": [240,230,140,1],
"lavender": [230,230,250,1], "lavenderblush": [255,240,245,1],
"lawngreen": [124,252,0,1], "lemonchiffon": [255,250,205,1],
"lightblue": [173,216,230,1], "lightcoral": [240,128,128,1],
"lightcyan": [224,255,255,1], "lightgoldenrodyellow": [250,250,210,1],
"lightgray": [211,211,211,1], "lightgreen": [144,238,144,1],
"lightgrey": [211,211,211,1], "lightpink": [255,182,193,1],
"lightsalmon": [255,160,122,1], "lightseagreen": [32,178,170,1],
"lightskyblue": [135,206,250,1], "lightslategray": [119,136,153,1],
"lightslategrey": [119,136,153,1], "lightsteelblue": [176,196,222,1],
"lightyellow": [255,255,224,1], "lime": [0,255,0,1],
"limegreen": [50,205,50,1], "linen": [250,240,230,1],
"magenta": [255,0,255,1], "maroon": [128,0,0,1],
"mediumaquamarine": [102,205,170,1], "mediumblue": [0,0,205,1],
"mediumorchid": [186,85,211,1], "mediumpurple": [147,112,219,1],
"mediumseagreen": [60,179,113,1], "mediumslateblue": [123,104,238,1],
"mediumspringgreen": [0,250,154,1], "mediumturquoise": [72,209,204,1],
"mediumvioletred": [199,21,133,1], "midnightblue": [25,25,112,1],
"mintcream": [245,255,250,1], "mistyrose": [255,228,225,1],
"moccasin": [255,228,181,1], "navajowhite": [255,222,173,1],
"navy": [0,0,128,1], "oldlace": [253,245,230,1],
"olive": [128,128,0,1], "olivedrab": [107,142,35,1],
"orange": [255,165,0,1], "orangered": [255,69,0,1],
"orchid": [218,112,214,1], "palegoldenrod": [238,232,170,1],
"palegreen": [152,251,152,1], "paleturquoise": [175,238,238,1],
"palevioletred": [219,112,147,1], "papayawhip": [255,239,213,1],
"peachpuff": [255,218,185,1], "peru": [205,133,63,1],
"pink": [255,192,203,1], "plum": [221,160,221,1],
"powderblue": [176,224,230,1], "purple": [128,0,128,1],
"red": [255,0,0,1], "rosybrown": [188,143,143,1],
"royalblue": [65,105,225,1], "saddlebrown": [139,69,19,1],
"salmon": [250,128,114,1], "sandybrown": [244,164,96,1],
"seagreen": [46,139,87,1], "seashell": [255,245,238,1],
"sienna": [160,82,45,1], "silver": [192,192,192,1],
"skyblue": [135,206,235,1], "slateblue": [106,90,205,1],
"slategray": [112,128,144,1], "slategrey": [112,128,144,1],
"snow": [255,250,250,1], "springgreen": [0,255,127,1],
"steelblue": [70,130,180,1], "tan": [210,180,140,1],
"teal": [0,128,128,1], "thistle": [216,191,216,1],
"tomato": [255,99,71,1], "turquoise": [64,224,208,1],
"violet": [238,130,238,1], "wheat": [245,222,179,1],
"white": [255,255,255,1], "whitesmoke": [245,245,245,1],
"yellow": [255,255,0,1], "yellowgreen": [154,205,50,1]}
function clamp_css_byte(i) { // Clamp to integer 0 .. 255.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 255 ? 255 : i;
}
function clamp_css_float(f) { // Clamp to float 0.0 .. 1.0.
return f < 0 ? 0 : f > 1 ? 1 : f;
}
function parse_css_int(str) { // int or percentage.
if (str[str.length - 1] === '%')
return clamp_css_byte(parseFloat(str) / 100 * 255);
return clamp_css_byte(parseInt(str));
}
function parse_css_float(str) { // float or percentage.
if (str[str.length - 1] === '%')
return clamp_css_float(parseFloat(str) / 100);
return clamp_css_float(parseFloat(str));
}
function css_hue_to_rgb(m1, m2, h) {
if (h < 0) h += 1;
else if (h > 1) h -= 1;
if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
if (h * 2 < 1) return m2;
if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;
return m1;
}
function parseCSSColor(css_str) {
// Remove all whitespace, not compliant, but should just be more accepting.
var str = css_str.replace(/ /g, '').toLowerCase();
// Color keywords (and transparent) lookup.
if (str in kCSSColorTable) return kCSSColorTable[str].slice(); // dup.
// #abc and #abc123 syntax.
if (str[0] === '#') {
if (str.length === 4) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xfff)) return null; // Covers NaN.
return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
(iv & 0xf0) | ((iv & 0xf0) >> 4),
(iv & 0xf) | ((iv & 0xf) << 4),
1];
} else if (str.length === 7) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN.
return [(iv & 0xff0000) >> 16,
(iv & 0xff00) >> 8,
iv & 0xff,
1];
}
return null;
}
var op = str.indexOf('('), ep = str.indexOf(')');
if (op !== -1 && ep + 1 === str.length) {
var fname = str.substr(0, op);
var params = str.substr(op+1, ep-(op+1)).split(',');
var alpha = 1; // To allow case fallthrough.
switch (fname) {
case 'rgba':
if (params.length !== 4) return null;
alpha = parse_css_float(params.pop());
// Fall through.
case 'rgb':
if (params.length !== 3) return null;
return [parse_css_int(params[0]),
parse_css_int(params[1]),
parse_css_int(params[2]),
alpha];
case 'hsla':
if (params.length !== 4) return null;
alpha = parse_css_float(params.pop());
// Fall through.
case 'hsl':
if (params.length !== 3) return null;
var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1
// NOTE(deanm): According to the CSS spec s/l should only be
// percentages, but we don't bother and let float or percentage.
var s = parse_css_float(params[1]);
var l = parse_css_float(params[2]);
var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var m1 = l * 2 - m2;
return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255),
clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255),
clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255),
alpha];
default:
return null;
}
}
return null;
}
try { exports.parseCSSColor = parseCSSColor } catch(e) { }
/*\
title: $:/core/modules/utils/dom/http.js
type: application/javascript
module-type: utils
Browser HTTP support
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
A quick and dirty HTTP function; to be refactored later. Options are:
url: URL to retrieve
type: GET, PUT, POST etc
callback: function invoked with (err,data)
*/
exports.httpRequest = function(options) {
var type = options.type || "GET",
headers = options.headers || {accept: "application/json"},
request = new XMLHttpRequest(),
data = "",
f,results;
// Massage the data hashmap into a string
if(options.data) {
if(typeof options.data === "string") { // Already a string
data = options.data;
} else { // A hashmap of strings
results = [];
$tw.utils.each(options.data,function(dataItem,dataItemTitle) {
results.push(dataItemTitle + "=" + encodeURIComponent(dataItem));
});
data = results.join("&");
}
}
// Set up the state change handler
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status === 200 || this.status === 201 || this.status === 204) {
// Success!
options.callback(null,this.responseText,this);
return;
}
// Something went wrong
options.callback("XMLHttpRequest error code: " + this.status);
}
};
// Make the request
request.open(type,options.url,true);
if(headers) {
$tw.utils.each(headers,function(header,headerTitle,object) {
request.setRequestHeader(headerTitle,header);
});
}
if(data && !$tw.utils.hop(headers,"Content-type")) {
request.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
}
try {
request.send(data);
} catch(e) {
options.callback(e);
}
return request;
};
})();
/*\
title: $:/core/modules/utils/dom/keyboard.js
type: application/javascript
module-type: utils
Keyboard utilities
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var namedKeys = {
"backspace": 8,
"tab": 9,
"enter": 13,
"escape": 27
};
/*
Parses a key descriptor into the structure:
{
keyCode: numeric keycode
shiftKey: boolean
altKey: boolean
ctrlKey: boolean
}
Key descriptors have the following format:
ctrl+enter
ctrl+shift+alt+A
*/
exports.parseKeyDescriptor = function(keyDescriptor) {
var components = keyDescriptor.split("+"),
info = {
keyCode: 0,
shiftKey: false,
altKey: false,
ctrlKey: false
};
for(var t=0; t<components.length; t++) {
var s = components[t].toLowerCase();
// Look for modifier keys
if(s === "ctrl") {
info.ctrlKey = true;
} else if(s === "shift") {
info.shiftKey = true;
} else if(s === "alt") {
info.altKey = true;
} else if(s === "meta") {
info.metaKey = true;
}
// Replace named keys with their code
if(namedKeys[s]) {
info.keyCode = namedKeys[s];
}
}
return info;
};
exports.checkKeyDescriptor = function(event,keyInfo) {
var metaKeyStatus = !!keyInfo.metaKey; // Using a temporary variable to keep JSHint happy
return event.keyCode === keyInfo.keyCode &&
event.shiftKey === keyInfo.shiftKey &&
event.altKey === keyInfo.altKey &&
event.ctrlKey === keyInfo.ctrlKey &&
event.metaKey === metaKeyStatus;
};
})();
/*\
title: $:/core/modules/utils/dom/modal.js
type: application/javascript
module-type: utils
Modal message mechanism
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var widget = require("$:/core/modules/widgets/widget.js");
var Modal = function(wiki) {
this.wiki = wiki;
this.modalCount = 0;
};
/*
Display a modal dialogue
title: Title of tiddler to display
options: see below
Options include:
downloadLink: Text of a big download link to include
*/
Modal.prototype.display = function(title,options) {
options = options || {};
var self = this,
refreshHandler,
duration = $tw.utils.getAnimationDuration(),
tiddler = this.wiki.getTiddler(title);
// Don't do anything if the tiddler doesn't exist
if(!tiddler) {
return;
}
// Create the variables
var variables = $tw.utils.extend({currentTiddler: title},options.variables);
// Create the wrapper divs
var wrapper = document.createElement("div"),
modalBackdrop = document.createElement("div"),
modalWrapper = document.createElement("div"),
modalHeader = document.createElement("div"),
headerTitle = document.createElement("h3"),
modalBody = document.createElement("div"),
modalLink = document.createElement("a"),
modalFooter = document.createElement("div"),
modalFooterHelp = document.createElement("span"),
modalFooterButtons = document.createElement("span");
// Up the modal count and adjust the body class
this.modalCount++;
this.adjustPageClass();
// Add classes
$tw.utils.addClass(wrapper,"tc-modal-wrapper");
$tw.utils.addClass(modalBackdrop,"tc-modal-backdrop");
$tw.utils.addClass(modalWrapper,"tc-modal");
$tw.utils.addClass(modalHeader,"tc-modal-header");
$tw.utils.addClass(modalBody,"tc-modal-body");
$tw.utils.addClass(modalFooter,"tc-modal-footer");
// Join them together
wrapper.appendChild(modalBackdrop);
wrapper.appendChild(modalWrapper);
modalHeader.appendChild(headerTitle);
modalWrapper.appendChild(modalHeader);
modalWrapper.appendChild(modalBody);
modalFooter.appendChild(modalFooterHelp);
modalFooter.appendChild(modalFooterButtons);
modalWrapper.appendChild(modalFooter);
// Render the title of the message
var headerWidgetNode = this.wiki.makeTranscludeWidget(title,{
field: "subtitle",
mode: "inline",
children: [{
type: "text",
attributes: {
text: {
type: "string",
value: title
}}}],
parentWidget: $tw.rootWidget,
document: document,
variables: variables
});
headerWidgetNode.render(headerTitle,null);
// Render the body of the message
var bodyWidgetNode = this.wiki.makeTranscludeWidget(title,{
parentWidget: $tw.rootWidget,
document: document,
variables: variables
});
bodyWidgetNode.render(modalBody,null);
// Setup the link if present
if(options.downloadLink) {
modalLink.href = options.downloadLink;
modalLink.appendChild(document.createTextNode("Right-click to save changes"));
modalBody.appendChild(modalLink);
}
// Render the footer of the message
if(tiddler && tiddler.fields && tiddler.fields.help) {
var link = document.createElement("a");
link.setAttribute("href",tiddler.fields.help);
link.setAttribute("target","_blank");
link.appendChild(document.createTextNode("Help"));
modalFooterHelp.appendChild(link);
modalFooterHelp.style.float = "left";
}
var footerWidgetNode = this.wiki.makeTranscludeWidget(title,{
field: "footer",
mode: "inline",
children: [{
type: "button",
attributes: {
message: {
type: "string",
value: "tm-close-tiddler"
}
},
children: [{
type: "text",
attributes: {
text: {
type: "string",
value: "Close"
}}}
]}],
parentWidget: $tw.rootWidget,
document: document,
variables: variables
});
footerWidgetNode.render(modalFooterButtons,null);
// Set up the refresh handler
refreshHandler = function(changes) {
headerWidgetNode.refresh(changes,modalHeader,null);
bodyWidgetNode.refresh(changes,modalBody,null);
footerWidgetNode.refresh(changes,modalFooterButtons,null);
};
this.wiki.addEventListener("change",refreshHandler);
// Add the close event handler
var closeHandler = function(event) {
// Remove our refresh handler
self.wiki.removeEventListener("change",refreshHandler);
// Decrease the modal count and adjust the body class
self.modalCount--;
self.adjustPageClass();
// Force layout and animate the modal message away
$tw.utils.forceLayout(modalBackdrop);
$tw.utils.forceLayout(modalWrapper);
$tw.utils.setStyle(modalBackdrop,[
{opacity: "0"}
]);
$tw.utils.setStyle(modalWrapper,[
{transform: "translateY(" + window.innerHeight + "px)"}
]);
// Set up an event for the transition end
window.setTimeout(function() {
if(wrapper.parentNode) {
// Remove the modal message from the DOM
document.body.removeChild(wrapper);
}
},duration);
// Don't let anyone else handle the tm-close-tiddler message
return false;
};
headerWidgetNode.addEventListener("tm-close-tiddler",closeHandler,false);
bodyWidgetNode.addEventListener("tm-close-tiddler",closeHandler,false);
footerWidgetNode.addEventListener("tm-close-tiddler",closeHandler,false);
// Set the initial styles for the message
$tw.utils.setStyle(modalBackdrop,[
{opacity: "0"}
]);
$tw.utils.setStyle(modalWrapper,[
{transformOrigin: "0% 0%"},
{transform: "translateY(" + (-window.innerHeight) + "px)"}
]);
// Put the message into the document
document.body.appendChild(wrapper);
// Set up animation for the styles
$tw.utils.setStyle(modalBackdrop,[
{transition: "opacity " + duration + "ms ease-out"}
]);
$tw.utils.setStyle(modalWrapper,[
{transition: $tw.utils.roundTripPropertyName("transform") + " " + duration + "ms ease-in-out"}
]);
// Force layout
$tw.utils.forceLayout(modalBackdrop);
$tw.utils.forceLayout(modalWrapper);
// Set final animated styles
$tw.utils.setStyle(modalBackdrop,[
{opacity: "0.7"}
]);
$tw.utils.setStyle(modalWrapper,[
{transform: "translateY(0px)"}
]);
};
Modal.prototype.adjustPageClass = function() {
if($tw.pageContainer) {
$tw.utils.toggleClass($tw.pageContainer,"tc-modal-displayed",this.modalCount > 0);
}
};
exports.Modal = Modal;
})();
/*\
title: $:/core/modules/utils/dom/notifier.js
type: application/javascript
module-type: utils
Notifier mechanism
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var widget = require("$:/core/modules/widgets/widget.js");
var Notifier = function(wiki) {
this.wiki = wiki;
};
/*
Display a notification
title: Title of tiddler containing the notification text
options: see below
Options include:
*/
Notifier.prototype.display = function(title,options) {
options = options || {};
// Create the wrapper divs
var self = this,
notification = document.createElement("div"),
tiddler = this.wiki.getTiddler(title),
duration = $tw.utils.getAnimationDuration(),
refreshHandler;
// Don't do anything if the tiddler doesn't exist
if(!tiddler) {
return;
}
// Add classes
$tw.utils.addClass(notification,"tc-notification");
// Create the variables
var variables = $tw.utils.extend({currentTiddler: title},options.variables);
// Render the body of the notification
var widgetNode = this.wiki.makeTranscludeWidget(title,{parentWidget: $tw.rootWidget, document: document, variables: variables});
widgetNode.render(notification,null);
refreshHandler = function(changes) {
widgetNode.refresh(changes,notification,null);
};
this.wiki.addEventListener("change",refreshHandler);
// Set the initial styles for the notification
$tw.utils.setStyle(notification,[
{opacity: "0"},
{transformOrigin: "0% 0%"},
{transform: "translateY(" + (-window.innerHeight) + "px)"},
{transition: "opacity " + duration + "ms ease-out, " + $tw.utils.roundTripPropertyName("transform") + " " + duration + "ms ease-in-out"}
]);
// Add the notification to the DOM
document.body.appendChild(notification);
// Force layout
$tw.utils.forceLayout(notification);
// Set final animated styles
$tw.utils.setStyle(notification,[
{opacity: "1.0"},
{transform: "translateY(0px)"}
]);
// Set a timer to remove the notification
window.setTimeout(function() {
// Remove our change event handler
self.wiki.removeEventListener("change",refreshHandler);
// Force layout and animate the notification away
$tw.utils.forceLayout(notification);
$tw.utils.setStyle(notification,[
{opacity: "0.0"},
{transform: "translateX(" + (notification.offsetWidth) + "px)"}
]);
// Remove the modal message from the DOM once the transition ends
setTimeout(function() {
if(notification.parentNode) {
document.body.removeChild(notification);
}
},duration);
},$tw.config.preferences.notificationDuration);
};
exports.Notifier = Notifier;
})();
/*\
title: $:/core/modules/utils/dom/popup.js
type: application/javascript
module-type: utils
Module that creates a $tw.utils.Popup object prototype that manages popups in the browser
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Creates a Popup object with these options:
rootElement: the DOM element to which the popup zapper should be attached
*/
var Popup = function(options) {
options = options || {};
this.rootElement = options.rootElement || document.documentElement;
this.popups = []; // Array of {title:,wiki:,domNode:} objects
};
/*
Trigger a popup open or closed. Parameters are in a hashmap:
title: title of the tiddler where the popup details are stored
domNode: dom node to which the popup will be positioned
wiki: wiki
force: if specified, forces the popup state to true or false (instead of toggling it)
*/
Popup.prototype.triggerPopup = function(options) {
// Check if this popup is already active
var index = this.findPopup(options.title);
// Compute the new state
var state = index === -1;
if(options.force !== undefined) {
state = options.force;
}
// Show or cancel the popup according to the new state
if(state) {
this.show(options);
} else {
this.cancel(index);
}
};
Popup.prototype.findPopup = function(title) {
var index = -1;
for(var t=0; t<this.popups.length; t++) {
if(this.popups[t].title === title) {
index = t;
}
}
return index;
};
Popup.prototype.handleEvent = function(event) {
if(event.type === "click") {
// Find out what was clicked on
var info = this.popupInfo(event.target),
cancelLevel = info.popupLevel - 1;
// Don't remove the level that was clicked on if we clicked on a handle
if(info.isHandle) {
cancelLevel++;
}
// Cancel
this.cancel(cancelLevel);
}
};
/*
Find the popup level containing a DOM node. Returns:
popupLevel: count of the number of nested popups containing the specified element
isHandle: true if the specified element is within a popup handle
*/
Popup.prototype.popupInfo = function(domNode) {
var isHandle = false,
popupCount = 0,
node = domNode;
// First check ancestors to see if we're within a popup handle
while(node) {
if($tw.utils.hasClass(node,"tc-popup-handle")) {
isHandle = true;
popupCount++;
}
if($tw.utils.hasClass(node,"tc-popup-keep")) {
isHandle = true;
}
node = node.parentNode;
}
// Then count the number of ancestor popups
node = domNode;
while(node) {
if($tw.utils.hasClass(node,"tc-popup")) {
popupCount++;
}
node = node.parentNode;
}
var info = {
popupLevel: popupCount,
isHandle: isHandle
};
return info;
};
/*
Display a popup by adding it to the stack
*/
Popup.prototype.show = function(options) {
// Find out what was clicked on
var info = this.popupInfo(options.domNode);
// Cancel any higher level popups
this.cancel(info.popupLevel);
// Store the popup details if not already there
if(this.findPopup(options.title) === -1) {
this.popups.push({
title: options.title,
wiki: options.wiki,
domNode: options.domNode
});
}
// Set the state tiddler
options.wiki.setTextReference(options.title,
"(" + options.domNode.offsetLeft + "," + options.domNode.offsetTop + "," +
options.domNode.offsetWidth + "," + options.domNode.offsetHeight + ")");
// Add the click handler if we have any popups
if(this.popups.length > 0) {
this.rootElement.addEventListener("click",this,true);
}
};
/*
Cancel all popups at or above a specified level or DOM node
level: popup level to cancel (0 cancels all popups)
*/
Popup.prototype.cancel = function(level) {
var numPopups = this.popups.length;
level = Math.max(0,Math.min(level,numPopups));
for(var t=level; t<numPopups; t++) {
var popup = this.popups.pop();
if(popup.title) {
popup.wiki.deleteTiddler(popup.title);
}
}
if(this.popups.length === 0) {
this.rootElement.removeEventListener("click",this,false);
}
};
/*
Returns true if the specified title and text identifies an active popup
*/
Popup.prototype.readPopupState = function(text) {
var popupLocationRegExp = /^\((-?[0-9\.E]+),(-?[0-9\.E]+),(-?[0-9\.E]+),(-?[0-9\.E]+)\)$/;
return popupLocationRegExp.test(text);
};
exports.Popup = Popup;
})();
/*\
title: $:/core/modules/utils/dom/scroller.js
type: application/javascript
module-type: utils
Module that creates a $tw.utils.Scroller object prototype that manages scrolling in the browser
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Event handler for when the `tm-scroll` event hits the document body
*/
var PageScroller = function() {
this.idRequestFrame = null;
this.requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) {
return window.setTimeout(callback, 1000/60);
};
this.cancelAnimationFrame = window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
function(id) {
window.clearTimeout(id);
};
};
PageScroller.prototype.cancelScroll = function() {
if(this.idRequestFrame) {
this.cancelAnimationFrame.call(window,this.idRequestFrame);
this.idRequestFrame = null;
}
};
/*
Handle an event
*/
PageScroller.prototype.handleEvent = function(event) {
if(event.type === "tm-scroll") {
return this.scrollIntoView(event.target);
}
return true;
};
/*
Handle a scroll event hitting the page document
*/
PageScroller.prototype.scrollIntoView = function(element) {
var duration = $tw.utils.getAnimationDuration();
// Now get ready to scroll the body
this.cancelScroll();
this.startTime = Date.now();
var scrollPosition = $tw.utils.getScrollPosition();
// Get the client bounds of the element and adjust by the scroll position
var clientBounds = element.getBoundingClientRect(),
bounds = {
left: clientBounds.left + scrollPosition.x,
top: clientBounds.top + scrollPosition.y,
width: clientBounds.width,
height: clientBounds.height
};
// We'll consider the horizontal and vertical scroll directions separately via this function
// targetPos/targetSize - position and size of the target element
// currentPos/currentSize - position and size of the current scroll viewport
// returns: new position of the scroll viewport
var getEndPos = function(targetPos,targetSize,currentPos,currentSize) {
var newPos = currentPos;
// If the target is above/left of the current view, then scroll to it's top/left
if(targetPos <= currentPos) {
newPos = targetPos;
// If the target is smaller than the window and the scroll position is too far up, then scroll till the target is at the bottom of the window
} else if(targetSize < currentSize && currentPos < (targetPos + targetSize - currentSize)) {
newPos = targetPos + targetSize - currentSize;
// If the target is big, then just scroll to the top
} else if(currentPos < targetPos) {
newPos = targetPos;
// Otherwise, stay where we are
} else {
newPos = currentPos;
}
// If we are scrolling within 50 pixels of the top/left then snap to zero
if(newPos < 50) {
newPos = 0;
}
return newPos;
},
endX = getEndPos(bounds.left,bounds.width,scrollPosition.x,window.innerWidth),
endY = getEndPos(bounds.top,bounds.height,scrollPosition.y,window.innerHeight);
// Only scroll if the position has changed
if(endX !== scrollPosition.x || endY !== scrollPosition.y) {
var self = this,
drawFrame;
drawFrame = function () {
var t;
if(duration <= 0) {
t = 1;
} else {
t = ((Date.now()) - self.startTime) / duration;
}
if(t >= 1) {
self.cancelScroll();
t = 1;
}
t = $tw.utils.slowInSlowOut(t);
window.scrollTo(scrollPosition.x + (endX - scrollPosition.x) * t,scrollPosition.y + (endY - scrollPosition.y) * t);
if(t < 1) {
self.idRequestFrame = self.requestAnimationFrame.call(window,drawFrame);
}
};
drawFrame();
}
};
exports.PageScroller = PageScroller;
})();
/*\
title: $:/core/modules/utils/edition-info.js
type: application/javascript
module-type: utils-node
Information about the available editions
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var fs = require("fs"),
path = require("path");
var editionInfo;
exports.getEditionInfo = function() {
if(!editionInfo) {
// Enumerate the edition paths
var editionPaths = $tw.getLibraryItemSearchPaths($tw.config.editionsPath,$tw.config.editionsEnvVar);
editionInfo = {};
for(var editionIndex=0; editionIndex<editionPaths.length; editionIndex++) {
var editionPath = editionPaths[editionIndex];
// Enumerate the folders
var entries = fs.readdirSync(editionPath);
for(var entryIndex=0; entryIndex<entries.length; entryIndex++) {
var entry = entries[entryIndex];
// Check if directories have a valid tiddlywiki.info
if(!editionInfo[entry] && $tw.utils.isDirectory(path.resolve(editionPath,entry))) {
var info;
try {
info = JSON.parse(fs.readFileSync(path.resolve(editionPath,entry,"tiddlywiki.info"),"utf8"));
} catch(ex) {
}
if(info) {
editionInfo[entry] = info;
}
}
}
}
}
return editionInfo;
};
})();
/*\
title: $:/core/modules/utils/fakedom.js
type: application/javascript
module-type: global
A barebones implementation of DOM interfaces needed by the rendering mechanism.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Sequence number used to enable us to track objects for testing
var sequenceNumber = null;
var bumpSequenceNumber = function(object) {
if(sequenceNumber !== null) {
object.sequenceNumber = sequenceNumber++;
}
};
var TW_TextNode = function(text) {
bumpSequenceNumber(this);
this.textContent = text;
};
Object.defineProperty(TW_TextNode.prototype, "nodeType", {
get: function() {
return 3;
}
});
Object.defineProperty(TW_TextNode.prototype, "formattedTextContent", {
get: function() {
return this.textContent.replace(/(\r?\n)/g,"");
}
});
var TW_Element = function(tag,namespace) {
bumpSequenceNumber(this);
this.isTiddlyWikiFakeDom = true;
this.tag = tag;
this.attributes = {};
this.isRaw = false;
this.children = [];
this.style = {};
this.namespaceURI = namespace || "http://www.w3.org/1999/xhtml";
};
Object.defineProperty(TW_Element.prototype, "nodeType", {
get: function() {
return 1;
}
});
TW_Element.prototype.getAttribute = function(name) {
if(this.isRaw) {
throw "Cannot getAttribute on a raw TW_Element";
}
return this.attributes[name];
};
TW_Element.prototype.setAttribute = function(name,value) {
if(this.isRaw) {
throw "Cannot setAttribute on a raw TW_Element";
}
this.attributes[name] = value;
};
TW_Element.prototype.setAttributeNS = function(namespace,name,value) {
this.setAttribute(name,value);
};
TW_Element.prototype.removeAttribute = function(name) {
if(this.isRaw) {
throw "Cannot removeAttribute on a raw TW_Element";
}
if($tw.utils.hop(this.attributes,name)) {
delete this.attributes[name];
}
};
TW_Element.prototype.appendChild = function(node) {
this.children.push(node);
node.parentNode = this;
};
TW_Element.prototype.insertBefore = function(node,nextSibling) {
if(nextSibling) {
var p = this.children.indexOf(nextSibling);
if(p !== -1) {
this.children.splice(p,0,node);
node.parentNode = this;
} else {
this.appendChild(node);
}
} else {
this.appendChild(node);
}
};
TW_Element.prototype.removeChild = function(node) {
var p = this.children.indexOf(node);
if(p !== -1) {
this.children.splice(p,1);
}
};
TW_Element.prototype.hasChildNodes = function() {
return !!this.children.length;
};
Object.defineProperty(TW_Element.prototype, "childNodes", {
get: function() {
return this.children;
}
});
Object.defineProperty(TW_Element.prototype, "firstChild", {
get: function() {
return this.children[0];
}
});
TW_Element.prototype.addEventListener = function(type,listener,useCapture) {
// Do nothing
};
Object.defineProperty(TW_Element.prototype, "tagName", {
get: function() {
return this.tag || "";
}
});
Object.defineProperty(TW_Element.prototype, "className", {
get: function() {
return this.attributes["class"] || "";
},
set: function(value) {
this.attributes["class"] = value;
}
});
Object.defineProperty(TW_Element.prototype, "value", {
get: function() {
return this.attributes.value || "";
},
set: function(value) {
this.attributes.value = value;
}
});
Object.defineProperty(TW_Element.prototype, "outerHTML", {
get: function() {
var output = [],attr,a,v;
output.push("<",this.tag);
if(this.attributes) {
attr = [];
for(a in this.attributes) {
attr.push(a);
}
attr.sort();
for(a=0; a<attr.length; a++) {
v = this.attributes[attr[a]];
if(v !== undefined) {
output.push(" ",attr[a],"=\"",$tw.utils.htmlEncode(v),"\"");
}
}
}
if(this.style) {
var style = [];
for(var s in this.style) {
style.push(s + ":" + this.style[s] + ";");
}
if(style.length > 0) {
output.push(" style=\"",style.join(""),"\"")
}
}
output.push(">");
if($tw.config.htmlVoidElements.indexOf(this.tag) === -1) {
output.push(this.innerHTML);
output.push("</",this.tag,">");
}
return output.join("");
}
});
Object.defineProperty(TW_Element.prototype, "innerHTML", {
get: function() {
if(this.isRaw) {
return this.rawHTML;
} else {
var b = [],self = this;
$tw.utils.each(this.children,function(node) {
if(node instanceof TW_Element) {
b.push(node.outerHTML);
} else if(node instanceof TW_TextNode) {
if (self.tag === "script") {
b.push(node.textContent);
} else {
b.push($tw.utils.htmlEncode(node.textContent));
}
}
});
return b.join("");
}
},
set: function(value) {
this.isRaw = true;
this.rawHTML = value;
}
});
Object.defineProperty(TW_Element.prototype, "textContent", {
get: function() {
if(this.isRaw) {
throw "Cannot get textContent on a raw TW_Element";
} else {
var b = [];
$tw.utils.each(this.children,function(node) {
b.push(node.textContent);
});
return b.join("");
}
},
set: function(value) {
this.children = [new TW_TextNode(value)];
}
});
Object.defineProperty(TW_Element.prototype, "formattedTextContent", {
get: function() {
if(this.isRaw) {
throw "Cannot get formattedTextContent on a raw TW_Element";
} else {
var b = [],
isBlock = $tw.config.htmlBlockElements.indexOf(this.tag) !== -1;
if(isBlock) {
b.push("\n");
}
if(this.tag === "li") {
b.push("* ");
}
$tw.utils.each(this.children,function(node) {
b.push(node.formattedTextContent);
});
if(isBlock) {
b.push("\n");
}
return b.join("");
}
}
});
var document = {
setSequenceNumber: function(value) {
sequenceNumber = value;
},
createElementNS: function(namespace,tag) {
return new TW_Element(tag,namespace);
},
createElement: function(tag) {
return new TW_Element(tag);
},
createTextNode: function(text) {
return new TW_TextNode(text);
},
compatMode: "CSS1Compat", // For KaTeX to know that we're not a browser in quirks mode
isTiddlyWikiFakeDom: true
};
exports.fakeDocument = document;
})();
/*\
title: $:/core/modules/utils/filesystem.js
type: application/javascript
module-type: utils-node
File system utilities
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var fs = require("fs"),
path = require("path");
/*
Recursively (and synchronously) copy a directory and all its content
*/
exports.copyDirectory = function(srcPath,dstPath) {
// Remove any trailing path separators
srcPath = $tw.utils.removeTrailingSeparator(srcPath);
dstPath = $tw.utils.removeTrailingSeparator(dstPath);
// Create the destination directory
var err = $tw.utils.createDirectory(dstPath);
if(err) {
return err;
}
// Function to copy a folder full of files
var copy = function(srcPath,dstPath) {
var srcStats = fs.lstatSync(srcPath),
dstExists = fs.existsSync(dstPath);
if(srcStats.isFile()) {
$tw.utils.copyFile(srcPath,dstPath);
} else if(srcStats.isDirectory()) {
var items = fs.readdirSync(srcPath);
for(var t=0; t<items.length; t++) {
var item = items[t],
err = copy(srcPath + path.sep + item,dstPath + path.sep + item);
if(err) {
return err;
}
}
}
};
copy(srcPath,dstPath);
return null;
};
/*
Copy a file
*/
var FILE_BUFFER_LENGTH = 64 * 1024,
fileBuffer;
exports.copyFile = function(srcPath,dstPath) {
// Create buffer if required
if(!fileBuffer) {
fileBuffer = new Buffer(FILE_BUFFER_LENGTH);
}
// Create any directories in the destination
$tw.utils.createDirectory(path.dirname(dstPath));
// Copy the file
var srcFile = fs.openSync(srcPath,"r"),
dstFile = fs.openSync(dstPath,"w"),
bytesRead = 1,
pos = 0;
while (bytesRead > 0) {
bytesRead = fs.readSync(srcFile,fileBuffer,0,FILE_BUFFER_LENGTH,pos);
fs.writeSync(dstFile,fileBuffer,0,bytesRead);
pos += bytesRead;
}
fs.closeSync(srcFile);
fs.closeSync(dstFile);
return null;
};
/*
Remove trailing path separator
*/
exports.removeTrailingSeparator = function(dirPath) {
var len = dirPath.length;
if(dirPath.charAt(len-1) === path.sep) {
dirPath = dirPath.substr(0,len-1);
}
return dirPath;
};
/*
Recursively create a directory
*/
exports.createDirectory = function(dirPath) {
if(dirPath.substr(dirPath.length-1,1) !== path.sep) {
dirPath = dirPath + path.sep;
}
var pos = 1;
pos = dirPath.indexOf(path.sep,pos);
while(pos !== -1) {
var subDirPath = dirPath.substr(0,pos);
if(!$tw.utils.isDirectory(subDirPath)) {
try {
fs.mkdirSync(subDirPath);
} catch(e) {
return "Error creating directory '" + subDirPath + "'";
}
}
pos = dirPath.indexOf(path.sep,pos + 1);
}
return null;
};
/*
Recursively create directories needed to contain a specified file
*/
exports.createFileDirectories = function(filePath) {
return $tw.utils.createDirectory(path.dirname(filePath));
};
/*
Recursively delete a directory
*/
exports.deleteDirectory = function(dirPath) {
if(fs.existsSync(dirPath)) {
var entries = fs.readdirSync(dirPath);
for(var entryIndex=0; entryIndex<entries.length; entryIndex++) {
var currPath = dirPath + path.sep + entries[entryIndex];
if(fs.lstatSync(currPath).isDirectory()) {
$tw.utils.deleteDirectory(currPath);
} else {
fs.unlinkSync(currPath);
}
}
fs.rmdirSync(dirPath);
}
return null;
};
/*
Check if a path identifies a directory
*/
exports.isDirectory = function(dirPath) {
return fs.existsSync(dirPath) && fs.statSync(dirPath).isDirectory();
};
/*
Check if a path identifies a directory that is empty
*/
exports.isDirectoryEmpty = function(dirPath) {
if(!$tw.utils.isDirectory(dirPath)) {
return false;
}
var files = fs.readdirSync(dirPath),
empty = true;
$tw.utils.each(files,function(file,index) {
if(file.charAt(0) !== ".") {
empty = false;
}
});
return empty;
};
})();
/*\
title: $:/core/modules/utils/logger.js
type: application/javascript
module-type: utils
A basic logging implementation
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var ALERT_TAG = "$:/tags/Alert";
/*
Make a new logger
*/
function Logger(componentName) {
this.componentName = componentName || "";
}
/*
Log a message
*/
Logger.prototype.log = function(/* args */) {
if(console !== undefined && console.log !== undefined) {
return Function.apply.call(console.log, console, [this.componentName + ":"].concat(Array.prototype.slice.call(arguments,0)));
}
};
/*
Alert a message
*/
Logger.prototype.alert = function(/* args */) {
// Prepare the text of the alert
var text = Array.prototype.join.call(arguments," ");
// Create alert tiddlers in the browser
if($tw.browser) {
// Check if there is an existing alert with the same text and the same component
var existingAlerts = $tw.wiki.getTiddlersWithTag(ALERT_TAG),
alertFields,
existingCount,
self = this;
$tw.utils.each(existingAlerts,function(title) {
var tiddler = $tw.wiki.getTiddler(title);
if(tiddler.fields.text === text && tiddler.fields.component === self.componentName && tiddler.fields.modified && (!alertFields || tiddler.fields.modified < alertFields.modified)) {
alertFields = $tw.utils.extend({},tiddler.fields);
}
});
if(alertFields) {
existingCount = alertFields.count || 1;
} else {
alertFields = {
title: $tw.wiki.generateNewTitle("$:/temp/alerts/alert",{prefix: ""}),
text: text,
tags: [ALERT_TAG],
component: this.componentName
};
existingCount = 0;
}
alertFields.modified = new Date();
if(++existingCount > 1) {
alertFields.count = existingCount;
} else {
alertFields.count = undefined;
}
$tw.wiki.addTiddler(new $tw.Tiddler(alertFields));
// Log the alert as well
this.log.apply(this,Array.prototype.slice.call(arguments,0));
} else {
// Print an orange message to the console if not in the browser
console.error("\x1b[1;33m" + text + "\x1b[0m");
}
};
exports.Logger = Logger;
})();
/*\
title: $:/core/modules/utils/parsetree.js
type: application/javascript
module-type: utils
Parse tree utility functions.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.addAttributeToParseTreeNode = function(node,name,value) {
node.attributes = node.attributes || {};
node.attributes[name] = {type: "string", value: value};
};
exports.getAttributeValueFromParseTreeNode = function(node,name,defaultValue) {
if(node.attributes && node.attributes[name] && node.attributes[name].value !== undefined) {
return node.attributes[name].value;
}
return defaultValue;
};
exports.addClassToParseTreeNode = function(node,classString) {
var classes = [];
node.attributes = node.attributes || {};
node.attributes["class"] = node.attributes["class"] || {type: "string", value: ""};
if(node.attributes["class"].type === "string") {
if(node.attributes["class"].value !== "") {
classes = node.attributes["class"].value.split(" ");
}
if(classString !== "") {
$tw.utils.pushTop(classes,classString.split(" "));
}
node.attributes["class"].value = classes.join(" ");
}
};
exports.addStyleToParseTreeNode = function(node,name,value) {
node.attributes = node.attributes || {};
node.attributes.style = node.attributes.style || {type: "string", value: ""};
if(node.attributes.style.type === "string") {
node.attributes.style.value += name + ":" + value + ";";
}
};
exports.findParseTreeNode = function(nodeArray,search) {
for(var t=0; t<nodeArray.length; t++) {
if(nodeArray[t].type === search.type && nodeArray[t].tag === search.tag) {
return nodeArray[t];
}
}
return undefined;
};
/*
Helper to get the text of a parse tree node or array of nodes
*/
exports.getParseTreeText = function getParseTreeText(tree) {
var output = [];
if($tw.utils.isArray(tree)) {
$tw.utils.each(tree,function(node) {
output.push(getParseTreeText(node));
});
} else {
if(tree.type === "text") {
output.push(tree.text);
}
if(tree.children) {
return getParseTreeText(tree.children);
}
}
return output.join("");
};
})();
/*\
title: $:/core/modules/utils/parseutils.js
type: application/javascript
module-type: utils
Utility functions concerned with parsing text into tokens.
Most functions have the following pattern:
* The parameters are:
** `source`: the source string being parsed
** `pos`: the current parse position within the string
** Any further parameters are used to identify the token that is being parsed
* The return value is:
** null if the token was not found at the specified position
** an object representing the token with the following standard fields:
*** `type`: string indicating the type of the token
*** `start`: start position of the token in the source string
*** `end`: end position of the token in the source string
*** Any further fields required to describe the token
The exception is `skipWhiteSpace`, which just returns the position after the whitespace.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Look for a whitespace token. Returns null if not found, otherwise returns {type: "whitespace", start:, end:,}
*/
exports.parseWhiteSpace = function(source,pos) {
var p = pos,c;
while(true) {
c = source.charAt(p);
if((c === " ") || (c === "\f") || (c === "\n") || (c === "\r") || (c === "\t") || (c === "\v") || (c === "\u00a0")) { // Ignores some obscure unicode spaces
p++;
} else {
break;
}
}
if(p === pos) {
return null;
} else {
return {
type: "whitespace",
start: pos,
end: p
}
}
};
/*
Convenience wrapper for parseWhiteSpace. Returns the position after the whitespace
*/
exports.skipWhiteSpace = function(source,pos) {
var c;
while(true) {
c = source.charAt(pos);
if((c === " ") || (c === "\f") || (c === "\n") || (c === "\r") || (c === "\t") || (c === "\v") || (c === "\u00a0")) { // Ignores some obscure unicode spaces
pos++;
} else {
return pos;
}
}
};
/*
Look for a given string token. Returns null if not found, otherwise returns {type: "token", value:, start:, end:,}
*/
exports.parseTokenString = function(source,pos,token) {
var match = source.indexOf(token,pos) === pos;
if(match) {
return {
type: "token",
value: token,
start: pos,
end: pos + token.length
};
}
return null;
};
/*
Look for a token matching a regex. Returns null if not found, otherwise returns {type: "regexp", match:, start:, end:,}
*/
exports.parseTokenRegExp = function(source,pos,reToken) {
var node = {
type: "regexp",
start: pos
};
reToken.lastIndex = pos;
node.match = reToken.exec(source);
if(node.match && node.match.index === pos) {
node.end = pos + node.match[0].length;
return node;
} else {
return null;
}
};
/*
Look for a string literal. Returns null if not found, otherwise returns {type: "string", value:, start:, end:,}
*/
exports.parseStringLiteral = function(source,pos) {
var node = {
type: "string",
start: pos
};
var reString = /(?:"""([\s\S]*?)"""|"([^"]*)")|(?:'([^']*)')/g;
reString.lastIndex = pos;
var match = reString.exec(source);
if(match && match.index === pos) {
node.value = match[1] !== undefined ? match[1] :(
match[2] !== undefined ? match[2] : match[3]
);
node.end = pos + match[0].length;
return node;
} else {
return null;
}
};
/*
Look for a macro invocation parameter. Returns null if not found, or {type: "macro-parameter", name:, value:, start:, end:}
*/
exports.parseMacroParameter = function(source,pos) {
var node = {
type: "macro-parameter",
start: pos
};
// Define our regexp
var reMacroParameter = /(?:([A-Za-z0-9\-_]+)\s*:)?(?:\s*(?:"""([\s\S]*?)"""|"([^"]*)"|'([^']*)'|\[\[([^\]]*)\]\]|([^\s>"'=]+)))/g;
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for the parameter
var token = $tw.utils.parseTokenRegExp(source,pos,reMacroParameter);
if(!token) {
return null;
}
pos = token.end;
// Get the parameter details
node.value = token.match[2] !== undefined ? token.match[2] : (
token.match[3] !== undefined ? token.match[3] : (
token.match[4] !== undefined ? token.match[4] : (
token.match[5] !== undefined ? token.match[5] : (
token.match[6] !== undefined ? token.match[6] : (
""
)
)
)
)
);
if(token.match[1]) {
node.name = token.match[1];
}
// Update the end position
node.end = pos;
return node;
};
/*
Look for a macro invocation. Returns null if not found, or {type: "macrocall", name:, parameters:, start:, end:}
*/
exports.parseMacroInvocation = function(source,pos) {
var node = {
type: "macrocall",
start: pos,
params: []
};
// Define our regexps
var reMacroName = /([^\s>"'=]+)/g;
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for a double less than sign
var token = $tw.utils.parseTokenString(source,pos,"<<");
if(!token) {
return null;
}
pos = token.end;
// Get the macro name
var name = $tw.utils.parseTokenRegExp(source,pos,reMacroName);
if(!name) {
return null;
}
node.name = name.match[1];
pos = name.end;
// Process parameters
var parameter = $tw.utils.parseMacroParameter(source,pos);
while(parameter) {
node.params.push(parameter);
pos = parameter.end;
// Get the next parameter
parameter = $tw.utils.parseMacroParameter(source,pos);
}
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for a double greater than sign
token = $tw.utils.parseTokenString(source,pos,">>");
if(!token) {
return null;
}
pos = token.end;
// Update the end position
node.end = pos;
return node;
};
/*
Look for an HTML attribute definition. Returns null if not found, otherwise returns {type: "attribute", name:, valueType: "string|indirect|macro", value:, start:, end:,}
*/
exports.parseAttribute = function(source,pos) {
var node = {
start: pos
};
// Define our regexps
var reAttributeName = /([^\/\s>"'=]+)/g,
reUnquotedAttribute = /([^\/\s<>"'=]+)/g,
reIndirectValue = /\{\{([^\}]+)\}\}/g;
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Get the attribute name
var name = $tw.utils.parseTokenRegExp(source,pos,reAttributeName);
if(!name) {
return null;
}
node.name = name.match[1];
pos = name.end;
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for an equals sign
var token = $tw.utils.parseTokenString(source,pos,"=");
if(token) {
pos = token.end;
// Skip whitespace
pos = $tw.utils.skipWhiteSpace(source,pos);
// Look for a string literal
var stringLiteral = $tw.utils.parseStringLiteral(source,pos);
if(stringLiteral) {
pos = stringLiteral.end;
node.type = "string";
node.value = stringLiteral.value;
} else {
// Look for an indirect value
var indirectValue = $tw.utils.parseTokenRegExp(source,pos,reIndirectValue);
if(indirectValue) {
pos = indirectValue.end;
node.type = "indirect";
node.textReference = indirectValue.match[1];
} else {
// Look for a unquoted value
var unquotedValue = $tw.utils.parseTokenRegExp(source,pos,reUnquotedAttribute);
if(unquotedValue) {
pos = unquotedValue.end;
node.type = "string";
node.value = unquotedValue.match[1];
} else {
// Look for a macro invocation value
var macroInvocation = $tw.utils.parseMacroInvocation(source,pos);
if(macroInvocation) {
pos = macroInvocation.end;
node.type = "macro";
node.value = macroInvocation;
} else {
node.type = "string";
node.value = "true";
}
}
}
}
} else {
node.type = "string";
node.value = "true";
}
// Update the end position
node.end = pos;
return node;
};
})();
/*\
title: $:/core/modules/utils/performance.js
type: application/javascript
module-type: global
Performance measurement.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
function Performance(enabled) {
this.enabled = !!enabled;
this.measures = {}; // Hashmap of current values of measurements
this.logger = new $tw.utils.Logger("performance");
}
/*
Wrap performance reporting around a top level function
*/
Performance.prototype.report = function(name,fn) {
var self = this;
if(this.enabled) {
return function() {
self.measures = {};
var startTime = $tw.utils.timer(),
result = fn.apply(this,arguments);
self.logger.log(name + ": " + $tw.utils.timer(startTime).toFixed(2) + "ms");
for(var m in self.measures) {
self.logger.log("+" + m + ": " + self.measures[m].toFixed(2) + "ms");
}
return result;
};
} else {
return fn;
}
};
/*
Wrap performance measurements around a subfunction
*/
Performance.prototype.measure = function(name,fn) {
var self = this;
if(this.enabled) {
return function() {
var startTime = $tw.utils.timer(),
result = fn.apply(this,arguments),
value = self.measures[name] || 0;
self.measures[name] = value + $tw.utils.timer(startTime);
return result;
};
} else {
return fn;
}
};
exports.Performance = Performance;
})();
/*\
title: $:/core/modules/utils/pluginmaker.js
type: application/javascript
module-type: utils
A quick and dirty way to pack up plugins within the browser.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Repack a plugin, and then delete any non-shadow payload tiddlers
*/
exports.repackPlugin = function(title,additionalTiddlers,excludeTiddlers) {
additionalTiddlers = additionalTiddlers || [];
excludeTiddlers = excludeTiddlers || [];
// Get the plugin tiddler
var pluginTiddler = $tw.wiki.getTiddler(title);
if(!pluginTiddler) {
throw "No such tiddler as " + title;
}
// Extract the JSON
var jsonPluginTiddler;
try {
jsonPluginTiddler = JSON.parse(pluginTiddler.fields.text);
} catch(e) {
throw "Cannot parse plugin tiddler " + title + "\nError: " + e;
}
// Get the list of tiddlers
var tiddlers = Object.keys(jsonPluginTiddler.tiddlers);
// Add the additional tiddlers
$tw.utils.pushTop(tiddlers,additionalTiddlers);
// Remove any excluded tiddlers
for(var t=tiddlers.length-1; t>=0; t--) {
if(excludeTiddlers.indexOf(tiddlers[t]) !== -1) {
tiddlers.splice(t,1);
}
}
// Pack up the tiddlers into a block of JSON
var plugins = {};
$tw.utils.each(tiddlers,function(title) {
var tiddler = $tw.wiki.getTiddler(title),
fields = {};
$tw.utils.each(tiddler.fields,function (value,name) {
fields[name] = tiddler.getFieldString(name);
});
plugins[title] = fields;
});
// Retrieve and bump the version number
var pluginVersion = $tw.utils.parseVersion(pluginTiddler.getFieldString("version") || "0.0.0") || {
major: "0",
minor: "0",
patch: "0"
};
pluginVersion.patch++;
var version = pluginVersion.major + "." + pluginVersion.minor + "." + pluginVersion.patch;
if(pluginVersion.prerelease) {
version += "-" + pluginVersion.prerelease;
}
if(pluginVersion.build) {
version += "+" + pluginVersion.build;
}
// Save the tiddler
$tw.wiki.addTiddler(new $tw.Tiddler(pluginTiddler,{text: JSON.stringify({tiddlers: plugins},null,4), version: version}));
// Delete any non-shadow constituent tiddlers
$tw.utils.each(tiddlers,function(title) {
if($tw.wiki.tiddlerExists(title)) {
$tw.wiki.deleteTiddler(title);
}
});
// Trigger an autosave
$tw.rootWidget.dispatchEvent({type: "tm-auto-save-wiki"});
// Return a heartwarming confirmation
return "Plugin " + title + " successfully saved";
};
})();
/*\
title: $:/core/modules/utils/utils.js
type: application/javascript
module-type: utils
Various static utility functions.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Display a warning, in colour if we're on a terminal
*/
exports.warning = function(text) {
console.log($tw.node ? "\x1b[1;33m" + text + "\x1b[0m" : text);
}
/*
Trim whitespace from the start and end of a string
Thanks to Steven Levithan, http://blog.stevenlevithan.com/archives/faster-trim-javascript
*/
exports.trim = function(str) {
if(typeof str === "string") {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
} else {
return str;
}
};
/*
Return the number of keys in an object
*/
exports.count = function(object) {
return Object.keys(object || {}).length;
};
/*
Check if an array is equal by value and by reference.
*/
exports.isArrayEqual = function(array1,array2) {
if(array1 === array2) {
return true;
}
array1 = array1 || [];
array2 = array2 || [];
if(array1.length !== array2.length) {
return false;
}
return array1.every(function(value,index) {
return value === array2[index];
});
};
/*
Push entries onto an array, removing them first if they already exist in the array
array: array to modify (assumed to be free of duplicates)
value: a single value to push or an array of values to push
*/
exports.pushTop = function(array,value) {
var t,p;
if($tw.utils.isArray(value)) {
// Remove any array entries that are duplicated in the new values
if(value.length !== 0) {
if(array.length !== 0) {
if(value.length < array.length) {
for(t=0; t<value.length; t++) {
p = array.indexOf(value[t]);
if(p !== -1) {
array.splice(p,1);
}
}
} else {
for(t=array.length-1; t>=0; t--) {
p = value.indexOf(array[t]);
if(p !== -1) {
array.splice(t,1);
}
}
}
}
// Push the values on top of the main array
array.push.apply(array,value);
}
} else {
p = array.indexOf(value);
if(p !== -1) {
array.splice(p,1);
}
array.push(value);
}
return array;
};
/*
Remove entries from an array
array: array to modify
value: a single value to remove, or an array of values to remove
*/
exports.removeArrayEntries = function(array,value) {
var t,p;
if($tw.utils.isArray(value)) {
for(t=0; t<value.length; t++) {
p = array.indexOf(value[t]);
if(p !== -1) {
array.splice(p,1);
}
}
} else {
p = array.indexOf(value);
if(p !== -1) {
array.splice(p,1);
}
}
};
/*
Check whether any members of a hashmap are present in another hashmap
*/
exports.checkDependencies = function(dependencies,changes) {
var hit = false;
$tw.utils.each(changes,function(change,title) {
if($tw.utils.hop(dependencies,title)) {
hit = true;
}
});
return hit;
};
exports.extend = function(object /* [, src] */) {
$tw.utils.each(Array.prototype.slice.call(arguments, 1), function(source) {
if(source) {
for(var property in source) {
object[property] = source[property];
}
}
});
return object;
};
exports.deepCopy = function(object) {
var result,t;
if($tw.utils.isArray(object)) {
// Copy arrays
result = object.slice(0);
} else if(typeof object === "object") {
result = {};
for(t in object) {
if(object[t] !== undefined) {
result[t] = $tw.utils.deepCopy(object[t]);
}
}
} else {
result = object;
}
return result;
};
exports.extendDeepCopy = function(object,extendedProperties) {
var result = $tw.utils.deepCopy(object),t;
for(t in extendedProperties) {
if(extendedProperties[t] !== undefined) {
result[t] = $tw.utils.deepCopy(extendedProperties[t]);
}
}
return result;
};
exports.deepFreeze = function deepFreeze(object) {
var property, key;
Object.freeze(object);
for(key in object) {
property = object[key];
if($tw.utils.hop(object,key) && (typeof property === "object") && !Object.isFrozen(property)) {
deepFreeze(property);
}
}
};
exports.slowInSlowOut = function(t) {
return (1 - ((Math.cos(t * Math.PI) + 1) / 2));
};
exports.formatDateString = function(date,template) {
var result = "",
t = template,
matches = [
[/^0hh12/, function() {
return $tw.utils.pad($tw.utils.getHours12(date));
}],
[/^wYYYY/, function() {
return $tw.utils.getYearForWeekNo(date);
}],
[/^hh12/, function() {
return $tw.utils.getHours12(date);
}],
[/^DDth/, function() {
return date.getDate() + $tw.utils.getDaySuffix(date);
}],
[/^YYYY/, function() {
return date.getFullYear();
}],
[/^0hh/, function() {
return $tw.utils.pad(date.getHours());
}],
[/^0mm/, function() {
return $tw.utils.pad(date.getMinutes());
}],
[/^0ss/, function() {
return $tw.utils.pad(date.getSeconds());
}],
[/^0DD/, function() {
return $tw.utils.pad(date.getDate());
}],
[/^0MM/, function() {
return $tw.utils.pad(date.getMonth()+1);
}],
[/^0WW/, function() {
return $tw.utils.pad($tw.utils.getWeek(date));
}],
[/^ddd/, function() {
return $tw.language.getString("Date/Short/Day/" + date.getDay());
}],
[/^mmm/, function() {
return $tw.language.getString("Date/Short/Month/" + (date.getMonth() + 1));
}],
[/^DDD/, function() {
return $tw.language.getString("Date/Long/Day/" + date.getDay());
}],
[/^MMM/, function() {
return $tw.language.getString("Date/Long/Month/" + (date.getMonth() + 1));
}],
[/^TZD/, function() {
var tz = date.getTimezoneOffset(),
atz = Math.abs(tz);
return (tz < 0 ? '+' : '-') + $tw.utils.pad(Math.floor(atz / 60)) + ':' + $tw.utils.pad(atz % 60);
}],
[/^wYY/, function() {
return $tw.utils.pad($tw.utils.getYearForWeekNo(date) - 2000);
}],
[/^[ap]m/, function() {
return $tw.utils.getAmPm(date).toLowerCase();
}],
[/^hh/, function() {
return date.getHours();
}],
[/^mm/, function() {
return date.getMinutes();
}],
[/^ss/, function() {
return date.getSeconds();
}],
[/^[AP]M/, function() {
return $tw.utils.getAmPm(date).toUpperCase();
}],
[/^DD/, function() {
return date.getDate();
}],
[/^MM/, function() {
return date.getMonth() + 1;
}],
[/^WW/, function() {
return $tw.utils.getWeek(date);
}],
[/^YY/, function() {
return $tw.utils.pad(date.getFullYear() - 2000);
}]
];
while(t.length){
var matchString = "";
$tw.utils.each(matches, function(m) {
var match = m[0].exec(t);
if(match) {
matchString = m[1].call();
t = t.substr(match[0].length);
return false;
}
});
if(matchString) {
result += matchString;
} else {
result += t.charAt(0);
t = t.substr(1);
}
}
result = result.replace(/\\(.)/g,"$1");
return result;
};
exports.getAmPm = function(date) {
return $tw.language.getString("Date/Period/" + (date.getHours() >= 12 ? "pm" : "am"));
};
exports.getDaySuffix = function(date) {
return $tw.language.getString("Date/DaySuffix/" + date.getDate());
};
exports.getWeek = function(date) {
var dt = new Date(date.getTime());
var d = dt.getDay();
if(d === 0) {
d = 7; // JavaScript Sun=0, ISO Sun=7
}
dt.setTime(dt.getTime() + (4 - d) * 86400000);// shift day to Thurs of same week to calculate weekNo
var n = Math.floor((dt.getTime()-new Date(dt.getFullYear(),0,1) + 3600000) / 86400000);
return Math.floor(n / 7) + 1;
};
exports.getYearForWeekNo = function(date) {
var dt = new Date(date.getTime());
var d = dt.getDay();
if(d === 0) {
d = 7; // JavaScript Sun=0, ISO Sun=7
}
dt.setTime(dt.getTime() + (4 - d) * 86400000);// shift day to Thurs of same week
return dt.getFullYear();
};
exports.getHours12 = function(date) {
var h = date.getHours();
return h > 12 ? h-12 : ( h > 0 ? h : 12 );
};
/*
Convert a date delta in milliseconds into a string representation of "23 seconds ago", "27 minutes ago" etc.
delta: delta in milliseconds
Returns an object with these members:
description: string describing the delta period
updatePeriod: time in millisecond until the string will be inaccurate
*/
exports.getRelativeDate = function(delta) {
var futurep = false;
if(delta < 0) {
delta = -1 * delta;
futurep = true;
}
var units = [
{name: "Years", duration: 365 * 24 * 60 * 60 * 1000},
{name: "Months", duration: (365/12) * 24 * 60 * 60 * 1000},
{name: "Days", duration: 24 * 60 * 60 * 1000},
{name: "Hours", duration: 60 * 60 * 1000},
{name: "Minutes", duration: 60 * 1000},
{name: "Seconds", duration: 1000}
];
for(var t=0; t<units.length; t++) {
var result = Math.floor(delta / units[t].duration);
if(result >= 2) {
return {
delta: delta,
description: $tw.language.getString(
"RelativeDate/" + (futurep ? "Future" : "Past") + "/" + units[t].name,
{variables:
{period: result.toString()}
}
),
updatePeriod: units[t].duration
};
}
}
return {
delta: delta,
description: $tw.language.getString(
"RelativeDate/" + (futurep ? "Future" : "Past") + "/Second",
{variables:
{period: "1"}
}
),
updatePeriod: 1000
};
};
// Convert & to "&", < to "<", > to ">", " to """
exports.htmlEncode = function(s) {
if(s) {
return s.toString().replace(/&/mg,"&").replace(/</mg,"<").replace(/>/mg,">").replace(/\"/mg,""");
} else {
return "";
}
};
// Converts all HTML entities to their character equivalents
exports.entityDecode = function(s) {
var e = s.substr(1,s.length-2); // Strip the & and the ;
if(e.charAt(0) === "#") {
if(e.charAt(1) === "x" || e.charAt(1) === "X") {
return String.fromCharCode(parseInt(e.substr(2),16));
} else {
return String.fromCharCode(parseInt(e.substr(1),10));
}
} else {
var c = $tw.config.htmlEntities[e];
if(c) {
return String.fromCharCode(c);
} else {
return s; // Couldn't convert it as an entity, just return it raw
}
}
};
exports.unescapeLineBreaks = function(s) {
return s.replace(/\\n/mg,"\n").replace(/\\b/mg," ").replace(/\\s/mg,"\\").replace(/\r/mg,"");
};
/*
* Returns an escape sequence for given character. Uses \x for characters <=
* 0xFF to save space, \u for the rest.
*
* The code needs to be in sync with th code template in the compilation
* function for "action" nodes.
*/
// Copied from peg.js, thanks to David Majda
exports.escape = function(ch) {
var charCode = ch.charCodeAt(0);
if(charCode <= 0xFF) {
return '\\x' + $tw.utils.pad(charCode.toString(16).toUpperCase());
} else {
return '\\u' + $tw.utils.pad(charCode.toString(16).toUpperCase(),4);
}
};
// Turns a string into a legal JavaScript string
// Copied from peg.js, thanks to David Majda
exports.stringify = function(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a string
* literal except for the closing quote character, backslash, carriage return,
* line separator, paragraph separator, and line feed. Any character may
* appear in the form of an escape sequence.
*
* For portability, we also escape all non-ASCII characters.
*/
return (s || "")
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // double quote character
.replace(/'/g, "\\'") // single quote character
.replace(/\r/g, '\\r') // carriage return
.replace(/\n/g, '\\n') // line feed
.replace(/[\x80-\uFFFF]/g, exports.escape); // non-ASCII characters
};
/*
Escape the RegExp special characters with a preceding backslash
*/
exports.escapeRegExp = function(s) {
return s.replace(/[\-\/\\\^\$\*\+\?\.\(\)\|\[\]\{\}]/g, '\\$&');
};
// Checks whether a link target is external, i.e. not a tiddler title
exports.isLinkExternal = function(to) {
var externalRegExp = /(?:file|http|https|mailto|ftp|irc|news|data|skype):[^\s<>{}\[\]`|'"\\^~]+(?:\/|\b)/i;
return externalRegExp.test(to);
};
exports.nextTick = function(fn) {
/*global window: false */
if(typeof process === "undefined") {
// Apparently it would be faster to use postMessage - http://dbaron.org/log/20100309-faster-timeouts
window.setTimeout(fn,4);
} else {
process.nextTick(fn);
}
};
/*
Convert a hyphenated CSS property name into a camel case one
*/
exports.unHyphenateCss = function(propName) {
return propName.replace(/-([a-z])/gi, function(match0,match1) {
return match1.toUpperCase();
});
};
/*
Convert a camelcase CSS property name into a dashed one ("backgroundColor" --> "background-color")
*/
exports.hyphenateCss = function(propName) {
return propName.replace(/([A-Z])/g, function(match0,match1) {
return "-" + match1.toLowerCase();
});
};
/*
Parse a text reference of one of these forms:
* title
* !!field
* title!!field
* title##index
* etc
Returns an object with the following fields, all optional:
* title: tiddler title
* field: tiddler field name
* index: JSON property index
*/
exports.parseTextReference = function(textRef) {
// Separate out the title, field name and/or JSON indices
var reTextRef = /(?:(.*?)!!(.+))|(?:(.*?)##(.+))|(.*)/mg,
match = reTextRef.exec(textRef),
result = {};
if(match && reTextRef.lastIndex === textRef.length) {
// Return the parts
if(match[1]) {
result.title = match[1];
}
if(match[2]) {
result.field = match[2];
}
if(match[3]) {
result.title = match[3];
}
if(match[4]) {
result.index = match[4];
}
if(match[5]) {
result.title = match[5];
}
} else {
// If we couldn't parse it
result.title = textRef
}
return result;
};
/*
Checks whether a string is a valid fieldname
*/
exports.isValidFieldName = function(name) {
if(!name || typeof name !== "string") {
return false;
}
name = name.toLowerCase().trim();
var fieldValidatorRegEx = /^[a-z0-9\-\._]+$/mg;
return fieldValidatorRegEx.test(name);
};
/*
Extract the version number from the meta tag or from the boot file
*/
// Browser version
exports.extractVersionInfo = function() {
if($tw.packageInfo) {
return $tw.packageInfo.version;
} else {
var metatags = document.getElementsByTagName("meta");
for(var t=0; t<metatags.length; t++) {
var m = metatags[t];
if(m.name === "tiddlywiki-version") {
return m.content;
}
}
}
return null;
};
/*
Get the animation duration in ms
*/
exports.getAnimationDuration = function() {
return parseInt($tw.wiki.getTiddlerText("$:/config/AnimationDuration","400"),10);
};
/*
Hash a string to a number
Derived from http://stackoverflow.com/a/15710692
*/
exports.hashString = function(str) {
return str.split("").reduce(function(a,b) {
a = ((a << 5) - a) + b.charCodeAt(0);
return a & a;
},0);
};
/*
Decode a base64 string
*/
exports.base64Decode = function(string64) {
if($tw.browser) {
// TODO
throw "$tw.utils.base64Decode() doesn't work in the browser";
} else {
return (new Buffer(string64,"base64")).toString();
}
};
/*
Convert a hashmap into a tiddler dictionary format sequence of name:value pairs
*/
exports.makeTiddlerDictionary = function(data) {
var output = [];
for(var name in data) {
output.push(name + ": " + data[name]);
}
return output.join("\n");
};
/*
High resolution microsecond timer for profiling
*/
exports.timer = function(base) {
var m;
if($tw.node) {
var r = process.hrtime();
m = r[0] * 1e3 + (r[1] / 1e6);
} else if(window.performance) {
m = performance.now();
} else {
m = Date.now();
}
if(typeof base !== "undefined") {
m = m - base;
}
return m;
};
/*
Convert text and content type to a data URI
*/
exports.makeDataUri = function(text,type) {
type = type || "text/vnd.tiddlywiki";
var typeInfo = $tw.config.contentTypeInfo[type] || $tw.config.contentTypeInfo["text/plain"],
isBase64 = typeInfo.encoding === "base64",
parts = [];
parts.push("data:");
parts.push(type);
parts.push(isBase64 ? ";base64" : "");
parts.push(",");
parts.push(isBase64 ? text : encodeURIComponent(text));
return parts.join("");
};
/*
Useful for finding out the fully escaped CSS selector equivalent to a given tag. For example:
$tw.utils.tagToCssSelector("$:/tags/Stylesheet") --> tc-tagged-\%24\%3A\%2Ftags\%2FStylesheet
*/
exports.tagToCssSelector = function(tagName) {
return "tc-tagged-" + encodeURIComponent(tagName).replace(/[!"#$%&'()*+,\-./:;<=>?@[\\\]^`{\|}~,]/mg,function(c) {
return "\\" + c;
});
};
/*
IE does not have sign function
*/
exports.sign = Math.sign || function(x) {
x = +x; // convert to a number
if (x === 0 || isNaN(x)) {
return x;
}
return x > 0 ? 1 : -1;
};
})();
/*\
title: $:/core/modules/widgets/action-deletefield.js
type: application/javascript
module-type: widget
Action widget to delete fields of a tiddler.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var DeleteFieldWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
DeleteFieldWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
DeleteFieldWidget.prototype.render = function(parent,nextSibling) {
this.computeAttributes();
this.execute();
};
/*
Compute the internal state of the widget
*/
DeleteFieldWidget.prototype.execute = function() {
this.actionTiddler = this.getAttribute("$tiddler",this.getVariable("currentTiddler"));
this.actionField = this.getAttribute("$field");
};
/*
Refresh the widget by ensuring our attributes are up to date
*/
DeleteFieldWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes["$tiddler"]) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
/*
Invoke the action associated with this widget
*/
DeleteFieldWidget.prototype.invokeAction = function(triggeringWidget,event) {
var self = this,
tiddler = this.wiki.getTiddler(self.actionTiddler),
removeFields = {};
if(this.actionField) {
removeFields[this.actionField] = undefined;
}
if(tiddler) {
$tw.utils.each(this.attributes,function(attribute,name) {
if(name.charAt(0) !== "$" && name !== "title") {
removeFields[name] = undefined;
}
});
this.wiki.addTiddler(new $tw.Tiddler(this.wiki.getModificationFields(),tiddler,removeFields,this.wiki.getCreationFields()));
}
return true; // Action was invoked
};
exports["action-deletefield"] = DeleteFieldWidget;
})();
/*\
title: $:/core/modules/widgets/action-deletetiddler.js
type: application/javascript
module-type: widget
Action widget to delete a tiddler.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var DeleteTiddlerWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
DeleteTiddlerWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
DeleteTiddlerWidget.prototype.render = function(parent,nextSibling) {
this.computeAttributes();
this.execute();
};
/*
Compute the internal state of the widget
*/
DeleteTiddlerWidget.prototype.execute = function() {
this.actionFilter = this.getAttribute("$filter");
this.actionTiddler = this.getAttribute("$tiddler");
};
/*
Refresh the widget by ensuring our attributes are up to date
*/
DeleteTiddlerWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes["$filter"] || changedAttributes["$tiddler"]) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
/*
Invoke the action associated with this widget
*/
DeleteTiddlerWidget.prototype.invokeAction = function(triggeringWidget,event) {
var tiddlers = [];
if(this.actionFilter) {
tiddlers = this.wiki.filterTiddlers(this.actionFilter,this);
}
if(this.actionTiddler) {
tiddlers.push(this.actionTiddler);
}
for(var t=0; t<tiddlers.length; t++) {
this.wiki.deleteTiddler(tiddlers[t]);
}
return true; // Action was invoked
};
exports["action-deletetiddler"] = DeleteTiddlerWidget;
})();
/*\
title: $:/core/modules/widgets/action-listops.js
type: application/javascript
module-type: widget
Action widget to apply list operations to any tiddler field (defaults to the 'list' field of the current tiddler)
\*/
(function() {
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var ActionListopsWidget = function(parseTreeNode, options) {
this.initialise(parseTreeNode, options);
};
/**
* Inherit from the base widget class
*/
ActionListopsWidget.prototype = new Widget();
/**
* Render this widget into the DOM
*/
ActionListopsWidget.prototype.render = function(parent, nextSibling) {
this.computeAttributes();
this.execute();
};
/**
* Compute the internal state of the widget
*/
ActionListopsWidget.prototype.execute = function() {
// Get our parameters
this.target = this.getAttribute("$tiddler", this.getVariable(
"currentTiddler"));
this.filter = this.getAttribute("$filter");
this.subfilter = this.getAttribute("$subfilter");
this.listField = this.getAttribute("$field", "list");
this.listIndex = this.getAttribute("$index");
this.filtertags = this.getAttribute("$tags");
};
/**
* Refresh the widget by ensuring our attributes are up to date
*/
ActionListopsWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.$tiddler || changedAttributes.$filter ||
changedAttributes.$subfilter || changedAttributes.$field ||
changedAttributes.$index || changedAttributes.$tags) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
/**
* Invoke the action associated with this widget
*/
ActionListopsWidget.prototype.invokeAction = function(triggeringWidget,
event) {
//Apply the specified filters to the lists
var field = this.listField,
index,
type = "!!",
list = this.listField;
if(this.listIndex) {
field = undefined;
index = this.listIndex;
type = "##";
list = this.listIndex;
}
if(this.filter) {
this.wiki.setText(this.target, field, index, $tw.utils.stringifyList(
this.wiki
.filterTiddlers(this.filter, this)));
}
if(this.subfilter) {
var subfilter = "[list[" + this.target + type + list + "]] " + this.subfilter;
this.wiki.setText(this.target, field, index, $tw.utils.stringifyList(
this.wiki
.filterTiddlers(subfilter, this)));
}
if(this.filtertags) {
var tagfilter = "[list[" + this.target + "!!tags]] " + this.filtertags;
this.wiki.setText(this.target, "tags", undefined, $tw.utils.stringifyList(
this.wiki.filterTiddlers(tagfilter, this)));
}
return true; // Action was invoked
};
exports["action-listops"] = ActionListopsWidget;
})();
/*\
title: $:/core/modules/widgets/action-navigate.js
type: application/javascript
module-type: widget
Action widget to navigate to a tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var NavigateWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
NavigateWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
NavigateWidget.prototype.render = function(parent,nextSibling) {
this.computeAttributes();
this.execute();
};
/*
Compute the internal state of the widget
*/
NavigateWidget.prototype.execute = function() {
this.actionTo = this.getAttribute("$to");
this.actionScroll = this.getAttribute("$scroll");
};
/*
Refresh the widget by ensuring our attributes are up to date
*/
NavigateWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes["$to"] || changedAttributes["$scroll"]) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
/*
Invoke the action associated with this widget
*/
NavigateWidget.prototype.invokeAction = function(triggeringWidget,event) {
var bounds = triggeringWidget && triggeringWidget.getBoundingClientRect && triggeringWidget.getBoundingClientRect(),
suppressNavigation = event.metaKey || event.ctrlKey || (event.button === 1);
if(this.actionScroll === "yes") {
suppressNavigation = false;
} else if(this.actionScroll === "no") {
suppressNavigation = true;
}
this.dispatchEvent({
type: "tm-navigate",
navigateTo: this.actionTo === undefined ? this.getVariable("currentTiddler") : this.actionTo,
navigateFromTitle: this.getVariable("storyTiddler"),
navigateFromNode: triggeringWidget,
navigateFromClientRect: bounds && { top: bounds.top, left: bounds.left, width: bounds.width, right: bounds.right, bottom: bounds.bottom, height: bounds.height
},
navigateSuppressNavigation: suppressNavigation
});
return true; // Action was invoked
};
exports["action-navigate"] = NavigateWidget;
})();
/*\
title: $:/core/modules/widgets/action-sendmessage.js
type: application/javascript
module-type: widget
Action widget to send a message
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var SendMessageWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
SendMessageWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
SendMessageWidget.prototype.render = function(parent,nextSibling) {
this.computeAttributes();
this.execute();
};
/*
Compute the internal state of the widget
*/
SendMessageWidget.prototype.execute = function() {
this.actionMessage = this.getAttribute("$message");
this.actionParam = this.getAttribute("$param");
this.actionName = this.getAttribute("$name");
this.actionValue = this.getAttribute("$value","");
};
/*
Refresh the widget by ensuring our attributes are up to date
*/
SendMessageWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(Object.keys(changedAttributes).length) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
/*
Invoke the action associated with this widget
*/
SendMessageWidget.prototype.invokeAction = function(triggeringWidget,event) {
// Get the string parameter
var param = this.actionParam;
// Assemble the attributes as a hashmap
var paramObject = Object.create(null);
var count = 0;
$tw.utils.each(this.attributes,function(attribute,name) {
if(name.charAt(0) !== "$") {
paramObject[name] = attribute;
count++;
}
});
// Add name/value pair if present
if(this.actionName) {
paramObject[this.actionName] = this.actionValue;
}
// Dispatch the message
this.dispatchEvent({
type: this.actionMessage,
param: param,
paramObject: paramObject,
tiddlerTitle: this.getVariable("currentTiddler"),
navigateFromTitle: this.getVariable("storyTiddler")
});
return true; // Action was invoked
};
exports["action-sendmessage"] = SendMessageWidget;
})();
/*\
title: $:/core/modules/widgets/action-setfield.js
type: application/javascript
module-type: widget
Action widget to set a single field or index on a tiddler.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var SetFieldWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
SetFieldWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
SetFieldWidget.prototype.render = function(parent,nextSibling) {
this.computeAttributes();
this.execute();
};
/*
Compute the internal state of the widget
*/
SetFieldWidget.prototype.execute = function() {
this.actionTiddler = this.getAttribute("$tiddler",this.getVariable("currentTiddler"));
this.actionField = this.getAttribute("$field");
this.actionIndex = this.getAttribute("$index");
this.actionValue = this.getAttribute("$value");
this.actionTimestamp = this.getAttribute("$timestamp","yes") === "yes";
};
/*
Refresh the widget by ensuring our attributes are up to date
*/
SetFieldWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes["$tiddler"] || changedAttributes["$field"] || changedAttributes["$index"] || changedAttributes["$value"]) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
/*
Invoke the action associated with this widget
*/
SetFieldWidget.prototype.invokeAction = function(triggeringWidget,event) {
var self = this,
options = {};
options.suppressTimestamp = !this.actionTimestamp;
if((typeof this.actionField == "string") || (typeof this.actionIndex == "string") || (typeof this.actionValue == "string")) {
this.wiki.setText(this.actionTiddler,this.actionField,this.actionIndex,this.actionValue,options);
}
$tw.utils.each(this.attributes,function(attribute,name) {
if(name.charAt(0) !== "$") {
self.wiki.setText(self.actionTiddler,name,undefined,attribute,options);
}
});
return true; // Action was invoked
};
exports["action-setfield"] = SetFieldWidget;
})();
/*\
title: $:/core/modules/widgets/browse.js
type: application/javascript
module-type: widget
Browse widget for browsing for files to import
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var BrowseWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
BrowseWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
BrowseWidget.prototype.render = function(parent,nextSibling) {
var self = this;
// Remember parent
this.parentDomNode = parent;
// Compute attributes and execute state
this.computeAttributes();
this.execute();
// Create element
var domNode = this.document.createElement("input");
domNode.setAttribute("type","file");
if(this.browseMultiple) {
domNode.setAttribute("multiple","multiple");
}
if(this.tooltip) {
domNode.setAttribute("title",this.tooltip);
}
// Nw.js supports "nwsaveas" to force a "save as" dialogue that allows a new or existing file to be selected
if(this.nwsaveas) {
domNode.setAttribute("nwsaveas",this.nwsaveas);
}
// Nw.js supports "webkitdirectory" to allow a directory to be selected
if(this.webkitdirectory) {
domNode.setAttribute("webkitdirectory",this.webkitdirectory);
}
// Add a click event handler
domNode.addEventListener("change",function (event) {
if(self.message) {
self.dispatchEvent({type: self.message, param: self.param, files: event.target.files});
} else {
self.wiki.readFiles(event.target.files,function(tiddlerFieldsArray) {
self.dispatchEvent({type: "tm-import-tiddlers", param: JSON.stringify(tiddlerFieldsArray)});
});
}
return false;
},false);
// Insert element
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
};
/*
Compute the internal state of the widget
*/
BrowseWidget.prototype.execute = function() {
this.browseMultiple = this.getAttribute("multiple");
this.message = this.getAttribute("message");
this.param = this.getAttribute("param");
this.tooltip = this.getAttribute("tooltip");
this.nwsaveas = this.getAttribute("nwsaveas");
this.webkitdirectory = this.getAttribute("webkitdirectory");
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
BrowseWidget.prototype.refresh = function(changedTiddlers) {
return false;
};
exports.browse = BrowseWidget;
})();
/*\
title: $:/core/modules/widgets/button-dragover-extend.js
type: application/javascript
module-type: widget
Extend the link widget to allow click when there is a drag over (option)
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var ButtonWidget = require("$:/core/modules/widgets/button.js")["button"];
ButtonWidget.prototype.bjDragExtend ={};
ButtonWidget.prototype.bjDragExtend.render = ButtonWidget.prototype.render;
ButtonWidget.prototype.render = function (parent,nextSibling) {
ButtonWidget.prototype.bjDragExtend.render.call(this,parent,nextSibling);
if (this.dragoverclick==="yes") {
$tw.utils.addEventListeners(this.domNodes[0],[
{name: "dragover", handlerObject: this, handlerMethod: "handleDragOverEvent"}
]);
}
}
/*
add option
*/
ButtonWidget.prototype.bjDragExtend.execute = ButtonWidget.prototype.execute;
ButtonWidget.prototype.execute = function() {
ButtonWidget.prototype.bjDragExtend.execute.call(this);
this.dragoverclick=this.getAttribute("dragoverclick","no");
};
/*
handle dragover
*/
ButtonWidget.prototype.handleDragOverEvent = function(event) {
// Tell the browser that we're still interested in the drop
event.preventDefault();
// Send the drag as click as a navigate event
var bounds = this.domNodes[0].getBoundingClientRect();
this.dispatchEvent({
type: "tm-navigate",
navigateTo: this.to,
navigateFromTitle: this.getVariable("storyTiddler"),
navigateFromNode: this,
navigateFromClientRect: { top: bounds.top, left: bounds.left, width: bounds.width, right: bounds.right, bottom: bounds.bottom, height: bounds.height
},
navigateSuppressNavigation: event.metaKey || event.ctrlKey
});
event.preventDefault();
event.stopPropagation();
return false;
};
})();
/*\
title: $:/core/modules/widgets/button.js
type: application/javascript
module-type: widget
Button widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var ButtonWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
ButtonWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
ButtonWidget.prototype.render = function(parent,nextSibling) {
var self = this;
// Remember parent
this.parentDomNode = parent;
// Compute attributes and execute state
this.computeAttributes();
this.execute();
// Create element
var tag = "button";
if(this.buttonTag && $tw.config.htmlUnsafeElements.indexOf(this.buttonTag) === -1) {
tag = this.buttonTag;
}
var domNode = this.document.createElement(tag);
// Assign classes
var classes = this["class"].split(" ") || [],
isPoppedUp = this.popup && this.isPoppedUp();
if(this.selectedClass) {
if(this.set && this.setTo && this.isSelected()) {
$tw.utils.pushTop(classes,this.selectedClass.split(" "));
}
if(isPoppedUp) {
$tw.utils.pushTop(classes,this.selectedClass.split(" "));
}
}
if(isPoppedUp) {
$tw.utils.pushTop(classes,"tc-popup-handle");
}
domNode.className = classes.join(" ");
// Assign other attributes
if(this.style) {
domNode.setAttribute("style",this.style);
}
if(this.tooltip) {
domNode.setAttribute("title",this.tooltip);
}
if(this["aria-label"]) {
domNode.setAttribute("aria-label",this["aria-label"]);
}
// Add a click event handler
domNode.addEventListener("click",function (event) {
var handled = false;
if(self.invokeActions(this,event)) {
handled = true;
}
if(self.to) {
self.navigateTo(event);
handled = true;
}
if(self.message) {
self.dispatchMessage(event);
handled = true;
}
if(self.popup) {
self.triggerPopup(event);
handled = true;
}
if(self.set) {
self.setTiddler();
handled = true;
}
if(handled) {
event.preventDefault();
event.stopPropagation();
}
return handled;
},false);
// Insert element
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
};
/*
We don't allow actions to propagate because we trigger actions ourselves
*/
ButtonWidget.prototype.allowActionPropagation = function() {
return false;
};
ButtonWidget.prototype.getBoundingClientRect = function() {
return this.domNodes[0].getBoundingClientRect();
};
ButtonWidget.prototype.isSelected = function() {
return this.wiki.getTextReference(this.set,this.defaultSetValue,this.getVariable("currentTiddler")) === this.setTo;
};
ButtonWidget.prototype.isPoppedUp = function() {
var tiddler = this.wiki.getTiddler(this.popup);
var result = tiddler && tiddler.fields.text ? $tw.popup.readPopupState(tiddler.fields.text) : false;
return result;
};
ButtonWidget.prototype.navigateTo = function(event) {
var bounds = this.getBoundingClientRect();
this.dispatchEvent({
type: "tm-navigate",
navigateTo: this.to,
navigateFromTitle: this.getVariable("storyTiddler"),
navigateFromNode: this,
navigateFromClientRect: { top: bounds.top, left: bounds.left, width: bounds.width, right: bounds.right, bottom: bounds.bottom, height: bounds.height
},
navigateSuppressNavigation: event.metaKey || event.ctrlKey || (event.button === 1)
});
};
ButtonWidget.prototype.dispatchMessage = function(event) {
this.dispatchEvent({type: this.message, param: this.param, tiddlerTitle: this.getVariable("currentTiddler")});
};
ButtonWidget.prototype.triggerPopup = function(event) {
$tw.popup.triggerPopup({
domNode: this.domNodes[0],
title: this.popup,
wiki: this.wiki
});
};
ButtonWidget.prototype.setTiddler = function() {
this.wiki.setTextReference(this.set,this.setTo,this.getVariable("currentTiddler"));
};
/*
Compute the internal state of the widget
*/
ButtonWidget.prototype.execute = function() {
// Get attributes
this.to = this.getAttribute("to");
this.message = this.getAttribute("message");
this.param = this.getAttribute("param");
this.set = this.getAttribute("set");
this.setTo = this.getAttribute("setTo");
this.popup = this.getAttribute("popup");
this.hover = this.getAttribute("hover");
this["class"] = this.getAttribute("class","");
this["aria-label"] = this.getAttribute("aria-label");
this.tooltip = this.getAttribute("tooltip");
this.style = this.getAttribute("style");
this.selectedClass = this.getAttribute("selectedClass");
this.defaultSetValue = this.getAttribute("default","");
this.buttonTag = this.getAttribute("tag");
// Make child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ButtonWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.to || changedAttributes.message || changedAttributes.param || changedAttributes.set || changedAttributes.setTo || changedAttributes.popup || changedAttributes.hover || changedAttributes["class"] || changedAttributes.selectedClass || changedAttributes.style || (this.set && changedTiddlers[this.set]) || (this.popup && changedTiddlers[this.popup])) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
exports.button = ButtonWidget;
})();
/*\
title: $:/core/modules/widgets/checkbox.js
type: application/javascript
module-type: widget
Checkbox widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var CheckboxWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
CheckboxWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
CheckboxWidget.prototype.render = function(parent,nextSibling) {
// Save the parent dom node
this.parentDomNode = parent;
// Compute our attributes
this.computeAttributes();
// Execute our logic
this.execute();
// Create our elements
this.labelDomNode = this.document.createElement("label");
this.labelDomNode.setAttribute("class",this.checkboxClass);
this.inputDomNode = this.document.createElement("input");
this.inputDomNode.setAttribute("type","checkbox");
if(this.getValue()) {
this.inputDomNode.setAttribute("checked","true");
}
this.labelDomNode.appendChild(this.inputDomNode);
this.spanDomNode = this.document.createElement("span");
this.labelDomNode.appendChild(this.spanDomNode);
// Add a click event handler
$tw.utils.addEventListeners(this.inputDomNode,[
{name: "change", handlerObject: this, handlerMethod: "handleChangeEvent"}
]);
// Insert the label into the DOM and render any children
parent.insertBefore(this.labelDomNode,nextSibling);
this.renderChildren(this.spanDomNode,null);
this.domNodes.push(this.labelDomNode);
};
CheckboxWidget.prototype.getValue = function() {
var tiddler = this.wiki.getTiddler(this.checkboxTitle);
if(tiddler) {
if(this.checkboxTag) {
if(this.checkboxInvertTag) {
return !tiddler.hasTag(this.checkboxTag);
} else {
return tiddler.hasTag(this.checkboxTag);
}
}
if(this.checkboxField) {
var value = tiddler.fields[this.checkboxField] || this.checkboxDefault || "";
if(value === this.checkboxChecked) {
return true;
}
if(value === this.checkboxUnchecked) {
return false;
}
}
} else {
if(this.checkboxTag) {
return false;
}
if(this.checkboxField) {
if(this.checkboxDefault === this.checkboxChecked) {
return true;
}
if(this.checkboxDefault === this.checkboxUnchecked) {
return false;
}
}
}
return false;
};
CheckboxWidget.prototype.handleChangeEvent = function(event) {
var checked = this.inputDomNode.checked,
tiddler = this.wiki.getTiddler(this.checkboxTitle),
fallbackFields = {text: ""},
newFields = {title: this.checkboxTitle},
hasChanged = false,
tagCheck = false,
hasTag = tiddler && tiddler.hasTag(this.checkboxTag);
if(this.checkboxTag && this.checkboxInvertTag === "yes") {
tagCheck = hasTag === checked;
} else {
tagCheck = hasTag !== checked;
}
// Set the tag if specified
if(this.checkboxTag && (!tiddler || tagCheck)) {
newFields.tags = tiddler ? (tiddler.fields.tags || []).slice(0) : [];
var pos = newFields.tags.indexOf(this.checkboxTag);
if(pos !== -1) {
newFields.tags.splice(pos,1);
}
if(this.checkboxInvertTag === "yes" && !checked) {
newFields.tags.push(this.checkboxTag);
} else if(this.checkboxInvertTag !== "yes" && checked) {
newFields.tags.push(this.checkboxTag);
}
hasChanged = true;
}
// Set the field if specified
if(this.checkboxField) {
var value = checked ? this.checkboxChecked : this.checkboxUnchecked;
if(!tiddler || tiddler.fields[this.checkboxField] !== value) {
newFields[this.checkboxField] = value;
hasChanged = true;
}
}
if(hasChanged) {
this.wiki.addTiddler(new $tw.Tiddler(this.wiki.getCreationFields(),fallbackFields,tiddler,newFields,this.wiki.getModificationFields()));
}
};
/*
Compute the internal state of the widget
*/
CheckboxWidget.prototype.execute = function() {
// Get the parameters from the attributes
this.checkboxTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
this.checkboxTag = this.getAttribute("tag");
this.checkboxField = this.getAttribute("field");
this.checkboxChecked = this.getAttribute("checked");
this.checkboxUnchecked = this.getAttribute("unchecked");
this.checkboxDefault = this.getAttribute("default");
this.checkboxClass = this.getAttribute("class","");
this.checkboxInvertTag = this.getAttribute("invertTag","");
// Make the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
CheckboxWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.tiddler || changedAttributes.tag || changedAttributes.invertTag || changedAttributes.field || changedAttributes.checked || changedAttributes.unchecked || changedAttributes["default"] || changedAttributes["class"]) {
this.refreshSelf();
return true;
} else {
var refreshed = false;
if(changedTiddlers[this.checkboxTitle]) {
this.inputDomNode.checked = this.getValue();
refreshed = true;
}
return this.refreshChildren(changedTiddlers) || refreshed;
}
};
exports.checkbox = CheckboxWidget;
})();
/*\
title: $:/core/modules/widgets/codeblock.js
type: application/javascript
module-type: widget
Code block node widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var CodeBlockWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
CodeBlockWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
CodeBlockWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
var codeNode = this.document.createElement("code"),
domNode = this.document.createElement("pre");
codeNode.appendChild(this.document.createTextNode(this.getAttribute("code")));
domNode.appendChild(codeNode);
parent.insertBefore(domNode,nextSibling);
this.domNodes.push(domNode);
if(this.postRender) {
this.postRender();
}
};
/*
Compute the internal state of the widget
*/
CodeBlockWidget.prototype.execute = function() {
this.language = this.getAttribute("language");
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
CodeBlockWidget.prototype.refresh = function(changedTiddlers) {
return false;
};
exports.codeblock = CodeBlockWidget;
})();
/*\
title: $:/core/modules/widgets/count.js
type: application/javascript
module-type: widget
Count widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var CountWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
CountWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
CountWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
var textNode = this.document.createTextNode(this.currentCount);
parent.insertBefore(textNode,nextSibling);
this.domNodes.push(textNode);
};
/*
Compute the internal state of the widget
*/
CountWidget.prototype.execute = function() {
// Get parameters from our attributes
this.filter = this.getAttribute("filter");
// Execute the filter
if(this.filter) {
this.currentCount = this.wiki.filterTiddlers(this.filter,this).length;
} else {
this.currentCount = undefined;
}
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
CountWidget.prototype.refresh = function(changedTiddlers) {
// Re-execute the filter to get the count
this.computeAttributes();
var oldCount = this.currentCount;
this.execute();
if(this.currentCount !== oldCount) {
// Regenerate and rerender the widget and replace the existing DOM node
this.refreshSelf();
return true;
} else {
return false;
}
};
exports.count = CountWidget;
})();
/*\
title: $:/core/modules/widgets/dropzone-extend.js
type: application/javascript
module-type: widget
Extend the dropzone widget to allow other widget to handle drop events
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var DropZoneWidget = require("$:/core/modules/widgets/dropzone.js")["dropzone"];
var Widget = require("$:/core/modules/widgets/widget.js").widget;
/*
The edit-text widget calls this method just after inserting its dom nodes
*/
/*
overload the base widget class initialise
*/
DropZoneWidget.prototype.bjDropzoneExtend ={};
DropZoneWidget.prototype.bjDropzoneExtend.initialise = DropZoneWidget.prototype.initialise;
DropZoneWidget.prototype.initialise = function (parseTreeNode,options) {
DropZoneWidget.prototype.bjDropzoneExtend.initialise.call(this,parseTreeNode,options);
this.addEventListeners([
{type: "tm-dropHandled", handler: "handleDropHandled"}]);
};
/*
handle drophandled message
*/
DropZoneWidget.prototype.handleDropHandled = function(event) {
// Reset the enter count
this.dragEnterCount = 0;
// Remove highlighting
$tw.utils.removeClass(this.domNodes[0],"tc-dragover");
return false;
};
})();
/*\
title: $:/core/modules/widgets/dropzone.js
type: application/javascript
module-type: widget
Dropzone widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var DropZoneWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
DropZoneWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
DropZoneWidget.prototype.render = function(parent,nextSibling) {
var self = this;
// Remember parent
this.parentDomNode = parent;
// Compute attributes and execute state
this.computeAttributes();
this.execute();
// Create element
var domNode = this.document.createElement("div");
domNode.className = "tc-dropzone";
// Add event handlers
$tw.utils.addEventListeners(domNode,[
{name: "dragenter", handlerObject: this, handlerMethod: "handleDragEnterEvent"},
{name: "dragover", handlerObject: this, handlerMethod: "handleDragOverEvent"},
{name: "dragleave", handlerObject: this, handlerMethod: "handleDragLeaveEvent"},
{name: "drop", handlerObject: this, handlerMethod: "handleDropEvent"},
{name: "paste", handlerObject: this, handlerMethod: "handlePasteEvent"}
]);
domNode.addEventListener("click",function (event) {
},false);
// Insert element
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
};
DropZoneWidget.prototype.enterDrag = function() {
// Check for this window being the source of the drag
if($tw.dragInProgress) {
return false;
}
// We count enter/leave events
this.dragEnterCount = (this.dragEnterCount || 0) + 1;
// If we're entering for the first time we need to apply highlighting
if(this.dragEnterCount === 1) {
$tw.utils.addClass(this.domNodes[0],"tc-dragover");
}
};
DropZoneWidget.prototype.leaveDrag = function() {
// Reduce the enter count
this.dragEnterCount = (this.dragEnterCount || 0) - 1;
// Remove highlighting if we're leaving externally
if(this.dragEnterCount <= 0) {
$tw.utils.removeClass(this.domNodes[0],"tc-dragover");
}
};
DropZoneWidget.prototype.handleDragEnterEvent = function(event) {
this.enterDrag();
// Tell the browser that we're ready to handle the drop
event.preventDefault();
// Tell the browser not to ripple the drag up to any parent drop handlers
event.stopPropagation();
};
DropZoneWidget.prototype.handleDragOverEvent = function(event) {
// Check for being over a TEXTAREA or INPUT
if(["TEXTAREA","INPUT"].indexOf(event.target.tagName) !== -1) {
return false;
}
// Check for this window being the source of the drag
if($tw.dragInProgress) {
return false;
}
// Tell the browser that we're still interested in the drop
event.preventDefault();
event.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy
};
DropZoneWidget.prototype.handleDragLeaveEvent = function(event) {
this.leaveDrag();
};
DropZoneWidget.prototype.handleDropEvent = function(event) {
this.leaveDrag();
// Check for being over a TEXTAREA or INPUT
if(["TEXTAREA","INPUT"].indexOf(event.target.tagName) !== -1) {
return false;
}
// Check for this window being the source of the drag
if($tw.dragInProgress) {
return false;
}
var self = this,
dataTransfer = event.dataTransfer;
// Reset the enter count
this.dragEnterCount = 0;
// Remove highlighting
$tw.utils.removeClass(this.domNodes[0],"tc-dragover");
// Import any files in the drop
var numFiles = this.wiki.readFiles(dataTransfer.files,function(tiddlerFieldsArray) {
self.dispatchEvent({type: "tm-import-tiddlers", param: JSON.stringify(tiddlerFieldsArray)});
});
// Try to import the various data types we understand
if(numFiles === 0) {
this.importData(dataTransfer);
}
// Tell the browser that we handled the drop
event.preventDefault();
// Stop the drop ripple up to any parent handlers
event.stopPropagation();
};
DropZoneWidget.prototype.importData = function(dataTransfer) {
// Try each provided data type in turn
for(var t=0; t<this.importDataTypes.length; t++) {
if(!$tw.browser.isIE || this.importDataTypes[t].IECompatible) {
// Get the data
var dataType = this.importDataTypes[t];
var data = dataTransfer.getData(dataType.type);
// Import the tiddlers in the data
if(data !== "" && data !== null) {
if($tw.log.IMPORT) {
console.log("Importing data type '" + dataType.type + "', data: '" + data + "'")
}
var tiddlerFields = dataType.convertToFields(data);
if(!tiddlerFields.title) {
tiddlerFields.title = this.wiki.generateNewTitle("Untitled");
}
this.dispatchEvent({type: "tm-import-tiddlers", param: JSON.stringify([tiddlerFields])});
return;
}
}
}
};
DropZoneWidget.prototype.importDataTypes = [
{type: "text/vnd.tiddler", IECompatible: false, convertToFields: function(data) {
return JSON.parse(data);
}},
{type: "URL", IECompatible: true, convertToFields: function(data) {
// Check for tiddler data URI
var match = decodeURIComponent(data).match(/^data\:text\/vnd\.tiddler,(.*)/i);
if(match) {
return JSON.parse(match[1]);
} else {
return { // As URL string
text: data
};
}
}},
{type: "text/x-moz-url", IECompatible: false, convertToFields: function(data) {
// Check for tiddler data URI
var match = decodeURIComponent(data).match(/^data\:text\/vnd\.tiddler,(.*)/i);
if(match) {
return JSON.parse(match[1]);
} else {
return { // As URL string
text: data
};
}
}},
{type: "text/html", IECompatible: false, convertToFields: function(data) {
return {
text: data
};
}},
{type: "text/plain", IECompatible: false, convertToFields: function(data) {
return {
text: data
};
}},
{type: "Text", IECompatible: true, convertToFields: function(data) {
return {
text: data
};
}},
{type: "text/uri-list", IECompatible: false, convertToFields: function(data) {
return {
text: data
};
}}
];
DropZoneWidget.prototype.handlePasteEvent = function(event) {
// Let the browser handle it if we're in a textarea or input box
if(["TEXTAREA","INPUT"].indexOf(event.target.tagName) == -1) {
var self = this,
items = event.clipboardData.items;
// Enumerate the clipboard items
for(var t = 0; t<items.length; t++) {
var item = items[t];
if(item.kind === "file") {
// Import any files
this.wiki.readFile(item.getAsFile(),function(tiddlerFieldsArray) {
self.dispatchEvent({type: "tm-import-tiddlers", param: JSON.stringify(tiddlerFieldsArray)});
});
} else if(item.kind === "string") {
// Create tiddlers from string items
var type = item.type;
item.getAsString(function(str) {
var tiddlerFields = {
title: self.wiki.generateNewTitle("Untitled"),
text: str,
type: type
};
if($tw.log.IMPORT) {
console.log("Importing string '" + str + "', type: '" + type + "'");
}
self.dispatchEvent({type: "tm-import-tiddlers", param: JSON.stringify([tiddlerFields])});
});
}
}
// Tell the browser that we've handled the paste
event.stopPropagation();
event.preventDefault();
}
};
/*
Compute the internal state of the widget
*/
DropZoneWidget.prototype.execute = function() {
// Make child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
DropZoneWidget.prototype.refresh = function(changedTiddlers) {
return this.refreshChildren(changedTiddlers);
};
exports.dropzone = DropZoneWidget;
})();
/*\
title: $:/core/modules/widgets/edit-binary.js
type: application/javascript
module-type: widget
Edit-binary widget; placeholder for editing binary tiddlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var BINARY_WARNING_MESSAGE = "$:/core/ui/BinaryWarning";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var EditBinaryWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
EditBinaryWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
EditBinaryWidget.prototype.render = function(parent,nextSibling) {
var self = this;
// Save the parent dom node
this.parentDomNode = parent;
// Compute our attributes
this.computeAttributes();
// Execute our logic
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
EditBinaryWidget.prototype.execute = function() {
// Construct the child widgets
this.makeChildWidgets([{
type: "transclude",
attributes: {
tiddler: {type: "string", value: BINARY_WARNING_MESSAGE}
}
}]);
};
/*
Refresh by refreshing our child widget
*/
EditBinaryWidget.prototype.refresh = function(changedTiddlers) {
return this.refreshChildren(changedTiddlers);
};
exports["edit-binary"] = EditBinaryWidget;
})();
/*\
title: $:/core/modules/widgets/edit-bitmap.js
type: application/javascript
module-type: widget
Edit-bitmap widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Default image sizes
var DEFAULT_IMAGE_WIDTH = 300,
DEFAULT_IMAGE_HEIGHT = 185;
// Configuration tiddlers
var LINE_WIDTH_TITLE = "$:/config/BitmapEditor/LineWidth",
LINE_COLOUR_TITLE = "$:/config/BitmapEditor/Colour";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var EditBitmapWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
EditBitmapWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
EditBitmapWidget.prototype.render = function(parent,nextSibling) {
var self = this;
// Save the parent dom node
this.parentDomNode = parent;
// Compute our attributes
this.computeAttributes();
// Execute our logic
this.execute();
// Create our element
this.canvasDomNode = $tw.utils.domMaker("canvas",{
document: this.document,
"class":"tc-edit-bitmapeditor",
eventListeners: [{
name: "touchstart", handlerObject: this, handlerMethod: "handleTouchStartEvent"
},{
name: "touchmove", handlerObject: this, handlerMethod: "handleTouchMoveEvent"
},{
name: "touchend", handlerObject: this, handlerMethod: "handleTouchEndEvent"
},{
name: "mousedown", handlerObject: this, handlerMethod: "handleMouseDownEvent"
},{
name: "mousemove", handlerObject: this, handlerMethod: "handleMouseMoveEvent"
},{
name: "mouseup", handlerObject: this, handlerMethod: "handleMouseUpEvent"
}]
});
this.widthDomNode = $tw.utils.domMaker("input",{
document: this.document,
"class":"tc-edit-bitmapeditor-width",
eventListeners: [{
name: "change", handlerObject: this, handlerMethod: "handleWidthChangeEvent"
}]
});
this.heightDomNode = $tw.utils.domMaker("input",{
document: this.document,
"class":"tc-edit-bitmapeditor-height",
eventListeners: [{
name: "change", handlerObject: this, handlerMethod: "handleHeightChangeEvent"
}]
});
// Insert the elements into the DOM
parent.insertBefore(this.canvasDomNode,nextSibling);
parent.insertBefore(this.widthDomNode,nextSibling);
parent.insertBefore(this.heightDomNode,nextSibling);
this.domNodes.push(this.canvasDomNode,this.widthDomNode,this.heightDomNode);
// Load the image into the canvas
if($tw.browser) {
this.loadCanvas();
}
};
/*
Compute the internal state of the widget
*/
EditBitmapWidget.prototype.execute = function() {
// Get our parameters
this.editTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
};
/*
Note that the bitmap editor intentionally doesn't try to refresh itself because it would be confusing to have the image changing spontaneously while editting it
*/
EditBitmapWidget.prototype.refresh = function(changedTiddlers) {
return false;
};
EditBitmapWidget.prototype.loadCanvas = function() {
var tiddler = this.wiki.getTiddler(this.editTitle),
currImage = new Image();
// Set up event handlers for loading the image
var self = this;
currImage.onload = function() {
// Copy the image to the on-screen canvas
self.initCanvas(self.canvasDomNode,currImage.width,currImage.height,currImage);
// And also copy the current bitmap to the off-screen canvas
self.currCanvas = self.document.createElement("canvas");
self.initCanvas(self.currCanvas,currImage.width,currImage.height,currImage);
// Set the width and height input boxes
self.updateSize();
};
currImage.onerror = function() {
// Set the on-screen canvas size and clear it
self.initCanvas(self.canvasDomNode,DEFAULT_IMAGE_WIDTH,DEFAULT_IMAGE_HEIGHT);
// Set the off-screen canvas size and clear it
self.currCanvas = self.document.createElement("canvas");
self.initCanvas(self.currCanvas,DEFAULT_IMAGE_WIDTH,DEFAULT_IMAGE_HEIGHT);
// Set the width and height input boxes
self.updateSize();
};
// Get the current bitmap into an image object
currImage.src = "data:" + tiddler.fields.type + ";base64," + tiddler.fields.text;
};
EditBitmapWidget.prototype.initCanvas = function(canvas,width,height,image) {
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
if(image) {
ctx.drawImage(image,0,0);
} else {
ctx.fillStyle = "#fff";
ctx.fillRect(0,0,canvas.width,canvas.height);
}
};
/*
** Update the input boxes with the actual size of the canvas
*/
EditBitmapWidget.prototype.updateSize = function() {
this.widthDomNode.value = this.currCanvas.width;
this.heightDomNode.value = this.currCanvas.height;
};
/*
** Change the size of the canvas, preserving the current image
*/
EditBitmapWidget.prototype.changeCanvasSize = function(newWidth,newHeight) {
// Create and size a new canvas
var newCanvas = this.document.createElement("canvas");
this.initCanvas(newCanvas,newWidth,newHeight);
// Copy the old image
var ctx = newCanvas.getContext("2d");
ctx.drawImage(this.currCanvas,0,0);
// Set the new canvas as the current one
this.currCanvas = newCanvas;
// Set the size of the onscreen canvas
this.canvasDomNode.width = newWidth;
this.canvasDomNode.height = newHeight;
// Paint the onscreen canvas with the offscreen canvas
ctx = this.canvasDomNode.getContext("2d");
ctx.drawImage(this.currCanvas,0,0);
};
EditBitmapWidget.prototype.handleWidthChangeEvent = function(event) {
// Get the new width
var newWidth = parseInt(this.widthDomNode.value,10);
// Update if necessary
if(newWidth > 0 && newWidth !== this.currCanvas.width) {
this.changeCanvasSize(newWidth,this.currCanvas.height);
}
// Update the input controls
this.updateSize();
};
EditBitmapWidget.prototype.handleHeightChangeEvent = function(event) {
// Get the new width
var newHeight = parseInt(this.heightDomNode.value,10);
// Update if necessary
if(newHeight > 0 && newHeight !== this.currCanvas.height) {
this.changeCanvasSize(this.currCanvas.width,newHeight);
}
// Update the input controls
this.updateSize();
};
EditBitmapWidget.prototype.handleTouchStartEvent = function(event) {
this.brushDown = true;
this.strokeStart(event.touches[0].clientX,event.touches[0].clientY);
event.preventDefault();
event.stopPropagation();
return false;
};
EditBitmapWidget.prototype.handleTouchMoveEvent = function(event) {
if(this.brushDown) {
this.strokeMove(event.touches[0].clientX,event.touches[0].clientY);
}
event.preventDefault();
event.stopPropagation();
return false;
};
EditBitmapWidget.prototype.handleTouchEndEvent = function(event) {
if(this.brushDown) {
this.brushDown = false;
this.strokeEnd();
}
event.preventDefault();
event.stopPropagation();
return false;
};
EditBitmapWidget.prototype.handleMouseDownEvent = function(event) {
this.strokeStart(event.clientX,event.clientY);
this.brushDown = true;
event.preventDefault();
event.stopPropagation();
return false;
};
EditBitmapWidget.prototype.handleMouseMoveEvent = function(event) {
if(this.brushDown) {
this.strokeMove(event.clientX,event.clientY);
event.preventDefault();
event.stopPropagation();
return false;
}
return true;
};
EditBitmapWidget.prototype.handleMouseUpEvent = function(event) {
if(this.brushDown) {
this.brushDown = false;
this.strokeEnd();
event.preventDefault();
event.stopPropagation();
return false;
}
return true;
};
EditBitmapWidget.prototype.adjustCoordinates = function(x,y) {
var canvasRect = this.canvasDomNode.getBoundingClientRect(),
scale = this.canvasDomNode.width/canvasRect.width;
return {x: (x - canvasRect.left) * scale, y: (y - canvasRect.top) * scale};
};
EditBitmapWidget.prototype.strokeStart = function(x,y) {
// Start off a new stroke
this.stroke = [this.adjustCoordinates(x,y)];
};
EditBitmapWidget.prototype.strokeMove = function(x,y) {
var ctx = this.canvasDomNode.getContext("2d"),
t;
// Add the new position to the end of the stroke
this.stroke.push(this.adjustCoordinates(x,y));
// Redraw the previous image
ctx.drawImage(this.currCanvas,0,0);
// Render the stroke
ctx.strokeStyle = this.wiki.getTiddlerText(LINE_COLOUR_TITLE,"#ff0");
ctx.lineWidth = parseInt(this.wiki.getTiddlerText(LINE_WIDTH_TITLE,"3"),10);
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(this.stroke[0].x,this.stroke[0].y);
for(t=1; t<this.stroke.length-1; t++) {
var s1 = this.stroke[t],
s2 = this.stroke[t-1],
tx = (s1.x + s2.x)/2,
ty = (s1.y + s2.y)/2;
ctx.quadraticCurveTo(s2.x,s2.y,tx,ty);
}
ctx.stroke();
};
EditBitmapWidget.prototype.strokeEnd = function() {
// Copy the bitmap to the off-screen canvas
var ctx = this.currCanvas.getContext("2d");
ctx.drawImage(this.canvasDomNode,0,0);
// Save the image into the tiddler
this.saveChanges();
};
EditBitmapWidget.prototype.saveChanges = function() {
var tiddler = this.wiki.getTiddler(this.editTitle);
if(tiddler) {
// data URIs look like "data:<type>;base64,<text>"
var dataURL = this.canvasDomNode.toDataURL(tiddler.fields.type,1.0),
posColon = dataURL.indexOf(":"),
posSemiColon = dataURL.indexOf(";"),
posComma = dataURL.indexOf(","),
type = dataURL.substring(posColon+1,posSemiColon),
text = dataURL.substring(posComma+1);
var update = {type: type, text: text};
this.wiki.addTiddler(new $tw.Tiddler(this.wiki.getModificationFields(),tiddler,update,this.wiki.getCreationFields()));
}
};
exports["edit-bitmap"] = EditBitmapWidget;
})();
/*\
title: $:/core/modules/widgets/edit-codemirror.js
type: application/javascript
module-type: widget
Codemirror-based text editor widget
Config options "$:/config/CodeMirror" e.g. to allow vim key bindings
{
"require": [
"$:/plugins/tiddlywiki/codemirror/addon/dialog/dialog.js",
"$:/plugins/tiddlywiki/codemirror/addon/search/searchcursor.js",
"$:/plugins/tiddlywiki/codemirror/keymap/vim.js"
],
"configuration": {
"keyMap": "vim",
"showCursorWhenSelecting": true
}
}
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var CODEMIRROR_OPTIONS = "$:/config/CodeMirror";
// Install CodeMirror
if($tw.browser && !window.CodeMirror) {
window.CodeMirror = require("$:/plugins/tiddlywiki/codemirror/lib/codemirror.js");
// Install required CodeMirror plugins
var configOptions = $tw.wiki.getTiddlerData(CODEMIRROR_OPTIONS,{}),
req = configOptions.require;
if(req) {
if($tw.utils.isArray(req)) {
for(var index=0; index<req.length; index++) {
require(req[index]);
}
} else {
require(req);
}
}
}
var MIN_TEXT_AREA_HEIGHT = 100; // Minimum height of textareas in pixels
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var EditCodeMirrorWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
EditCodeMirrorWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
EditCodeMirrorWidget.prototype.render = function(parent,nextSibling) {
var self = this;
// Save the parent dom node
this.parentDomNode = parent;
// Compute our attributes
this.computeAttributes();
// Execute our logic
this.execute();
// Get the configuration options for the CodeMirror object
var config = $tw.wiki.getTiddlerData(CODEMIRROR_OPTIONS,{}).configuration || {},
editInfo = this.getEditInfo();
if(!("lineWrapping" in config)) {
config.lineWrapping = true;
}
if(!("lineNumbers" in config)) {
config.lineNumbers = true;
}
config.mode = editInfo.type;
config.value = editInfo.value;
// Create the CodeMirror instance
var cm = window.CodeMirror(function(domNode) {
parent.insertBefore(domNode,nextSibling);
self.domNodes.push(domNode);
},config);
// Set up a change event handler
cm.on("change",function() {
self.saveChanges(cm.getValue());
});
this.codeMirrorInstance = cm;
};
/*
Get the tiddler being edited and current value
*/
EditCodeMirrorWidget.prototype.getEditInfo = function() {
// Get the edit value
var self = this,
value,
type = "text/plain",
update;
if(this.editIndex) {
value = this.wiki.extractTiddlerDataItem(this.editTitle,this.editIndex,this.editDefault);
update = function(value) {
var data = self.wiki.getTiddlerData(self.editTitle,{});
if(data[self.editIndex] !== value) {
data[self.editIndex] = value;
self.wiki.setTiddlerData(self.editTitle,data);
}
};
} else {
// Get the current tiddler and the field name
var tiddler = this.wiki.getTiddler(this.editTitle);
if(tiddler) {
// If we've got a tiddler, the value to display is the field string value
value = tiddler.getFieldString(this.editField);
if(this.editField === "text") {
type = tiddler.fields.type || "text/vnd.tiddlywiki";
}
} else {
// Otherwise, we need to construct a default value for the editor
switch(this.editField) {
case "text":
value = "Type the text for the tiddler '" + this.editTitle + "'";
type = "text/vnd.tiddlywiki";
break;
case "title":
value = this.editTitle;
break;
default:
value = "";
break;
}
if(this.editDefault !== undefined) {
value = this.editDefault;
}
}
update = function(value) {
var tiddler = self.wiki.getTiddler(self.editTitle),
updateFields = {
title: self.editTitle
};
updateFields[self.editField] = value;
self.wiki.addTiddler(new $tw.Tiddler(self.wiki.getCreationFields(),tiddler,updateFields,self.wiki.getModificationFields()));
};
}
if(this.editType) {
type = this.editType;
}
return {value: value || "", type: type, update: update};
};
/*
Compute the internal state of the widget
*/
EditCodeMirrorWidget.prototype.execute = function() {
// Get our parameters
this.editTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
this.editField = this.getAttribute("field","text");
this.editIndex = this.getAttribute("index");
this.editDefault = this.getAttribute("default");
this.editType = this.getAttribute("type");
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
EditCodeMirrorWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
// Completely rerender if any of our attributes have changed
if(changedAttributes.tiddler || changedAttributes.field || changedAttributes.index) {
this.refreshSelf();
return true;
} else if(changedTiddlers[this.editTitle]) {
var editInfo = this.getEditInfo();
this.updateEditor(editInfo.value,editInfo.type);
return true;
}
return false;
};
/*
Update the editor with new text and type. This method is separate from updateEditorDomNode()
so that subclasses can override updateEditor() and still use updateEditorDomNode()
*/
EditCodeMirrorWidget.prototype.updateEditor = function(text,type) {
this.updateEditorDomNode(text);
this.codeMirrorInstance.setOption("mode",type);
};
/*
Update the editor dom node with new text
*/
EditCodeMirrorWidget.prototype.updateEditorDomNode = function(text) {
if(this.codeMirrorInstance) {
if(!this.codeMirrorInstance.hasFocus()) {
this.codeMirrorInstance.setValue(text);
}
}
};
EditCodeMirrorWidget.prototype.saveChanges = function(text) {
var editInfo = this.getEditInfo();
if(text !== editInfo.value) {
editInfo.update(text);
}
};
exports["edit-codemirror"] = EditCodeMirrorWidget;
})();
/*\
title: $:/core/modules/widgets/edit-text.js
type: application/javascript
module-type: widget
Edit-text widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var DEFAULT_MIN_TEXT_AREA_HEIGHT = "100px"; // Minimum height of textareas in pixels
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var EditTextWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
EditTextWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
EditTextWidget.prototype.render = function(parent,nextSibling) {
var self = this;
// Save the parent dom node
this.parentDomNode = parent;
// Compute our attributes
this.computeAttributes();
// Execute our logic
this.execute();
// Create our element
var editInfo = this.getEditInfo(),
tag = this.editTag;
if($tw.config.htmlUnsafeElements.indexOf(tag) !== -1) {
tag = "input";
}
var domNode = this.document.createElement(tag);
if(this.editType) {
domNode.setAttribute("type",this.editType);
}
if(editInfo.value === "" && this.editPlaceholder) {
domNode.setAttribute("placeholder",this.editPlaceholder);
}
if(this.editSize) {
domNode.setAttribute("size",this.editSize);
}
if(this.editRows) {
domNode.setAttribute("rows",this.editRows);
}
// Assign classes
if(this.editClass) {
domNode.className = this.editClass;
}
// Set the text
if(this.editTag === "textarea") {
domNode.appendChild(this.document.createTextNode(editInfo.value));
} else {
domNode.value = editInfo.value;
}
// Add an input event handler
$tw.utils.addEventListeners(domNode,[
{name: "focus", handlerObject: this, handlerMethod: "handleFocusEvent"},
{name: "input", handlerObject: this, handlerMethod: "handleInputEvent"}
]);
// Insert the element into the DOM
parent.insertBefore(domNode,nextSibling);
this.domNodes.push(domNode);
if(this.postRender) {
this.postRender();
}
// Fix height
this.fixHeight();
// Focus field
if(this.editFocus === "true") {
if(domNode.focus && domNode.select) {
domNode.focus();
domNode.select();
}
}
};
/*
Get the tiddler being edited and current value
*/
EditTextWidget.prototype.getEditInfo = function() {
// Get the edit value
var self = this,
value,
update;
if(this.editIndex) {
value = this.wiki.extractTiddlerDataItem(this.editTitle,this.editIndex,this.editDefault);
update = function(value) {
var data = self.wiki.getTiddlerData(self.editTitle,{});
if(data[self.editIndex] !== value) {
data[self.editIndex] = value;
self.wiki.setTiddlerData(self.editTitle,data);
}
};
} else {
// Get the current tiddler and the field name
var tiddler = this.wiki.getTiddler(this.editTitle);
if(tiddler) {
// If we've got a tiddler, the value to display is the field string value
value = tiddler.getFieldString(this.editField);
} else {
// Otherwise, we need to construct a default value for the editor
switch(this.editField) {
case "text":
value = "Type the text for the tiddler '" + this.editTitle + "'";
break;
case "title":
value = this.editTitle;
break;
default:
value = "";
break;
}
if(this.editDefault !== undefined) {
value = this.editDefault;
}
}
update = function(value) {
var tiddler = self.wiki.getTiddler(self.editTitle),
updateFields = {
title: self.editTitle
};
updateFields[self.editField] = value;
self.wiki.addTiddler(new $tw.Tiddler(self.wiki.getCreationFields(),tiddler,updateFields,self.wiki.getModificationFields()));
};
}
return {value: value, update: update};
};
/*
Compute the internal state of the widget
*/
EditTextWidget.prototype.execute = function() {
// Get our parameters
this.editTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
this.editField = this.getAttribute("field","text");
this.editIndex = this.getAttribute("index");
this.editDefault = this.getAttribute("default");
this.editClass = this.getAttribute("class");
this.editPlaceholder = this.getAttribute("placeholder");
this.editSize = this.getAttribute("size");
this.editRows = this.getAttribute("rows");
this.editAutoHeight = this.getAttribute("autoHeight","yes") === "yes";
this.editMinHeight = this.getAttribute("minHeight",DEFAULT_MIN_TEXT_AREA_HEIGHT);
this.editFocusPopup = this.getAttribute("focusPopup");
this.editFocus = this.getAttribute("focus");
// Get the editor element tag and type
var tag,type;
if(this.editField === "text") {
tag = "textarea";
} else {
tag = "input";
var fieldModule = $tw.Tiddler.fieldModules[this.editField];
if(fieldModule && fieldModule.editTag) {
tag = fieldModule.editTag;
}
if(fieldModule && fieldModule.editType) {
type = fieldModule.editType;
}
type = type || "text";
}
// Get the rest of our parameters
this.editTag = this.getAttribute("tag",tag);
this.editType = this.getAttribute("type",type);
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
EditTextWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
// Completely rerender if any of our attributes have changed
if(changedAttributes.tiddler || changedAttributes.field || changedAttributes.index || changedAttributes["default"] || changedAttributes["class"] || changedAttributes.placeholder || changedAttributes.size || changedAttributes.autoHeight || changedAttributes.minHeight || changedAttributes.focusPopup || changedAttributes.rows) {
this.refreshSelf();
return true;
} else if(changedTiddlers[this.editTitle]) {
this.updateEditor(this.getEditInfo().value);
return true;
}
// Fix the height anyway in case there has been a reflow
this.fixHeight();
return false;
};
/*
Update the editor with new text. This method is separate from updateEditorDomNode()
so that subclasses can override updateEditor() and still use updateEditorDomNode()
*/
EditTextWidget.prototype.updateEditor = function(text) {
this.updateEditorDomNode(text);
};
/*
Update the editor dom node with new text
*/
EditTextWidget.prototype.updateEditorDomNode = function(text) {
// Replace the edit value if the tiddler we're editing has changed
var domNode = this.domNodes[0];
if(!domNode.isTiddlyWikiFakeDom) {
if(this.document.activeElement !== domNode) {
domNode.value = text;
}
// Fix the height if needed
this.fixHeight();
}
};
/*
Get the first parent element that has scrollbars or use the body as fallback.
*/
EditTextWidget.prototype.getScrollContainer = function(el) {
while(el.parentNode) {
el = el.parentNode;
if(el.scrollTop) {
return el;
}
}
return this.document.body;
};
/*
Fix the height of textareas to fit their content
*/
EditTextWidget.prototype.fixHeight = function() {
var domNode = this.domNodes[0];
if(this.editAutoHeight && domNode && !domNode.isTiddlyWikiFakeDom && this.editTag === "textarea") {
// Resize the textarea to fit its content, preserving scroll position
// Get the scroll container and register the current scroll position
var container = this.getScrollContainer(domNode),
scrollTop = container.scrollTop;
// Measure the specified minimum height
domNode.style.height = this.editMinHeight;
var minHeight = domNode.offsetHeight;
// Set its height to auto so that it snaps to the correct height
domNode.style.height = "auto";
// Calculate the revised height
var newHeight = Math.max(domNode.scrollHeight + domNode.offsetHeight - domNode.clientHeight,minHeight);
// Only try to change the height if it has changed
if(newHeight !== domNode.offsetHeight) {
domNode.style.height = newHeight + "px";
// Make sure that the dimensions of the textarea are recalculated
$tw.utils.forceLayout(domNode);
// Set the container to the position we registered at the beginning
container.scrollTop = scrollTop;
}
}
};
/*
Handle a dom "input" event
*/
EditTextWidget.prototype.handleInputEvent = function(event) {
this.saveChanges(this.domNodes[0].value);
this.fixHeight();
return true;
};
EditTextWidget.prototype.handleFocusEvent = function(event) {
if(this.editFocusPopup) {
$tw.popup.triggerPopup({
domNode: this.domNodes[0],
title: this.editFocusPopup,
wiki: this.wiki,
force: true
});
}
return true;
};
EditTextWidget.prototype.saveChanges = function(text) {
var editInfo = this.getEditInfo();
if(text !== editInfo.value) {
editInfo.update(text);
}
};
exports["edit-text"] = EditTextWidget;
})();
/*\
title: $:/core/modules/widgets/edit.js
type: application/javascript
module-type: widget
Edit widget is a meta-widget chooses the appropriate actual editting widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var EditWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
EditWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
EditWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
// Mappings from content type to editor type are stored in tiddlers with this prefix
var EDITOR_MAPPING_PREFIX = "$:/config/EditorTypeMappings/";
/*
Compute the internal state of the widget
*/
EditWidget.prototype.execute = function() {
// Get our parameters
this.editTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
this.editField = this.getAttribute("field","text");
this.editIndex = this.getAttribute("index");
this.editClass = this.getAttribute("class");
this.editPlaceholder = this.getAttribute("placeholder");
// Choose the appropriate edit widget
this.editorType = this.getEditorType();
// Make the child widgets
this.makeChildWidgets([{
type: "edit-" + this.editorType,
attributes: {
tiddler: {type: "string", value: this.editTitle},
field: {type: "string", value: this.editField},
index: {type: "string", value: this.editIndex},
"class": {type: "string", value: this.editClass},
"placeholder": {type: "string", value: this.editPlaceholder}
}
}]);
};
EditWidget.prototype.getEditorType = function() {
// Get the content type of the thing we're editing
var type;
if(this.editField === "text") {
var tiddler = this.wiki.getTiddler(this.editTitle);
if(tiddler) {
type = tiddler.fields.type;
}
}
type = type || "text/vnd.tiddlywiki";
var editorType = this.wiki.getTiddlerText(EDITOR_MAPPING_PREFIX + type);
if(!editorType) {
var typeInfo = $tw.config.contentTypeInfo[type];
if(typeInfo && typeInfo.encoding === "base64") {
editorType = "binary";
} else {
editorType = "text";
}
}
return editorType;
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
EditWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
// Refresh if an attribute has changed, or the type associated with the target tiddler has changed
if(changedAttributes.tiddler || changedAttributes.field || changedAttributes.index || (changedTiddlers[this.editTitle] && this.getEditorType() !== this.editorType)) {
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
exports.edit = EditWidget;
})();
/*\
title: $:/core/modules/widgets/element.js
type: application/javascript
module-type: widget
Element widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var ElementWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
ElementWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
ElementWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
// Neuter blacklisted elements
var tag = this.parseTreeNode.tag;
if($tw.config.htmlUnsafeElements.indexOf(tag) !== -1) {
tag = "safe-" + tag;
}
var domNode = this.document.createElementNS(this.namespace,tag);
this.assignAttributes(domNode,{excludeEventAttributes: true});
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
};
/*
Compute the internal state of the widget
*/
ElementWidget.prototype.execute = function() {
// Select the namespace for the tag
var tagNamespaces = {
svg: "http://www.w3.org/2000/svg",
math: "http://www.w3.org/1998/Math/MathML",
body: "http://www.w3.org/1999/xhtml"
};
this.namespace = tagNamespaces[this.parseTreeNode.tag];
if(this.namespace) {
this.setVariable("namespace",this.namespace);
} else {
this.namespace = this.getVariable("namespace",{defaultValue: "http://www.w3.org/1999/xhtml"});
}
// Make the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ElementWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes(),
hasChangedAttributes = $tw.utils.count(changedAttributes) > 0;
if(hasChangedAttributes) {
// Update our attributes
this.assignAttributes(this.domNodes[0],{excludeEventAttributes: true});
}
return this.refreshChildren(changedTiddlers) || hasChangedAttributes;
};
exports.element = ElementWidget;
})();
/*\
title: $:/core/modules/widgets/encrypt.js
type: application/javascript
module-type: widget
Encrypt widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var EncryptWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
EncryptWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
EncryptWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
var textNode = this.document.createTextNode(this.encryptedText);
parent.insertBefore(textNode,nextSibling);
this.domNodes.push(textNode);
};
/*
Compute the internal state of the widget
*/
EncryptWidget.prototype.execute = function() {
// Get parameters from our attributes
this.filter = this.getAttribute("filter","[!is[system]]");
// Encrypt the filtered tiddlers
var tiddlers = this.wiki.filterTiddlers(this.filter),
json = {},
self = this;
$tw.utils.each(tiddlers,function(title) {
var tiddler = self.wiki.getTiddler(title),
jsonTiddler = {};
for(var f in tiddler.fields) {
jsonTiddler[f] = tiddler.getFieldString(f);
}
json[title] = jsonTiddler;
});
this.encryptedText = $tw.utils.htmlEncode($tw.crypto.encrypt(JSON.stringify(json)));
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
EncryptWidget.prototype.refresh = function(changedTiddlers) {
// We don't need to worry about refreshing because the encrypt widget isn't for interactive use
return false;
};
exports.encrypt = EncryptWidget;
})();
/*\
title: $:/core/modules/widgets/entity.js
type: application/javascript
module-type: widget
HTML entity widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var EntityWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
EntityWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
EntityWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.execute();
var textNode = this.document.createTextNode($tw.utils.entityDecode(this.parseTreeNode.entity));
parent.insertBefore(textNode,nextSibling);
this.domNodes.push(textNode);
};
/*
Compute the internal state of the widget
*/
EntityWidget.prototype.execute = function() {
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
EntityWidget.prototype.refresh = function(changedTiddlers) {
return false;
};
exports.entity = EntityWidget;
})();
/*\
title: $:/core/modules/widgets/fieldmangler.js
type: application/javascript
module-type: widget
Field mangler widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var FieldManglerWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
this.addEventListeners([
{type: "tm-remove-field", handler: "handleRemoveFieldEvent"},
{type: "tm-add-field", handler: "handleAddFieldEvent"},
{type: "tm-remove-tag", handler: "handleRemoveTagEvent"},
{type: "tm-add-tag", handler: "handleAddTagEvent"}
]);
};
/*
Inherit from the base widget class
*/
FieldManglerWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
FieldManglerWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
FieldManglerWidget.prototype.execute = function() {
// Get our parameters
this.mangleTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
// Construct the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
FieldManglerWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.tiddler) {
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
FieldManglerWidget.prototype.handleRemoveFieldEvent = function(event) {
var tiddler = this.wiki.getTiddler(this.mangleTitle),
deletion = {};
deletion[event.param] = undefined;
this.wiki.addTiddler(new $tw.Tiddler(tiddler,deletion));
return true;
};
FieldManglerWidget.prototype.handleAddFieldEvent = function(event) {
var tiddler = this.wiki.getTiddler(this.mangleTitle),
addition = this.wiki.getModificationFields(),
hadInvalidFieldName = false,
addField = function(name,value) {
var trimmedName = name.toLowerCase().trim();
if(!$tw.utils.isValidFieldName(trimmedName)) {
if(!hadInvalidFieldName) {
alert($tw.language.getString(
"InvalidFieldName",
{variables:
{fieldName: trimmedName}
}
));
hadInvalidFieldName = true;
return;
}
} else {
if(!value && tiddler) {
value = tiddler.fields[trimmedName];
}
addition[trimmedName] = value || "";
}
return;
};
addition.title = this.mangleTitle;
if(typeof event.param === "string") {
addField(event.param,"");
}
if(typeof event.paramObject === "object") {
for(var name in event.paramObject) {
addField(name,event.paramObject[name]);
}
}
this.wiki.addTiddler(new $tw.Tiddler(tiddler,addition));
return true;
};
FieldManglerWidget.prototype.handleRemoveTagEvent = function(event) {
var tiddler = this.wiki.getTiddler(this.mangleTitle);
if(tiddler && tiddler.fields.tags) {
var p = tiddler.fields.tags.indexOf(event.param);
if(p !== -1) {
var modification = this.wiki.getModificationFields();
modification.tags = (tiddler.fields.tags || []).slice(0);
modification.tags.splice(p,1);
if(modification.tags.length === 0) {
modification.tags = undefined;
}
this.wiki.addTiddler(new $tw.Tiddler(tiddler,modification));
}
}
return true;
};
FieldManglerWidget.prototype.handleAddTagEvent = function(event) {
var tiddler = this.wiki.getTiddler(this.mangleTitle);
if(tiddler && typeof event.param === "string") {
var tag = event.param.trim();
if(tag !== "") {
var modification = this.wiki.getModificationFields();
modification.tags = (tiddler.fields.tags || []).slice(0);
$tw.utils.pushTop(modification.tags,tag);
this.wiki.addTiddler(new $tw.Tiddler(tiddler,modification));
}
} else if(typeof event.param === "string" && event.param.trim() !== "" && this.mangleTitle.trim() !== "") {
var tag = [];
tag.push(event.param.trim());
this.wiki.addTiddler({title: this.mangleTitle, tags: tag});
}
return true;
};
exports.fieldmangler = FieldManglerWidget;
})();
/*\
title: $:/core/modules/widgets/fields.js
type: application/javascript
module-type: widget
Fields widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var FieldsWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
FieldsWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
FieldsWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
var textNode = this.document.createTextNode(this.text);
parent.insertBefore(textNode,nextSibling);
this.domNodes.push(textNode);
};
/*
Compute the internal state of the widget
*/
FieldsWidget.prototype.execute = function() {
// Get parameters from our attributes
this.tiddlerTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
this.template = this.getAttribute("template");
this.exclude = this.getAttribute("exclude");
this.stripTitlePrefix = this.getAttribute("stripTitlePrefix","no") === "yes";
// Get the value to display
var tiddler = this.wiki.getTiddler(this.tiddlerTitle);
// Get the exclusion list
var exclude;
if(this.exclude) {
exclude = this.exclude.split(" ");
} else {
exclude = ["text"];
}
// Compose the template
var text = [];
if(this.template && tiddler) {
var fields = [];
for(var fieldName in tiddler.fields) {
if(exclude.indexOf(fieldName) === -1) {
fields.push(fieldName);
}
}
fields.sort();
for(var f=0; f<fields.length; f++) {
fieldName = fields[f];
if(exclude.indexOf(fieldName) === -1) {
var row = this.template,
value = tiddler.getFieldString(fieldName);
if(this.stripTitlePrefix && fieldName === "title") {
var reStrip = /^\{[^\}]+\}(.+)/mg,
reMatch = reStrip.exec(value);
if(reMatch) {
value = reMatch[1];
}
}
row = row.replace("$name$",fieldName);
row = row.replace("$value$",value);
row = row.replace("$encoded_value$",$tw.utils.htmlEncode(value));
text.push(row);
}
}
}
this.text = text.join("");
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
FieldsWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.tiddler || changedAttributes.template || changedAttributes.exclude || changedAttributes.stripTitlePrefix || changedTiddlers[this.tiddlerTitle]) {
this.refreshSelf();
return true;
} else {
return false;
}
};
exports.fields = FieldsWidget;
})();
/*\
title: $:/core/modules/widgets/image.js
type: application/javascript
module-type: widget
The image widget displays an image referenced with an external URI or with a local tiddler title.
```
<$image src="TiddlerTitle" width="320" height="400" class="classnames">
```
The image source can be the title of an existing tiddler or the URL of an external image.
External images always generate an HTML `<img>` tag.
Tiddlers that have a _canonical_uri field generate an HTML `<img>` tag with the src attribute containing the URI.
Tiddlers that contain image data generate an HTML `<img>` tag with the src attribute containing a base64 representation of the image.
Tiddlers that contain wikitext could be rendered to a DIV of the usual size of a tiddler, and then transformed to the size requested.
The width and height attributes are interpreted as a number of pixels, and do not need to include the "px" suffix.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var ImageWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
ImageWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
ImageWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
// Create element
// Determine what type of image it is
var tag = "img", src = "",
tiddler = this.wiki.getTiddler(this.imageSource);
if(!tiddler) {
// The source isn't the title of a tiddler, so we'll assume it's a URL
src = this.getVariable("tv-get-export-image-link",{params: [{name: "src",value: this.imageSource}],defaultValue: this.imageSource});
} else {
// Check if it is an image tiddler
if(this.wiki.isImageTiddler(this.imageSource)) {
var type = tiddler.fields.type,
text = tiddler.fields.text,
_canonical_uri = tiddler.fields._canonical_uri;
// If the tiddler has body text then it doesn't need to be lazily loaded
if(text) {
// Render the appropriate element for the image type
switch(type) {
case "application/pdf":
tag = "embed";
src = "data:application/pdf;base64," + text;
break;
case "image/svg+xml":
src = "data:image/svg+xml," + encodeURIComponent(text);
break;
default:
src = "data:" + type + ";base64," + text;
break;
}
} else if(_canonical_uri) {
switch(type) {
case "application/pdf":
tag = "embed";
src = _canonical_uri;
break;
case "image/svg+xml":
src = _canonical_uri;
break;
default:
src = _canonical_uri;
break;
}
} else this.wiki.getTiddlerText(this.imageSource);
}
}
// Create the element and assign the attributes
var domNode = this.document.createElement(tag);
domNode.setAttribute("src",src);
if(this.imageClass) {
domNode.setAttribute("class",this.imageClass);
}
if(this.imageWidth) {
domNode.setAttribute("width",this.imageWidth);
}
if(this.imageHeight) {
domNode.setAttribute("height",this.imageHeight);
}
if(this.imageTooltip) {
domNode.setAttribute("title",this.imageTooltip);
}
if(this.imageAlt) {
domNode.setAttribute("alt",this.imageAlt);
}
// Insert element
parent.insertBefore(domNode,nextSibling);
this.domNodes.push(domNode);
};
/*
Compute the internal state of the widget
*/
ImageWidget.prototype.execute = function() {
// Get our parameters
this.imageSource = this.getAttribute("source");
this.imageWidth = this.getAttribute("width");
this.imageHeight = this.getAttribute("height");
this.imageClass = this.getAttribute("class");
this.imageTooltip = this.getAttribute("tooltip");
this.imageAlt = this.getAttribute("alt");
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ImageWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.source || changedAttributes.width || changedAttributes.height || changedAttributes["class"] || changedAttributes.tooltip || changedTiddlers[this.imageSource]) {
this.refreshSelf();
return true;
} else {
return false;
}
};
exports.image = ImageWidget;
})();
/*\
title: $:/core/modules/widgets/importvariables.js
type: application/javascript
module-type: widget
Import variable definitions from other tiddlers
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var ImportVariablesWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
ImportVariablesWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
ImportVariablesWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
ImportVariablesWidget.prototype.execute = function(tiddlerList) {
var self = this;
// Get our parameters
this.filter = this.getAttribute("filter");
// Compute the filter
this.tiddlerList = tiddlerList || this.wiki.filterTiddlers(this.filter,this);
// Accumulate the <$set> widgets from each tiddler
var widgetStackStart,widgetStackEnd;
function addWidgetNode(widgetNode) {
if(widgetNode) {
if(!widgetStackStart && !widgetStackEnd) {
widgetStackStart = widgetNode;
widgetStackEnd = widgetNode;
} else {
widgetStackEnd.children = [widgetNode];
widgetStackEnd = widgetNode;
}
}
}
$tw.utils.each(this.tiddlerList,function(title) {
var parser = self.wiki.parseTiddler(title);
if(parser) {
var parseTreeNode = parser.tree[0];
while(parseTreeNode && parseTreeNode.type === "set") {
addWidgetNode({
type: "set",
attributes: parseTreeNode.attributes,
params: parseTreeNode.params
});
parseTreeNode = parseTreeNode.children[0];
}
}
});
// Add our own children to the end of the pile
var parseTreeNodes;
if(widgetStackStart && widgetStackEnd) {
parseTreeNodes = [widgetStackStart];
widgetStackEnd.children = this.parseTreeNode.children;
} else {
parseTreeNodes = this.parseTreeNode.children;
}
// Construct the child widgets
this.makeChildWidgets(parseTreeNodes);
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ImportVariablesWidget.prototype.refresh = function(changedTiddlers) {
// Recompute our attributes and the filter list
var changedAttributes = this.computeAttributes(),
tiddlerList = this.wiki.filterTiddlers(this.getAttribute("filter"),this);
// Refresh if the filter has changed, or the list of tiddlers has changed, or any of the tiddlers in the list has changed
function haveListedTiddlersChanged() {
var changed = false;
tiddlerList.forEach(function(title) {
if(changedTiddlers[title]) {
changed = true;
}
});
return changed;
}
if(changedAttributes.filter || !$tw.utils.isArrayEqual(this.tiddlerList,tiddlerList) || haveListedTiddlersChanged()) {
// Compute the filter
this.removeChildDomNodes();
this.execute(tiddlerList);
this.renderChildren(this.parentDomNode,this.findNextSiblingDomNode());
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
exports.importvariables = ImportVariablesWidget;
})();
/*\
title: $:/core/modules/widgets/keyboard.js
type: application/javascript
module-type: widget
Keyboard shortcut widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var KeyboardWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
KeyboardWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
KeyboardWidget.prototype.render = function(parent,nextSibling) {
var self = this;
// Remember parent
this.parentDomNode = parent;
// Compute attributes and execute state
this.computeAttributes();
this.execute();
// Create element
var domNode = this.document.createElement("div");
// Assign classes
var classes = (this["class"] || "").split(" ");
classes.push("tc-keyboard");
domNode.className = classes.join(" ");
// Add a keyboard event handler
domNode.addEventListener("keydown",function (event) {
if($tw.utils.checkKeyDescriptor(event,self.keyInfo)) {
self.invokeActions(this,event);
self.dispatchMessage(event);
event.preventDefault();
event.stopPropagation();
return true;
}
return false;
},false);
// Insert element
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
};
KeyboardWidget.prototype.dispatchMessage = function(event) {
this.dispatchEvent({type: this.message, param: this.param, tiddlerTitle: this.getVariable("currentTiddler")});
};
/*
Compute the internal state of the widget
*/
KeyboardWidget.prototype.execute = function() {
// Get attributes
this.message = this.getAttribute("message");
this.param = this.getAttribute("param");
this.key = this.getAttribute("key");
this.keyInfo = $tw.utils.parseKeyDescriptor(this.key);
this["class"] = this.getAttribute("class");
// Make child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
KeyboardWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.message || changedAttributes.param || changedAttributes.key || changedAttributes["class"]) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
exports.keyboard = KeyboardWidget;
})();
/*\
title: $:/core/modules/widgets/link-dragover-extend.js
type: application/javascript
module-type: widget
Extend the link widget to allow click when there is a drag over (option)
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var LinkWidget = require("$:/core/modules/widgets/link.js")["link"];
LinkWidget.prototype.bjDragExtend ={};
LinkWidget.prototype.bjDragExtend.renderLink = LinkWidget.prototype.renderLink;
LinkWidget.prototype.renderLink = function (parent,nextSibling) {
LinkWidget.prototype.bjDragExtend.renderLink.call(this,parent,nextSibling);
if (this.dragoverclick==="yes") {
$tw.utils.addEventListeners(this.domNodes[0],[
{name: "dragover", handlerObject: this, handlerMethod: "handleDragOverEvent"}
]);
}
}
/*
add option
*/
LinkWidget.prototype.bjDragExtend.execute = LinkWidget.prototype.execute;
LinkWidget.prototype.execute = function() {
LinkWidget.prototype.bjDragExtend.execute.call(this);
this.dragoverclick=this.getAttribute("dragoverclic","no");
};
/*
handle dragover
*/
LinkWidget.prototype.handleDragOverEvent = function(event) {
// Tell the browser that we're still interested in the drop
event.preventDefault();
// Send the drag as click as a navigate event
var bounds = this.domNodes[0].getBoundingClientRect();
this.dispatchEvent({
type: "tm-navigate",
navigateTo: this.to,
navigateFromTitle: this.getVariable("storyTiddler"),
navigateFromNode: this,
navigateFromClientRect: { top: bounds.top, left: bounds.left, width: bounds.width, right: bounds.right, bottom: bounds.bottom, height: bounds.height
},
navigateSuppressNavigation: event.metaKey || event.ctrlKey
});
event.preventDefault();
event.stopPropagation();
return false;
};
})();
/*\
title: $:/core/modules/widgets/link.js
type: application/javascript
module-type: widget
Link widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var LinkWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
LinkWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
LinkWidget.prototype.render = function(parent,nextSibling) {
// Save the parent dom node
this.parentDomNode = parent;
// Compute our attributes
this.computeAttributes();
// Execute our logic
this.execute();
// Get the value of the tv-wikilinks configuration macro
var wikiLinksMacro = this.getVariable("tv-wikilinks"),
useWikiLinks = wikiLinksMacro ? (wikiLinksMacro.trim() !== "no") : true;
// Render the link if required
if(useWikiLinks) {
this.renderLink(parent,nextSibling);
} else {
// Just insert the link text
var domNode = this.document.createElement("span");
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
}
};
/*
Render this widget into the DOM
*/
LinkWidget.prototype.renderLink = function(parent,nextSibling) {
var self = this;
// Sanitise the specified tag
var tag = this.linkTag;
if($tw.config.htmlUnsafeElements.indexOf(tag) !== -1) {
tag = "a";
}
// Create our element
var domNode = this.document.createElement(tag);
// Assign classes
var classes = [];
if(this.linkClasses) {
classes.push(this.linkClasses);
}
classes.push("tc-tiddlylink");
if(this.isShadow) {
classes.push("tc-tiddlylink-shadow");
}
if(this.isMissing && !this.isShadow) {
classes.push("tc-tiddlylink-missing");
} else {
if(!this.isMissing) {
classes.push("tc-tiddlylink-resolves");
}
}
domNode.setAttribute("class",classes.join(" "));
// Set an href
var wikiLinkTemplateMacro = this.getVariable("tv-wikilink-template"),
wikiLinkTemplate = wikiLinkTemplateMacro ? wikiLinkTemplateMacro.trim() : "#$uri_encoded$",
wikiLinkText = wikiLinkTemplate.replace("$uri_encoded$",encodeURIComponent(this.to));
wikiLinkText = wikiLinkText.replace("$uri_doubleencoded$",encodeURIComponent(encodeURIComponent(this.to)));
wikiLinkText = this.getVariable("tv-get-export-link",{params: [{name: "to",value: this.to}],defaultValue: wikiLinkText});
if(tag === "a") {
domNode.setAttribute("href",wikiLinkText);
}
if(this.tabIndex) {
domNode.setAttribute("tabindex",this.tabIndex);
}
// Set the tooltip
// HACK: Performance issues with re-parsing the tooltip prevent us defaulting the tooltip to "<$transclude field='tooltip'><$transclude field='title'/></$transclude>"
var tooltipWikiText = this.tooltip || this.getVariable("tv-wikilink-tooltip");
if(tooltipWikiText) {
var tooltipText = this.wiki.renderText("text/plain","text/vnd.tiddlywiki",tooltipWikiText,{
parseAsInline: true,
variables: {
currentTiddler: this.to
},
parentWidget: this
});
domNode.setAttribute("title",tooltipText);
}
if(this["aria-label"]) {
domNode.setAttribute("aria-label",this["aria-label"]);
}
// Add a click event handler
$tw.utils.addEventListeners(domNode,[
{name: "click", handlerObject: this, handlerMethod: "handleClickEvent"},
]);
if(this.draggable === "yes") {
$tw.utils.addEventListeners(domNode,[
{name: "dragstart", handlerObject: this, handlerMethod: "handleDragStartEvent"},
{name: "dragend", handlerObject: this, handlerMethod: "handleDragEndEvent"}
]);
}
// Insert the link into the DOM and render any children
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
};
LinkWidget.prototype.handleClickEvent = function(event) {
// Send the click on its way as a navigate event
var bounds = this.domNodes[0].getBoundingClientRect();
this.dispatchEvent({
type: "tm-navigate",
navigateTo: this.to,
navigateFromTitle: this.getVariable("storyTiddler"),
navigateFromNode: this,
navigateFromClientRect: { top: bounds.top, left: bounds.left, width: bounds.width, right: bounds.right, bottom: bounds.bottom, height: bounds.height
},
navigateSuppressNavigation: event.metaKey || event.ctrlKey || (event.button === 1)
});
if(this.domNodes[0].hasAttribute("href")) {
event.preventDefault();
}
event.stopPropagation();
return false;
};
LinkWidget.prototype.handleDragStartEvent = function(event) {
if(event.target === this.domNodes[0]) {
if(this.to) {
$tw.dragInProgress = true;
// Set the dragging class on the element being dragged
$tw.utils.addClass(event.target,"tc-tiddlylink-dragging");
// Create the drag image elements
this.dragImage = this.document.createElement("div");
this.dragImage.className = "tc-tiddler-dragger";
var inner = this.document.createElement("div");
inner.className = "tc-tiddler-dragger-inner";
inner.appendChild(this.document.createTextNode(this.to));
this.dragImage.appendChild(inner);
this.document.body.appendChild(this.dragImage);
// Astoundingly, we need to cover the dragger up: http://www.kryogenix.org/code/browser/custom-drag-image.html
var cover = this.document.createElement("div");
cover.className = "tc-tiddler-dragger-cover";
cover.style.left = (inner.offsetLeft - 16) + "px";
cover.style.top = (inner.offsetTop - 16) + "px";
cover.style.width = (inner.offsetWidth + 32) + "px";
cover.style.height = (inner.offsetHeight + 32) + "px";
this.dragImage.appendChild(cover);
// Set the data transfer properties
var dataTransfer = event.dataTransfer;
// First the image
dataTransfer.effectAllowed = "copy";
if(dataTransfer.setDragImage) {
dataTransfer.setDragImage(this.dragImage.firstChild,-16,-16);
}
// Then the data
dataTransfer.clearData();
var jsonData = this.wiki.getTiddlerAsJson(this.to),
textData = this.wiki.getTiddlerText(this.to,""),
title = (new RegExp("^" + $tw.config.textPrimitives.wikiLink + "$","mg")).exec(this.to) ? this.to : "[[" + this.to + "]]";
// IE doesn't like these content types
if(!$tw.browser.isIE) {
dataTransfer.setData("text/vnd.tiddler",jsonData);
dataTransfer.setData("text/plain",title);
dataTransfer.setData("text/x-moz-url","data:text/vnd.tiddler," + encodeURIComponent(jsonData));
}
dataTransfer.setData("URL","data:text/vnd.tiddler," + encodeURIComponent(jsonData));
dataTransfer.setData("Text",title);
event.stopPropagation();
} else {
event.preventDefault();
}
}
};
LinkWidget.prototype.handleDragEndEvent = function(event) {
if(event.target === this.domNodes[0]) {
$tw.dragInProgress = false;
// Remove the dragging class on the element being dragged
$tw.utils.removeClass(event.target,"tc-tiddlylink-dragging");
// Delete the drag image element
if(this.dragImage) {
this.dragImage.parentNode.removeChild(this.dragImage);
}
}
};
/*
Compute the internal state of the widget
*/
LinkWidget.prototype.execute = function() {
// Pick up our attributes
this.to = this.getAttribute("to",this.getVariable("currentTiddler"));
this.tooltip = this.getAttribute("tooltip");
this["aria-label"] = this.getAttribute("aria-label");
this.linkClasses = this.getAttribute("class");
this.tabIndex = this.getAttribute("tabindex");
this.draggable = this.getAttribute("draggable","yes");
this.linkTag = this.getAttribute("tag","a");
// Determine the link characteristics
this.isMissing = !this.wiki.tiddlerExists(this.to);
this.isShadow = this.wiki.isShadowTiddler(this.to);
// Make the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
LinkWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.to || changedTiddlers[this.to] || changedAttributes["aria-label"] || changedAttributes.tooltip) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
exports.link = LinkWidget;
})();
/*\
title: $:/core/modules/widgets/linkcatcher.js
type: application/javascript
module-type: widget
Linkcatcher widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var LinkCatcherWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
this.addEventListeners([
{type: "tm-navigate", handler: "handleNavigateEvent"}
]);
};
/*
Inherit from the base widget class
*/
LinkCatcherWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
LinkCatcherWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
LinkCatcherWidget.prototype.execute = function() {
// Get our parameters
this.catchTo = this.getAttribute("to");
this.catchMessage = this.getAttribute("message");
this.catchSet = this.getAttribute("set");
this.catchSetTo = this.getAttribute("setTo");
// Construct the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
LinkCatcherWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.to || changedAttributes.message || changedAttributes.set || changedAttributes.setTo) {
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
/*
Handle a tm-navigate event
*/
LinkCatcherWidget.prototype.handleNavigateEvent = function(event) {
if(this.catchTo) {
this.wiki.setTextReference(this.catchTo,event.navigateTo,this.getVariable("currentTiddler"));
}
if(this.catchMessage && this.parentWidget) {
this.parentWidget.dispatchEvent({
type: this.catchMessage,
param: event.navigateTo,
navigateTo: event.navigateTo
});
}
if(this.catchSet) {
var tiddler = this.wiki.getTiddler(this.catchSet);
this.wiki.addTiddler(new $tw.Tiddler(tiddler,{title: this.catchSet, text: this.catchSetTo}));
}
return false;
};
exports.linkcatcher = LinkCatcherWidget;
})();
/*\
title: $:/core/modules/widgets/list.js
type: application/javascript
module-type: widget
List and list item widgets
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
/*
The list widget creates list element sub-widgets that reach back into the list widget for their configuration
*/
var ListWidget = function(parseTreeNode,options) {
// Initialise the storyviews if they've not been done already
if(!this.storyViews) {
ListWidget.prototype.storyViews = {};
$tw.modules.applyMethods("storyview",this.storyViews);
}
// Main initialisation inherited from widget.js
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
ListWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
ListWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
// Construct the storyview
var StoryView = this.storyViews[this.storyViewName];
if(StoryView && !this.document.isTiddlyWikiFakeDom) {
this.storyview = new StoryView(this);
} else {
this.storyview = null;
}
};
/*
Compute the internal state of the widget
*/
ListWidget.prototype.execute = function() {
// Get our attributes
this.template = this.getAttribute("template");
this.editTemplate = this.getAttribute("editTemplate");
this.variableName = this.getAttribute("variable","currentTiddler");
this.storyViewName = this.getAttribute("storyview");
this.historyTitle = this.getAttribute("history");
// Compose the list elements
this.list = this.getTiddlerList();
var members = [],
self = this;
// Check for an empty list
if(this.list.length === 0) {
members = this.getEmptyMessage();
} else {
$tw.utils.each(this.list,function(title,index) {
members.push(self.makeItemTemplate(title));
});
}
// Construct the child widgets
this.makeChildWidgets(members);
// Clear the last history
this.history = [];
};
ListWidget.prototype.getTiddlerList = function() {
var defaultFilter = "[!is[system]sort[title]]";
return this.wiki.filterTiddlers(this.getAttribute("filter",defaultFilter),this);
};
ListWidget.prototype.getEmptyMessage = function() {
var emptyMessage = this.getAttribute("emptyMessage",""),
parser = this.wiki.parseText("text/vnd.tiddlywiki",emptyMessage,{parseAsInline: true});
if(parser) {
return parser.tree;
} else {
return [];
}
};
/*
Compose the template for a list item
*/
ListWidget.prototype.makeItemTemplate = function(title) {
// Check if the tiddler is a draft
var tiddler = this.wiki.getTiddler(title),
isDraft = tiddler && tiddler.hasField("draft.of"),
template = this.template,
templateTree;
if(isDraft && this.editTemplate) {
template = this.editTemplate;
}
// Compose the transclusion of the template
if(template) {
templateTree = [{type: "transclude", attributes: {tiddler: {type: "string", value: template}}}];
} else {
if(this.parseTreeNode.children && this.parseTreeNode.children.length > 0) {
templateTree = this.parseTreeNode.children;
} else {
// Default template is a link to the title
templateTree = [{type: "element", tag: this.parseTreeNode.isBlock ? "div" : "span", children: [{type: "link", attributes: {to: {type: "string", value: title}}, children: [
{type: "text", text: title}
]}]}];
}
}
// Return the list item
return {type: "listitem", itemTitle: title, variableName: this.variableName, children: templateTree};
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ListWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes(),
result;
// Call the storyview
if(this.storyview && this.storyview.refreshStart) {
this.storyview.refreshStart(changedTiddlers,changedAttributes);
}
// Completely refresh if any of our attributes have changed
if(changedAttributes.filter || changedAttributes.template || changedAttributes.editTemplate || changedAttributes.emptyMessage || changedAttributes.storyview || changedAttributes.history) {
this.refreshSelf();
result = true;
} else {
// Handle any changes to the list
result = this.handleListChanges(changedTiddlers);
// Handle any changes to the history stack
if(this.historyTitle && changedTiddlers[this.historyTitle]) {
this.handleHistoryChanges();
}
}
// Call the storyview
if(this.storyview && this.storyview.refreshEnd) {
this.storyview.refreshEnd(changedTiddlers,changedAttributes);
}
return result;
};
/*
Handle any changes to the history list
*/
ListWidget.prototype.handleHistoryChanges = function() {
// Get the history data
var newHistory = this.wiki.getTiddlerDataCached(this.historyTitle,[]);
// Ignore any entries of the history that match the previous history
var entry = 0;
while(entry < newHistory.length && entry < this.history.length && newHistory[entry].title === this.history[entry].title) {
entry++;
}
// Navigate forwards to each of the new tiddlers
while(entry < newHistory.length) {
if(this.storyview && this.storyview.navigateTo) {
this.storyview.navigateTo(newHistory[entry]);
}
entry++;
}
// Update the history
this.history = newHistory;
};
/*
Process any changes to the list
*/
ListWidget.prototype.handleListChanges = function(changedTiddlers) {
// Get the new list
var prevList = this.list;
this.list = this.getTiddlerList();
// Check for an empty list
if(this.list.length === 0) {
// Check if it was empty before
if(prevList.length === 0) {
// If so, just refresh the empty message
return this.refreshChildren(changedTiddlers);
} else {
// Replace the previous content with the empty message
for(t=this.children.length-1; t>=0; t--) {
this.removeListItem(t);
}
var nextSibling = this.findNextSiblingDomNode();
this.makeChildWidgets(this.getEmptyMessage());
this.renderChildren(this.parentDomNode,nextSibling);
return true;
}
} else {
// If the list was empty then we need to remove the empty message
if(prevList.length === 0) {
this.removeChildDomNodes();
this.children = [];
}
// Cycle through the list, inserting and removing list items as needed
var hasRefreshed = false;
for(var t=0; t<this.list.length; t++) {
var index = this.findListItem(t,this.list[t]);
if(index === undefined) {
// The list item must be inserted
this.insertListItem(t,this.list[t]);
hasRefreshed = true;
} else {
// There are intervening list items that must be removed
for(var n=index-1; n>=t; n--) {
this.removeListItem(n);
hasRefreshed = true;
}
// Refresh the item we're reusing
var refreshed = this.children[t].refresh(changedTiddlers);
hasRefreshed = hasRefreshed || refreshed;
}
}
// Remove any left over items
for(t=this.children.length-1; t>=this.list.length; t--) {
this.removeListItem(t);
hasRefreshed = true;
}
return hasRefreshed;
}
};
/*
Find the list item with a given title, starting from a specified position
*/
ListWidget.prototype.findListItem = function(startIndex,title) {
while(startIndex < this.children.length) {
if(this.children[startIndex].parseTreeNode.itemTitle === title) {
return startIndex;
}
startIndex++;
}
return undefined;
};
/*
Insert a new list item at the specified index
*/
ListWidget.prototype.insertListItem = function(index,title) {
// Create, insert and render the new child widgets
var widget = this.makeChildWidget(this.makeItemTemplate(title));
widget.parentDomNode = this.parentDomNode; // Hack to enable findNextSiblingDomNode() to work
this.children.splice(index,0,widget);
var nextSibling = widget.findNextSiblingDomNode();
widget.render(this.parentDomNode,nextSibling);
// Animate the insertion if required
if(this.storyview && this.storyview.insert) {
this.storyview.insert(widget);
}
return true;
};
/*
Remove the specified list item
*/
ListWidget.prototype.removeListItem = function(index) {
var widget = this.children[index];
// Animate the removal if required
if(this.storyview && this.storyview.remove) {
this.storyview.remove(widget);
} else {
widget.removeChildDomNodes();
}
// Remove the child widget
this.children.splice(index,1);
};
exports.list = ListWidget;
var ListItemWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
ListItemWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
ListItemWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
ListItemWidget.prototype.execute = function() {
// Set the current list item title
this.setVariable(this.parseTreeNode.variableName,this.parseTreeNode.itemTitle);
// Construct the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ListItemWidget.prototype.refresh = function(changedTiddlers) {
return this.refreshChildren(changedTiddlers);
};
exports.listitem = ListItemWidget;
})();
/*\
title: $:/core/modules/widgets/macrocall.js
type: application/javascript
module-type: widget
Macrocall widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MacroCallWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
MacroCallWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MacroCallWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
MacroCallWidget.prototype.execute = function() {
// Get the parse type if specified
this.parseType = this.getAttribute("$type","text/vnd.tiddlywiki");
this.renderOutput = this.getAttribute("$output","text/html");
// Merge together the parameters specified in the parse tree with the specified attributes
var params = this.parseTreeNode.params ? this.parseTreeNode.params.slice(0) : [];
$tw.utils.each(this.attributes,function(attribute,name) {
if(name.charAt(0) !== "$") {
params.push({name: name, value: attribute});
}
});
// Get the macro value
var text = this.getVariable(this.parseTreeNode.name || this.getAttribute("$name"),{params: params}),
parseTreeNodes;
// Are we rendering to HTML?
if(this.renderOutput === "text/html") {
// If so we'll return the parsed macro
var parser = this.wiki.parseText(this.parseType,text,
{parseAsInline: !this.parseTreeNode.isBlock});
parseTreeNodes = parser ? parser.tree : [];
} else {
// Otherwise, we'll render the text
var plainText = this.wiki.renderText("text/plain",this.parseType,text,{parentWidget: this});
parseTreeNodes = [{type: "text", text: plainText}];
}
// Construct the child widgets
this.makeChildWidgets(parseTreeNodes);
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
MacroCallWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if($tw.utils.count(changedAttributes) > 0) {
// Rerender ourselves
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
exports.macrocall = MacroCallWidget;
})();
/*\
title: $:/core/modules/widgets/navigator.js
type: application/javascript
module-type: widget
Navigator widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var IMPORT_TITLE = "$:/Import";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var NavigatorWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
this.addEventListeners([
{type: "tm-navigate", handler: "handleNavigateEvent"},
{type: "tm-edit-tiddler", handler: "handleEditTiddlerEvent"},
{type: "tm-delete-tiddler", handler: "handleDeleteTiddlerEvent"},
{type: "tm-save-tiddler", handler: "handleSaveTiddlerEvent"},
{type: "tm-cancel-tiddler", handler: "handleCancelTiddlerEvent"},
{type: "tm-close-tiddler", handler: "handleCloseTiddlerEvent"},
{type: "tm-close-all-tiddlers", handler: "handleCloseAllTiddlersEvent"},
{type: "tm-close-other-tiddlers", handler: "handleCloseOtherTiddlersEvent"},
{type: "tm-new-tiddler", handler: "handleNewTiddlerEvent"},
{type: "tm-import-tiddlers", handler: "handleImportTiddlersEvent"},
{type: "tm-perform-import", handler: "handlePerformImportEvent"},
{type: "tm-fold-tiddler", handler: "handleFoldTiddlerEvent"},
{type: "tm-fold-other-tiddlers", handler: "handleFoldOtherTiddlersEvent"},
{type: "tm-fold-all-tiddlers", handler: "handleFoldAllTiddlersEvent"},
{type: "tm-unfold-all-tiddlers", handler: "handleUnfoldAllTiddlersEvent"},
{type: "tm-rename-tiddler", handler: "handleRenameTiddlerEvent"}
]);
};
/*
Inherit from the base widget class
*/
NavigatorWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
NavigatorWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
NavigatorWidget.prototype.execute = function() {
// Get our parameters
this.storyTitle = this.getAttribute("story");
this.historyTitle = this.getAttribute("history");
// Construct the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
NavigatorWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.story || changedAttributes.history) {
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
NavigatorWidget.prototype.getStoryList = function() {
return this.storyTitle ? this.wiki.getTiddlerList(this.storyTitle) : null;
};
NavigatorWidget.prototype.saveStoryList = function(storyList) {
var storyTiddler = this.wiki.getTiddler(this.storyTitle);
this.wiki.addTiddler(new $tw.Tiddler(
{title: this.storyTitle},
storyTiddler,
{list: storyList}
));
};
NavigatorWidget.prototype.removeTitleFromStory = function(storyList,title) {
var p = storyList.indexOf(title);
while(p !== -1) {
storyList.splice(p,1);
p = storyList.indexOf(title);
}
};
NavigatorWidget.prototype.replaceFirstTitleInStory = function(storyList,oldTitle,newTitle) {
var pos = storyList.indexOf(oldTitle);
if(pos !== -1) {
storyList[pos] = newTitle;
do {
pos = storyList.indexOf(oldTitle,pos + 1);
if(pos !== -1) {
storyList.splice(pos,1);
}
} while(pos !== -1);
} else {
storyList.splice(0,0,newTitle);
}
};
NavigatorWidget.prototype.addToStory = function(title,fromTitle) {
var storyList = this.getStoryList();
// Quit if we cannot get hold of the story list
if(!storyList) {
return;
}
// See if the tiddler is already there
var slot = storyList.indexOf(title);
// Quit if it already exists in the story river
if(slot >= 0) {
return;
}
// First we try to find the position of the story element we navigated from
var fromIndex = storyList.indexOf(fromTitle);
if(fromIndex >= 0) {
// The tiddler is added from inside the river
// Determine where to insert the tiddler; Fallback is "below"
switch(this.getAttribute("openLinkFromInsideRiver","below")) {
case "top":
slot = 0;
break;
case "bottom":
slot = storyList.length;
break;
case "above":
slot = fromIndex;
break;
case "below": // Intentional fall-through
default:
slot = fromIndex + 1;
break;
}
} else {
// The tiddler is opened from outside the river. Determine where to insert the tiddler; default is "top"
if(this.getAttribute("openLinkFromOutsideRiver","top") === "bottom") {
// Insert at bottom
slot = storyList.length;
} else {
// Insert at top
slot = 0;
}
}
// Add the tiddler
storyList.splice(slot,0,title);
// Save the story
this.saveStoryList(storyList);
};
/*
Add a new record to the top of the history stack
title: a title string or an array of title strings
fromPageRect: page coordinates of the origin of the navigation
*/
NavigatorWidget.prototype.addToHistory = function(title,fromPageRect) {
this.wiki.addToHistory(title,fromPageRect,this.historyTitle);
};
/*
Handle a tm-navigate event
*/
NavigatorWidget.prototype.handleNavigateEvent = function(event) {
if(event.navigateTo) {
this.addToStory(event.navigateTo,event.navigateFromTitle);
if(!event.navigateSuppressNavigation) {
this.addToHistory(event.navigateTo,event.navigateFromClientRect);
}
}
return false;
};
// Close a specified tiddler
NavigatorWidget.prototype.handleCloseTiddlerEvent = function(event) {
var title = event.param || event.tiddlerTitle,
storyList = this.getStoryList();
// Look for tiddlers with this title to close
this.removeTitleFromStory(storyList,title);
this.saveStoryList(storyList);
return false;
};
// Close all tiddlers
NavigatorWidget.prototype.handleCloseAllTiddlersEvent = function(event) {
this.saveStoryList([]);
return false;
};
// Close other tiddlers
NavigatorWidget.prototype.handleCloseOtherTiddlersEvent = function(event) {
var title = event.param || event.tiddlerTitle;
this.saveStoryList([title]);
return false;
};
// Place a tiddler in edit mode
NavigatorWidget.prototype.handleEditTiddlerEvent = function(event) {
var self = this;
function isUnmodifiedShadow(title) {
return self.wiki.isShadowTiddler(title) && !self.wiki.tiddlerExists(title);
}
function confirmEditShadow(title) {
return confirm($tw.language.getString(
"ConfirmEditShadowTiddler",
{variables:
{title: title}
}
));
}
var title = event.param || event.tiddlerTitle;
if(isUnmodifiedShadow(title) && !confirmEditShadow(title)) {
return false;
}
// Replace the specified tiddler with a draft in edit mode
var draftTiddler = this.makeDraftTiddler(title);
// Update the story and history if required
if(!event.paramObject || event.paramObject.suppressNavigation !== "yes") {
var draftTitle = draftTiddler.fields.title,
storyList = this.getStoryList();
this.removeTitleFromStory(storyList,draftTitle);
this.replaceFirstTitleInStory(storyList,title,draftTitle);
this.addToHistory(draftTitle,event.navigateFromClientRect);
this.saveStoryList(storyList);
return false;
}
};
// Delete a tiddler
NavigatorWidget.prototype.handleDeleteTiddlerEvent = function(event) {
// Get the tiddler we're deleting
var title = event.param || event.tiddlerTitle,
tiddler = this.wiki.getTiddler(title),
storyList = this.getStoryList(),
originalTitle = tiddler ? tiddler.fields["draft.of"] : "",
confirmationTitle;
if(!tiddler) {
return false;
}
// Check if the tiddler we're deleting is in draft mode
if(originalTitle) {
// If so, we'll prompt for confirmation referencing the original tiddler
confirmationTitle = originalTitle;
} else {
// If not a draft, then prompt for confirmation referencing the specified tiddler
confirmationTitle = title;
}
// Seek confirmation
if((this.wiki.getTiddler(originalTitle) || (tiddler.fields.text || "") !== "") && !confirm($tw.language.getString(
"ConfirmDeleteTiddler",
{variables:
{title: confirmationTitle}
}
))) {
return false;
}
// Delete the original tiddler
if(originalTitle) {
this.wiki.deleteTiddler(originalTitle);
this.removeTitleFromStory(storyList,originalTitle);
}
// Delete this tiddler
this.wiki.deleteTiddler(title);
// Remove the closed tiddler from the story
this.removeTitleFromStory(storyList,title);
this.saveStoryList(storyList);
// Trigger an autosave
$tw.rootWidget.dispatchEvent({type: "tm-auto-save-wiki"});
return false;
};
/*
Create/reuse the draft tiddler for a given title
*/
NavigatorWidget.prototype.makeDraftTiddler = function(targetTitle) {
// See if there is already a draft tiddler for this tiddler
var draftTitle = this.wiki.findDraft(targetTitle);
if(draftTitle) {
return this.wiki.getTiddler(draftTitle);
}
// Get the current value of the tiddler we're editing
var tiddler = this.wiki.getTiddler(targetTitle);
// Save the initial value of the draft tiddler
draftTitle = this.generateDraftTitle(targetTitle);
var draftTiddler = new $tw.Tiddler(
tiddler,
{
title: draftTitle,
"draft.title": targetTitle,
"draft.of": targetTitle
},
this.wiki.getModificationFields()
);
this.wiki.addTiddler(draftTiddler);
return draftTiddler;
};
/*
Generate a title for the draft of a given tiddler
*/
NavigatorWidget.prototype.generateDraftTitle = function(title) {
var c = 0,
draftTitle;
do {
draftTitle = "Draft " + (c ? (c + 1) + " " : "") + "of '" + title + "'";
c++;
} while(this.wiki.tiddlerExists(draftTitle));
return draftTitle;
};
// Take a tiddler out of edit mode, saving the changes
NavigatorWidget.prototype.handleSaveTiddlerEvent = function(event) {
var title = event.param || event.tiddlerTitle,
tiddler = this.wiki.getTiddler(title),
storyList = this.getStoryList();
// Replace the original tiddler with the draft
if(tiddler) {
var draftTitle = (tiddler.fields["draft.title"] || "").trim(),
draftOf = (tiddler.fields["draft.of"] || "").trim();
if(draftTitle) {
var isRename = draftOf !== draftTitle,
isConfirmed = true;
if(isRename && this.wiki.tiddlerExists(draftTitle)) {
isConfirmed = confirm($tw.language.getString(
"ConfirmOverwriteTiddler",
{variables:
{title: draftTitle}
}
));
}
if(isConfirmed) {
// Create the new tiddler and pass it through the th-saving-tiddler hook
var newTiddler = new $tw.Tiddler(this.wiki.getCreationFields(),tiddler,{
title: draftTitle,
"draft.title": undefined,
"draft.of": undefined
},this.wiki.getModificationFields());
newTiddler = $tw.hooks.invokeHook("th-saving-tiddler",newTiddler);
this.wiki.addTiddler(newTiddler);
// Remove the draft tiddler
this.wiki.deleteTiddler(title);
// Remove the original tiddler if we're renaming it
if(isRename) {
this.wiki.deleteTiddler(draftOf);
}
if(!event.paramObject || event.paramObject.suppressNavigation !== "yes") {
// Replace the draft in the story with the original
this.replaceFirstTitleInStory(storyList,title,draftTitle);
this.addToHistory(draftTitle,event.navigateFromClientRect);
if(draftTitle !== this.storyTitle) {
this.saveStoryList(storyList);
}
}
// Trigger an autosave
$tw.rootWidget.dispatchEvent({type: "tm-auto-save-wiki"});
}
}
}
return false;
};
// Take a tiddler out of edit mode without saving the changes
NavigatorWidget.prototype.handleCancelTiddlerEvent = function(event) {
// Flip the specified tiddler from draft back to the original
var draftTitle = event.param || event.tiddlerTitle,
draftTiddler = this.wiki.getTiddler(draftTitle),
originalTitle = draftTiddler && draftTiddler.fields["draft.of"];
if(draftTiddler && originalTitle) {
// Ask for confirmation if the tiddler text has changed
var isConfirmed = true,
originalTiddler = this.wiki.getTiddler(originalTitle),
storyList = this.getStoryList();
if(this.wiki.isDraftModified(draftTitle)) {
isConfirmed = confirm($tw.language.getString(
"ConfirmCancelTiddler",
{variables:
{title: draftTitle}
}
));
}
// Remove the draft tiddler
if(isConfirmed) {
this.wiki.deleteTiddler(draftTitle);
if(!event.paramObject || event.paramObject.suppressNavigation !== "yes") {
if(originalTiddler) {
this.replaceFirstTitleInStory(storyList,draftTitle,originalTitle);
this.addToHistory(originalTitle,event.navigateFromClientRect);
} else {
this.removeTitleFromStory(storyList,draftTitle);
}
this.saveStoryList(storyList);
}
}
}
return false;
};
// Create a new draft tiddler
// event.param can either be the title of a template tiddler, or a hashmap of fields.
//
// The title of the newly created tiddler follows these rules:
// * If a hashmap was used and a title field was specified, use that title
// * If a hashmap was used without a title field, use a default title, if necessary making it unique with a numeric suffix
// * If a template tiddler was used, use the title of the template, if necessary making it unique with a numeric suffix
//
// If a draft of the target tiddler already exists then it is reused
NavigatorWidget.prototype.handleNewTiddlerEvent = function(event) {
// Get the story details
var storyList = this.getStoryList(),
templateTiddler, additionalFields, title, draftTitle, existingTiddler;
// Get the template tiddler (if any)
if(typeof event.param === "string") {
// Get the template tiddler
templateTiddler = this.wiki.getTiddler(event.param);
// Generate a new title
title = this.wiki.generateNewTitle(event.param || $tw.language.getString("DefaultNewTiddlerTitle"));
}
// Get the specified additional fields
if(typeof event.paramObject === "object") {
additionalFields = event.paramObject;
}
if(typeof event.param === "object") { // Backwards compatibility with 5.1.3
additionalFields = event.param;
}
if(additionalFields && additionalFields.title) {
title = additionalFields.title;
}
// Generate a title if we don't have one
title = title || this.wiki.generateNewTitle($tw.language.getString("DefaultNewTiddlerTitle"));
// Find any existing draft for this tiddler
draftTitle = this.wiki.findDraft(title);
// Pull in any existing tiddler
if(draftTitle) {
existingTiddler = this.wiki.getTiddler(draftTitle);
} else {
draftTitle = this.generateDraftTitle(title);
existingTiddler = this.wiki.getTiddler(title);
}
// Merge the tags
var mergedTags = [];
if(existingTiddler && existingTiddler.fields.tags) {
$tw.utils.pushTop(mergedTags,existingTiddler.fields.tags)
}
if(additionalFields && additionalFields.tags) {
// Merge tags
mergedTags = $tw.utils.pushTop(mergedTags,$tw.utils.parseStringArray(additionalFields.tags));
}
if(templateTiddler && templateTiddler.fields.tags) {
// Merge tags
mergedTags = $tw.utils.pushTop(mergedTags,templateTiddler.fields.tags);
}
// Save the draft tiddler
var draftTiddler = new $tw.Tiddler({
text: "",
"draft.title": title
},
templateTiddler,
existingTiddler,
additionalFields,
this.wiki.getCreationFields(),
{
title: draftTitle,
"draft.of": title,
tags: mergedTags
},this.wiki.getModificationFields());
this.wiki.addTiddler(draftTiddler);
// Update the story to insert the new draft at the top and remove any existing tiddler
if(storyList.indexOf(draftTitle) === -1) {
var slot = storyList.indexOf(event.navigateFromTitle);
storyList.splice(slot + 1,0,draftTitle);
}
if(storyList.indexOf(title) !== -1) {
storyList.splice(storyList.indexOf(title),1);
}
this.saveStoryList(storyList);
// Add a new record to the top of the history stack
this.addToHistory(draftTitle);
return false;
};
// Import JSON tiddlers into a pending import tiddler
NavigatorWidget.prototype.handleImportTiddlersEvent = function(event) {
var self = this;
// Get the tiddlers
var tiddlers = [];
try {
tiddlers = JSON.parse(event.param);
} catch(e) {
}
// Get the current $:/Import tiddler
var importTiddler = this.wiki.getTiddler(IMPORT_TITLE),
importData = this.wiki.getTiddlerData(IMPORT_TITLE,{}),
newFields = new Object({
title: IMPORT_TITLE,
type: "application/json",
"plugin-type": "import",
"status": "pending"
}),
incomingTiddlers = [];
// Process each tiddler
importData.tiddlers = importData.tiddlers || {};
$tw.utils.each(tiddlers,function(tiddlerFields) {
var title = tiddlerFields.title;
if(title) {
incomingTiddlers.push(title);
importData.tiddlers[title] = tiddlerFields;
}
});
// Give the active upgrader modules a chance to process the incoming tiddlers
var messages = this.wiki.invokeUpgraders(incomingTiddlers,importData.tiddlers);
$tw.utils.each(messages,function(message,title) {
newFields["message-" + title] = message;
});
// Deselect any suppressed tiddlers
$tw.utils.each(importData.tiddlers,function(tiddler,title) {
if($tw.utils.count(tiddler) === 0) {
newFields["selection-" + title] = "unchecked";
}
});
// Save the $:/Import tiddler
newFields.text = JSON.stringify(importData,null,$tw.config.preferences.jsonSpaces);
this.wiki.addTiddler(new $tw.Tiddler(importTiddler,newFields));
// Update the story and history details
if(this.getVariable("tv-auto-open-on-import") !== "no") {
var storyList = this.getStoryList(),
history = [];
// Add it to the story
if(storyList.indexOf(IMPORT_TITLE) === -1) {
storyList.unshift(IMPORT_TITLE);
}
// And to history
history.push(IMPORT_TITLE);
// Save the updated story and history
this.saveStoryList(storyList);
this.addToHistory(history);
}
return false;
};
//
NavigatorWidget.prototype.handlePerformImportEvent = function(event) {
var self = this,
importTiddler = this.wiki.getTiddler(event.param),
importData = this.wiki.getTiddlerDataCached(event.param,{tiddlers: {}}),
importReport = [];
// Add the tiddlers to the store
importReport.push($tw.language.getString("Import/Imported") + "\n");
$tw.utils.each(importData.tiddlers,function(tiddlerFields) {
var title = tiddlerFields.title;
if(title && importTiddler && importTiddler.fields["selection-" + title] !== "unchecked") {
self.wiki.addTiddler(new $tw.Tiddler(tiddlerFields));
importReport.push("# [[" + tiddlerFields.title + "]]");
}
});
// Replace the $:/Import tiddler with an import report
this.wiki.addTiddler(new $tw.Tiddler({
title: event.param,
text: importReport.join("\n"),
"status": "complete"
}));
// Navigate to the $:/Import tiddler
this.addToHistory([event.param]);
// Trigger an autosave
$tw.rootWidget.dispatchEvent({type: "tm-auto-save-wiki"});
};
NavigatorWidget.prototype.handleFoldTiddlerEvent = function(event) {
var self = this,
paramObject = event.paramObject || {};
if(paramObject.foldedState) {
var foldedState = this.wiki.getTiddlerText(paramObject.foldedState,"show") === "show" ? "hide" : "show";
this.wiki.setText(paramObject.foldedState,"text",null,foldedState);
}
};
NavigatorWidget.prototype.handleFoldOtherTiddlersEvent = function(event) {
var self = this,
paramObject = event.paramObject || {},
prefix = paramObject.foldedStatePrefix;
$tw.utils.each(this.getStoryList(),function(title) {
self.wiki.setText(prefix + title,"text",null,event.param === title ? "show" : "hide");
});
};
NavigatorWidget.prototype.handleFoldAllTiddlersEvent = function(event) {
var self = this,
paramObject = event.paramObject || {},
prefix = paramObject.foldedStatePrefix;
$tw.utils.each(this.getStoryList(),function(title) {
self.wiki.setText(prefix + title,"text",null,"hide");
});
};
NavigatorWidget.prototype.handleUnfoldAllTiddlersEvent = function(event) {
var self = this,
paramObject = event.paramObject || {},
prefix = paramObject.foldedStatePrefix;
$tw.utils.each(this.getStoryList(),function(title) {
self.wiki.setText(prefix + title,"text",null,"show");
});
};
NavigatorWidget.prototype.handleRenameTiddlerEvent = function(event) {
var self = this,
paramObject = event.paramObject || {},
from = paramObject.from || event.tiddlerTitle,
to = paramObject.to;
$tw.wiki.renameTiddler(from,to);
};
exports.navigator = NavigatorWidget;
})();
/*\
title: $:/core/modules/widgets/ondrop.js
type: application/javascript
module-type: widget
List and list item widgets
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
/*
The list widget creates list element sub-widgets that reach back into the list widget for their configuration
*/
var OnDrop = function(parseTreeNode,options) {
// Main initialisation inherited from widget.js
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
OnDrop.prototype = new Widget();
/*
Render this widget into the DOM
*/
OnDrop.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
// Add event handlers
// Create element
var domNode = this.document.createElement("div");
domNode.className = "tc-dropzone";
$tw.utils.addEventListeners(domNode,[
{name: "drop", handlerObject: this, handlerMethod: "handleDropEvent"}
]);
// Insert element
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
};
/*
Compute the internal state of the widget
*/
OnDrop.prototype.execute = function() {
this.listtag = this.getAttribute("targeTtag",this.getVariable("currentTiddler"));
this.onAddMessage = this.getAttribute("onAddMessage");
this.action = this.getAttribute("tagAction");
// Make child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
OnDrop.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
// Completely refresh if any of our attributes have changed
if(changedAttributes.tagAction || changedAttributes.onAddMessage) {
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
OnDrop.prototype.addTag = function (tidname) {
var tiddler = this.wiki.getTiddler(tidname);
var modification = this.wiki.getModificationFields();
modification.tags = (tiddler.fields.tags || []).slice(0);
$tw.utils.pushTop(modification.tags,this.listtag);
this.wiki.addTiddler(new $tw.Tiddler(tiddler,modification));
}
OnDrop.prototype.removeTag = function (tidname) {
var tiddler = this.wiki.getTiddler(tidname);
var p = tiddler.fields.tags.indexOf(this.listtag);
if(p !== -1) {
var modification = this.wiki.getModificationFields();
modification.tags = (tiddler.fields.tags || []).slice(0);
modification.tags.splice(p,1);
if(modification.tags.length === 0) {
modification.tags = undefined;
}
this.wiki.addTiddler(new $tw.Tiddler(tiddler,modification));
}
}
OnDrop.prototype.handleDropEvent = function(event) {
var self = this,
dataTransfer = event.dataTransfer, returned={};
returned = self.nameandOnListTag(dataTransfer);
if (!!returned.name) { //only handle tiddler drops
if (!returned.onList) { //this means tiddler does not have the tag
if (self.action === 'addtag') self.addTag(returned.name);
}
else {
if (self.action === 'removetag') self.removeTag(returned.name);
}
//cancel normal action
self.cancelAction(event);
self.dispatchEvent({type: "tm-dropHandled", param: null});
if (self.onAddMessage) self.dispatchEvent({type: self.onAddMessage, param: returned.name});
}
//else let the event fall thru
};
OnDrop.prototype.importDataTypes = [
{type: "text/vnd.tiddler", IECompatible: false, convertToFields: function(data) {
return JSON.parse(data);
}},
{type: "URL", IECompatible: true, convertToFields: function(data) {
// Check for tiddler data URI
var match = decodeURI(data).match(/^data\:text\/vnd\.tiddler,(.*)/i);
if(match) {
return JSON.parse(match[1]);
} else {
return { // As URL string
text: data
};
}
}},
{type: "text/x-moz-url", IECompatible: false, convertToFields: function(data) {
// Check for tiddler data URI
var match = decodeURI(data).match(/^data\:text\/vnd\.tiddler,(.*)/i);
if(match) {
return JSON.parse(match[1]);
} else {
return { // As URL string
text: data
};
}
}},
{type: "text/plain", IECompatible: false, convertToFields: function(data) {
return {
text: data
};
}},
{type: "Text", IECompatible: true, convertToFields: function(data) {
return {
text: data
};
}},
{type: "text/uri-list", IECompatible: false, convertToFields: function(data) {
return {
text: data
};
}}
];
OnDrop.prototype.cancelAction =function(event) {
// Try each provided data type in turn
{
var dataTransfer = event.dataTransfer;
event.preventDefault();
// Stop the drop ripple up to any parent handlers
event.stopPropagation();
};
};
OnDrop.prototype.nameandOnListTag = function(dataTransfer) {
// Try each provided data type in turn
for(var t=0; t<this.importDataTypes.length; t++) {
if(!$tw.browser.isIE || this.importDataTypes[t].IECompatible) {
// Get the data
var dataType = this.importDataTypes[t];
var data = dataTransfer.getData(dataType.type);
// Import the tiddlers in the data);
if(data !== "" && data !== null) {
var tiddlerFields = dataType.convertToFields(data);
if(!tiddlerFields.title) {
break;
}
if (tiddlerFields.tags && $tw.utils.parseStringArray(tiddlerFields.tags).indexOf(this.listtag) !== -1) {
return {name:tiddlerFields.title, onList:true};
}
else {//we have to add the tag to the tiddler
if (!!this.wiki.getTiddler(tiddlerFields.title)){//tid is in this tw
return {name:tiddlerFields.title, onList:false};
}
//return false;
}
}
}
};
return {name:null, onList:false};
};
exports.ondrop = OnDrop;
})();
/*\
title: $:/core/modules/widgets/password.js
type: application/javascript
module-type: widget
Password widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var PasswordWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
PasswordWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
PasswordWidget.prototype.render = function(parent,nextSibling) {
// Save the parent dom node
this.parentDomNode = parent;
// Compute our attributes
this.computeAttributes();
// Execute our logic
this.execute();
// Get the current password
var password = $tw.browser ? $tw.utils.getPassword(this.passwordName) || "" : "";
// Create our element
var domNode = this.document.createElement("input");
domNode.setAttribute("type","password");
domNode.setAttribute("value",password);
// Add a click event handler
$tw.utils.addEventListeners(domNode,[
{name: "change", handlerObject: this, handlerMethod: "handleChangeEvent"}
]);
// Insert the label into the DOM and render any children
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
};
PasswordWidget.prototype.handleChangeEvent = function(event) {
var password = this.domNodes[0].value;
return $tw.utils.savePassword(this.passwordName,password);
};
/*
Compute the internal state of the widget
*/
PasswordWidget.prototype.execute = function() {
// Get the parameters from the attributes
this.passwordName = this.getAttribute("name","");
// Make the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
PasswordWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.name) {
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
exports.password = PasswordWidget;
})();
/*\
title: $:/core/modules/widgets/radio.js
type: application/javascript
module-type: widget
Radio widget
Will set a field to the selected value:
```
<$radio field="myfield" value="check 1">one</$radio>
<$radio field="myfield" value="check 2">two</$radio>
<$radio field="myfield" value="check 3">three</$radio>
```
|Parameter |Description |h
|tiddler |Name of the tiddler in which the field should be set. Defaults to current tiddler |
|field |The name of the field to be set |
|value |The value to set |
|class |Optional class name(s) |
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var RadioWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
RadioWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
RadioWidget.prototype.render = function(parent,nextSibling) {
// Save the parent dom node
this.parentDomNode = parent;
// Compute our attributes
this.computeAttributes();
// Execute our logic
this.execute();
// Create our elements
this.labelDomNode = this.document.createElement("label");
this.labelDomNode.setAttribute("class",this.radioClass);
this.inputDomNode = this.document.createElement("input");
this.inputDomNode.setAttribute("type","radio");
if(this.getValue() == this.radioValue) {
this.inputDomNode.setAttribute("checked","true");
}
this.labelDomNode.appendChild(this.inputDomNode);
this.spanDomNode = this.document.createElement("span");
this.labelDomNode.appendChild(this.spanDomNode);
// Add a click event handler
$tw.utils.addEventListeners(this.inputDomNode,[
{name: "change", handlerObject: this, handlerMethod: "handleChangeEvent"}
]);
// Insert the label into the DOM and render any children
parent.insertBefore(this.labelDomNode,nextSibling);
this.renderChildren(this.spanDomNode,null);
this.domNodes.push(this.labelDomNode);
};
RadioWidget.prototype.getValue = function() {
var tiddler = this.wiki.getTiddler(this.radioTitle);
return tiddler && tiddler.getFieldString(this.radioField);
};
RadioWidget.prototype.setValue = function() {
if(this.radioField) {
var tiddler = this.wiki.getTiddler(this.radioTitle),
addition = {};
addition[this.radioField] = this.radioValue;
this.wiki.addTiddler(new $tw.Tiddler(this.wiki.getCreationFields(),{title: this.radioTitle},tiddler,addition,this.wiki.getModificationFields()));
}
};
RadioWidget.prototype.handleChangeEvent = function(event) {
if(this.inputDomNode.checked) {
this.setValue();
}
};
/*
Compute the internal state of the widget
*/
RadioWidget.prototype.execute = function() {
// Get the parameters from the attributes
this.radioTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
this.radioField = this.getAttribute("field","text");
this.radioValue = this.getAttribute("value");
this.radioClass = this.getAttribute("class","");
if(this.radioClass !== "") {
this.radioClass += " ";
}
this.radioClass += "tc-radio";
// Make the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
RadioWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.tiddler || changedAttributes.field || changedAttributes.value || changedAttributes["class"]) {
this.refreshSelf();
return true;
} else {
var refreshed = false;
if(changedTiddlers[this.radioTitle]) {
this.inputDomNode.checked = this.getValue() === this.radioValue;
refreshed = true;
}
return this.refreshChildren(changedTiddlers) || refreshed;
}
};
exports.radio = RadioWidget;
})();
/*\
title: $:/core/modules/widgets/raw.js
type: application/javascript
module-type: widget
Raw widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var RawWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
RawWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
RawWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.execute();
var div = this.document.createElement("div");
div.innerHTML=this.parseTreeNode.html;
parent.insertBefore(div,nextSibling);
this.domNodes.push(div);
};
/*
Compute the internal state of the widget
*/
RawWidget.prototype.execute = function() {
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
RawWidget.prototype.refresh = function(changedTiddlers) {
return false;
};
exports.raw = RawWidget;
})();
/*\
title: $:/core/modules/widgets/reveal.js
type: application/javascript
module-type: widget
Reveal widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var RevealWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
RevealWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
RevealWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
var tag = this.parseTreeNode.isBlock ? "div" : "span";
if(this.revealTag && $tw.config.htmlUnsafeElements.indexOf(this.revealTag) === -1) {
tag = this.revealTag;
}
var domNode = this.document.createElement(tag);
var classes = this["class"].split(" ") || [];
classes.push("tc-reveal");
domNode.className = classes.join(" ");
if(this.style) {
domNode.setAttribute("style",this.style);
}
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
if(!domNode.isTiddlyWikiFakeDom && this.type === "popup" && this.isOpen) {
this.positionPopup(domNode);
$tw.utils.addClass(domNode,"tc-popup"); // Make sure that clicks don't dismiss popups within the revealed content
}
if(!this.isOpen) {
domNode.setAttribute("hidden","true");
}
this.domNodes.push(domNode);
};
RevealWidget.prototype.positionPopup = function(domNode) {
domNode.style.position = "absolute";
domNode.style.zIndex = "1000";
switch(this.position) {
case "left":
domNode.style.left = (this.popup.left - domNode.offsetWidth) + "px";
domNode.style.top = this.popup.top + "px";
break;
case "above":
domNode.style.left = this.popup.left + "px";
domNode.style.top = (this.popup.top - domNode.offsetHeight) + "px";
break;
case "aboveright":
domNode.style.left = (this.popup.left + this.popup.width) + "px";
domNode.style.top = (this.popup.top + this.popup.height - domNode.offsetHeight) + "px";
break;
case "right":
domNode.style.left = (this.popup.left + this.popup.width) + "px";
domNode.style.top = this.popup.top + "px";
break;
case "belowleft":
domNode.style.left = (this.popup.left + this.popup.width - domNode.offsetWidth) + "px";
domNode.style.top = (this.popup.top + this.popup.height) + "px";
break;
default: // Below
domNode.style.left = this.popup.left + "px";
domNode.style.top = (this.popup.top + this.popup.height) + "px";
break;
}
};
/*
Compute the internal state of the widget
*/
RevealWidget.prototype.execute = function() {
// Get our parameters
this.state = this.getAttribute("state");
this.revealTag = this.getAttribute("tag");
this.type = this.getAttribute("type");
this.text = this.getAttribute("text");
this.position = this.getAttribute("position");
this["class"] = this.getAttribute("class","");
this.style = this.getAttribute("style","");
this["default"] = this.getAttribute("default","");
this.animate = this.getAttribute("animate","no");
this.retain = this.getAttribute("retain","no");
this.openAnimation = this.animate === "no" ? undefined : "open";
this.closeAnimation = this.animate === "no" ? undefined : "close";
// Compute the title of the state tiddler and read it
this.stateTitle = this.state;
this.readState();
// Construct the child widgets
var childNodes = this.isOpen ? this.parseTreeNode.children : [];
this.hasChildNodes = this.isOpen;
this.makeChildWidgets(childNodes);
};
/*
Read the state tiddler
*/
RevealWidget.prototype.readState = function() {
// Read the information from the state tiddler
var state = this.stateTitle ? this.wiki.getTextReference(this.stateTitle,this["default"],this.getVariable("currentTiddler")) : this["default"];
switch(this.type) {
case "popup":
this.readPopupState(state);
break;
case "match":
this.readMatchState(state);
break;
case "nomatch":
this.readMatchState(state);
this.isOpen = !this.isOpen;
break;
}
};
RevealWidget.prototype.readMatchState = function(state) {
this.isOpen = state === this.text;
};
RevealWidget.prototype.readPopupState = function(state) {
var popupLocationRegExp = /^\((-?[0-9\.E]+),(-?[0-9\.E]+),(-?[0-9\.E]+),(-?[0-9\.E]+)\)$/,
match = popupLocationRegExp.exec(state);
// Check if the state matches the location regexp
if(match) {
// If so, we're open
this.isOpen = true;
// Get the location
this.popup = {
left: parseFloat(match[1]),
top: parseFloat(match[2]),
width: parseFloat(match[3]),
height: parseFloat(match[4])
};
} else {
// If not, we're closed
this.isOpen = false;
}
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
RevealWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.state || changedAttributes.type || changedAttributes.text || changedAttributes.position || changedAttributes["default"] || changedAttributes.animate) {
this.refreshSelf();
return true;
} else {
var refreshed = false,
currentlyOpen = this.isOpen;
this.readState();
if(this.isOpen !== currentlyOpen) {
if(this.retain === "yes") {
this.updateState();
} else {
this.refreshSelf();
refreshed = true;
}
}
return this.refreshChildren(changedTiddlers) || refreshed;
}
};
/*
Called by refresh() to dynamically show or hide the content
*/
RevealWidget.prototype.updateState = function() {
// Read the current state
this.readState();
// Construct the child nodes if needed
var domNode = this.domNodes[0];
if(this.isOpen && !this.hasChildNodes) {
this.hasChildNodes = true;
this.makeChildWidgets(this.parseTreeNode.children);
this.renderChildren(domNode,null);
}
// Animate our DOM node
if(!domNode.isTiddlyWikiFakeDom && this.type === "popup" && this.isOpen) {
this.positionPopup(domNode);
$tw.utils.addClass(domNode,"tc-popup"); // Make sure that clicks don't dismiss popups within the revealed content
}
if(this.isOpen) {
domNode.removeAttribute("hidden");
$tw.anim.perform(this.openAnimation,domNode);
} else {
$tw.anim.perform(this.closeAnimation,domNode,{callback: function() {
domNode.setAttribute("hidden","true");
}});
}
};
exports.reveal = RevealWidget;
})();
/*\
title: $:/core/modules/widgets/scrollable.js
type: application/javascript
module-type: widget
Scrollable widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var ScrollableWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
this.scaleFactor = 1;
this.addEventListeners([
{type: "tm-scroll", handler: "handleScrollEvent"}
]);
if($tw.browser) {
this.requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) {
return window.setTimeout(callback, 1000/60);
};
this.cancelAnimationFrame = window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
function(id) {
window.clearTimeout(id);
};
}
};
/*
Inherit from the base widget class
*/
ScrollableWidget.prototype = new Widget();
ScrollableWidget.prototype.cancelScroll = function() {
if(this.idRequestFrame) {
this.cancelAnimationFrame.call(window,this.idRequestFrame);
this.idRequestFrame = null;
}
};
/*
Handle a scroll event
*/
ScrollableWidget.prototype.handleScrollEvent = function(event) {
// Pass the scroll event through if our offsetsize is larger than our scrollsize
if(this.outerDomNode.scrollWidth <= this.outerDomNode.offsetWidth && this.outerDomNode.scrollHeight <= this.outerDomNode.offsetHeight && this.fallthrough === "yes") {
return true;
}
this.scrollIntoView(event.target);
return false; // Handled event
};
/*
Scroll an element into view
*/
ScrollableWidget.prototype.scrollIntoView = function(element) {
var duration = $tw.utils.getAnimationDuration();
this.cancelScroll();
this.startTime = Date.now();
var scrollPosition = {
x: this.outerDomNode.scrollLeft,
y: this.outerDomNode.scrollTop
};
// Get the client bounds of the element and adjust by the scroll position
var scrollableBounds = this.outerDomNode.getBoundingClientRect(),
clientTargetBounds = element.getBoundingClientRect(),
bounds = {
left: clientTargetBounds.left + scrollPosition.x - scrollableBounds.left,
top: clientTargetBounds.top + scrollPosition.y - scrollableBounds.top,
width: clientTargetBounds.width,
height: clientTargetBounds.height
};
// We'll consider the horizontal and vertical scroll directions separately via this function
var getEndPos = function(targetPos,targetSize,currentPos,currentSize) {
// If the target is already visible then stay where we are
if(targetPos >= currentPos && (targetPos + targetSize) <= (currentPos + currentSize)) {
return currentPos;
// If the target is above/left of the current view, then scroll to its top/left
} else if(targetPos <= currentPos) {
return targetPos;
// If the target is smaller than the window and the scroll position is too far up, then scroll till the target is at the bottom of the window
} else if(targetSize < currentSize && currentPos < (targetPos + targetSize - currentSize)) {
return targetPos + targetSize - currentSize;
// If the target is big, then just scroll to the top
} else if(currentPos < targetPos) {
return targetPos;
// Otherwise, stay where we are
} else {
return currentPos;
}
},
endX = getEndPos(bounds.left,bounds.width,scrollPosition.x,this.outerDomNode.offsetWidth),
endY = getEndPos(bounds.top,bounds.height,scrollPosition.y,this.outerDomNode.offsetHeight);
// Only scroll if necessary
if(endX !== scrollPosition.x || endY !== scrollPosition.y) {
var self = this,
drawFrame;
drawFrame = function () {
var t;
if(duration <= 0) {
t = 1;
} else {
t = ((Date.now()) - self.startTime) / duration;
}
if(t >= 1) {
self.cancelScroll();
t = 1;
}
t = $tw.utils.slowInSlowOut(t);
self.outerDomNode.scrollLeft = scrollPosition.x + (endX - scrollPosition.x) * t;
self.outerDomNode.scrollTop = scrollPosition.y + (endY - scrollPosition.y) * t;
if(t < 1) {
self.idRequestFrame = self.requestAnimationFrame.call(window,drawFrame);
}
};
drawFrame();
}
};
/*
Render this widget into the DOM
*/
ScrollableWidget.prototype.render = function(parent,nextSibling) {
var self = this;
// Remember parent
this.parentDomNode = parent;
// Compute attributes and execute state
this.computeAttributes();
this.execute();
// Create elements
this.outerDomNode = this.document.createElement("div");
$tw.utils.setStyle(this.outerDomNode,[
{overflowY: "auto"},
{overflowX: "auto"},
{webkitOverflowScrolling: "touch"}
]);
this.innerDomNode = this.document.createElement("div");
this.outerDomNode.appendChild(this.innerDomNode);
// Assign classes
this.outerDomNode.className = this["class"] || "";
// Insert element
parent.insertBefore(this.outerDomNode,nextSibling);
this.renderChildren(this.innerDomNode,null);
this.domNodes.push(this.outerDomNode);
};
/*
Compute the internal state of the widget
*/
ScrollableWidget.prototype.execute = function() {
// Get attributes
this.fallthrough = this.getAttribute("fallthrough","yes");
this["class"] = this.getAttribute("class");
// Make child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ScrollableWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes["class"]) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
exports.scrollable = ScrollableWidget;
})();
/*\
title: $:/core/modules/widgets/select.js
type: application/javascript
module-type: widget
Select widget:
```
<$select tiddler="MyTiddler" field="text">
<$list filter="[tag[chapter]]">
<option value=<<currentTiddler>>>
<$view field="description"/>
</option>
</$list>
</$select>
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var SelectWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
SelectWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
SelectWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
this.setSelectValue();
$tw.utils.addEventListeners(this.getSelectDomNode(),[
{name: "change", handlerObject: this, handlerMethod: "handleChangeEvent"}
]);
};
/*
Handle a change event
*/
SelectWidget.prototype.handleChangeEvent = function(event) {
if(this.selectMultiple == false) {
var value = this.getSelectDomNode().value;
} else {
var value = this.getSelectValues()
value = $tw.utils.stringifyList(value);
}
this.wiki.setText(this.selectTitle,this.selectField,this.selectIndex,value);
};
/*
If necessary, set the value of the select element to the current value
*/
SelectWidget.prototype.setSelectValue = function() {
var value = this.selectDefault;
// Get the value
if(this.selectIndex) {
value = this.wiki.extractTiddlerDataItem(this.selectTitle,this.selectIndex);
} else {
var tiddler = this.wiki.getTiddler(this.selectTitle);
if(tiddler) {
if(this.selectField === "text") {
// Calling getTiddlerText() triggers lazy loading of skinny tiddlers
value = this.wiki.getTiddlerText(this.selectTitle);
} else {
if($tw.utils.hop(tiddler.fields,this.selectField)) {
value = tiddler.getFieldString(this.selectField);
}
}
} else {
if(this.selectField === "title") {
value = this.selectTitle;
}
}
}
// Assign it to the select element if it's different than the current value
if (this.selectMultiple) {
value = value === undefined ? "" : value;
var select = this.getSelectDomNode();
var values = Array.isArray(value) ? value : $tw.utils.parseStringArray(value);
for(var i=0; i < select.children.length; i++){
if(values.indexOf(select.children[i].value) != -1) {
select.children[i].selected = true;
}
}
} else {
var domNode = this.getSelectDomNode();
if(domNode.value !== value) {
domNode.value = value;
}
}
};
/*
Get the DOM node of the select element
*/
SelectWidget.prototype.getSelectDomNode = function() {
return this.children[0].domNodes[0];
};
// Return an array of the selected opion values
// select is an HTML select element
SelectWidget.prototype.getSelectValues = function() {
var select, result, options, opt;
select = this.getSelectDomNode();
result = [];
options = select && select.options;
for (var i=0; i<options.length; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
/*
Compute the internal state of the widget
*/
SelectWidget.prototype.execute = function() {
// Get our parameters
this.selectTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
this.selectField = this.getAttribute("field","text");
this.selectIndex = this.getAttribute("index");
this.selectClass = this.getAttribute("class");
this.selectDefault = this.getAttribute("default");
this.selectMultiple = this.getAttribute("multiple", false);
this.selectSize = this.getAttribute("size");
// Make the child widgets
var selectNode = {
type: "element",
tag: "select",
children: this.parseTreeNode.children
};
if(this.selectClass) {
$tw.utils.addAttributeToParseTreeNode(selectNode,"class",this.selectClass);
}
if(this.selectMultiple) {
$tw.utils.addAttributeToParseTreeNode(selectNode,"multiple","multiple");
}
if(this.selectSize) {
$tw.utils.addAttributeToParseTreeNode(selectNode,"size",this.selectSize);
}
this.makeChildWidgets([selectNode]);
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
SelectWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
// If we're using a different tiddler/field/index then completely refresh ourselves
if(changedAttributes.selectTitle || changedAttributes.selectField || changedAttributes.selectIndex) {
this.refreshSelf();
return true;
// If the target tiddler value has changed, just update setting and refresh the children
} else {
var childrenRefreshed = this.refreshChildren(changedTiddlers);
if(changedTiddlers[this.selectTitle] || childrenRefreshed) {
this.setSelectValue();
}
return childrenRefreshed;
}
};
exports.select = SelectWidget;
})();
/*\
title: $:/core/modules/widgets/set.js
type: application/javascript
module-type: widget
Set variable widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var SetWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
SetWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
SetWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
SetWidget.prototype.execute = function() {
// Get our parameters
this.setName = this.getAttribute("name","currentTiddler");
this.setFilter = this.getAttribute("filter");
this.setValue = this.getAttribute("value");
this.setEmptyValue = this.getAttribute("emptyValue");
// Set context variable
this.setVariable(this.setName,this.getValue(),this.parseTreeNode.params);
// Construct the child widgets
this.makeChildWidgets();
};
/*
Get the value to be assigned
*/
SetWidget.prototype.getValue = function() {
var value = this.setValue;
if(this.setFilter) {
var results = this.wiki.filterTiddlers(this.setFilter,this);
if(!this.setValue) {
value = $tw.utils.stringifyList(results);
}
if(results.length === 0 && this.setEmptyValue !== undefined) {
value = this.setEmptyValue;
}
} else if(!value && this.setEmptyValue) {
value = this.setEmptyValue;
}
return value;
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
SetWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.name || changedAttributes.filter || changedAttributes.value || changedAttributes.emptyValue ||
(this.setFilter && this.getValue() != this.variables[this.setName].value)) {
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
exports.setvariable = SetWidget;
exports.set = SetWidget;
})();
/*\
title: $:/core/modules/widgets/taglist.js
type: application/javascript
module-type: widget
List and list item widgets
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
/*
The list widget creates list element sub-widgets that reach back into the list widget for their configuration
*/
var TagListWidget = function(parseTreeNode,options) {
// Initialise the storyviews if they've not been done already
if(!this.storyViews) {
TagListWidget.prototype.storyViews = {};
$tw.modules.applyMethods("storyview",this.storyViews);
}
// Main initialisation inherited from widget.js
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
TagListWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
TagListWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
TagListWidget.prototype.execute = function() {
// Get our attributes
this.template = this.getAttribute("template");
this.editTemplate = this.getAttribute("editTemplate");
this.variableName = this.getAttribute("variable","currentTiddler");
this.nodrop = this.getAttribute("nodrop");
this.htmltag = this.getAttribute("htmltag");
this.static = this.getAttribute("static");
this.listtag=this.getAttribute("targeTtag",this.getVariable("currentTiddler"));
this.listtag=this.getAttribute("targettag",this.listtag);
// Compose the list elements
this.list = this.getTiddlerList();
var members = [],
self = this;
// Check for an empty list
if(this.list.length === 0) {
members = this.getEmptyMessage();
} else {
$tw.utils.each(this.list,function(title,index) {
members.push(self.makeItemTemplate(title));
});
}
// Construct the child widgets
this.makeChildWidgets(members);
};
TagListWidget.prototype.getTiddlerList = function() {
var defaultFilter = "[tag["+this.listtag+"]]";
return this.wiki.filterTiddlers(this.getAttribute("filter",defaultFilter),this);//BJ FIXME should not allow user defined filters
};
TagListWidget.prototype.setTiddlerList = function(what,where) {
var self = this;
if (this.nodrop || this.static) return;
var update = function(value) {
var tiddler = self.wiki.getTiddler(self.listtag)||{title:self.listtag},
updateFields = {};
updateFields["list"] = value;
self.wiki.addTiddler(new $tw.Tiddler(self.wiki.getCreationFields(),tiddler,updateFields,
self.wiki.getModificationFields()));
};
var newlist=[],
j=0;
for (var i=0;i<this.list.length;i++) {
if (this.list[i]===what) continue;
if (this.list[i]===where) {
newlist[j]=what;
j++;
}
newlist[j]=this.list[i];
j++;
}
update(newlist);
};
TagListWidget.prototype.getEmptyMessage = function() {
var emptyMessage = this.getAttribute("emptyMessage",""),
parser = this.wiki.parseText("text/vnd.tiddlywiki",emptyMessage,{parseAsInline: true});
if(parser) {
return parser.tree;
} else {
return [];
}
};
/*
Compose the template for a list item
*/
TagListWidget.prototype.makeItemTemplate = function(title) {
// Check if the tiddler is a draft
var tiddler = this.wiki.getTiddler(title),
isDraft = tiddler && tiddler.hasField("draft.of"),
template = this.template,
templateTree;
if(isDraft && this.editTemplate) {
template = this.editTemplate;
}
// Compose the transclusion of the template
if(template) {
templateTree = [{type: "transclude", attributes: {tiddler: {type: "string", value: template}}}];
} else {
if(this.parseTreeNode.children && this.parseTreeNode.children.length > 0) {
templateTree = this.parseTreeNode.children;
} else {
// Default template is a link to the title
templateTree = [{type: "element", tag: this.parseTreeNode.isBlock ? "div" : "span", children: [{type: "link", attributes: {to: {type: "string", value: title}}, children: [
{type: "text", text: title}
]}]}];
}
}
// Return the list item
if (this.nodrop) return {type: "taglistitem", itemTitle: title, variableName: this.variableName, children: templateTree, listtag:null};
return {type: "taglistitem", itemTitle: title, variableName: this.variableName, children: templateTree, listtag:this.listtag, htmltag:this.htmltag};
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
TagListWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
// Completely refresh if any of our attributes have changed
if(changedAttributes.filter || changedAttributes.template || changedAttributes.editTemplate || changedAttributes.emptyMessage || changedAttributes.storyview || changedAttributes.targeTtag) {
this.refreshSelf();
return true;
} else {
// Handle any changes to the list
var hasChanged = this.handleListChanges(changedTiddlers);
return hasChanged;
}
};
/*
Process any changes to the list
*/
TagListWidget.prototype.handleListChanges = function(changedTiddlers) {
// Get the new list
var prevList = this.list;
this.list = this.getTiddlerList();//alert(this.list);
var redolist = false;
// Check for an empty list
if(this.list.length === 0) {
// Check if it was empty before
if(prevList.length === 0) {
// If so, just refresh the empty message
return this.refreshChildren(changedTiddlers);
} else {
// Replace the previous content with the empty message
for(var t=this.children.length-1; t>=0; t--) {
this.removeListItem(t);
}
var nextSibling = this.findNextSiblingDomNode();
this.makeChildWidgets(this.getEmptyMessage());
this.renderChildren(this.parentDomNode,nextSibling);
return true;
}
} else {
// If the list was empty then we need to remove the empty message
if(prevList.length === 0)
{
this.removeChildDomNodes();
this.children = [];
}
if (prevList.length!==this.list.length) {
redolist = true;
} else {
var t;
for(t=0; t<this.list.length; t++) {
if (prevList[t]!==this.list[t]) {//compare tid titles
break;
}
}
if ( t!==this.list.length ){
redolist = true;
}
}
var hasRefreshed = false;
if (redolist === true) {
var hasRefreshed = true;
for(var t=this.children.length-1; t>=0; t--) {
this.removeListItem(t);
}
for(var t=0; t<this.list.length; t++) {
this.insertListItem(t,this.list[t]);
}
} else {
return this.refreshChildren(changedTiddlers);
}
return hasRefreshed;
}
};
/*
Find the list item with a given title, starting from a specified position
*/
TagListWidget.prototype.findListItem = function(startIndex,title) {
while(startIndex < this.children.length) {
if(this.children[startIndex].parseTreeNode.itemTitle === title) {
return startIndex;
}
startIndex++;
}
return undefined;
};
/*
Insert a new list item at the specified index
*/
TagListWidget.prototype.insertListItem = function(index,title) {
// Create, insert and render the new child widgets
var widget = this.makeChildWidget(this.makeItemTemplate(title));
widget.parentDomNode = this.parentDomNode; // Hack to enable findNextSiblingDomNode() to work
this.children.splice(index,0,widget);
var nextSibling = widget.findNextSiblingDomNode();
widget.render(this.parentDomNode,nextSibling);
// Animate the insertion if required
if(this.storyview && this.storyview.insert) {
this.storyview.insert(widget);
}
return true;
};
/*
Remove the specified list item
*/
TagListWidget.prototype.removeListItem = function(index) {
var widget = this.children[index];
// Animate the removal if required
if(this.storyview && this.storyview.remove) {
this.storyview.remove(widget);
} else {
widget.removeChildDomNodes();
}
// Remove the child widget
this.children.splice(index,1);
};
exports.taglist = TagListWidget;
var TagListItemWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
this.nodrop = this.parseTreeNode.listtag;
};
/*
Inherit from the base widget class
*/
TagListItemWidget.prototype = new Widget();
TagListItemWidget.prototype.addTag = function (tidname) {
var tiddler = this.wiki.getTiddler(tidname);
var modification = this.wiki.getModificationFields();
modification.tags = (tiddler.fields.tags || []).slice(0);
$tw.utils.pushTop(modification.tags,this.parseTreeNode.listtag);
this.wiki.addTiddler(new $tw.Tiddler(tiddler,modification));
}
TagListItemWidget.prototype.handleDropEvent = function(event) {
var self = this,
dataTransfer = event.dataTransfer,
returned = this.nameandOnListTag(dataTransfer);
if (!this.nodrop) {
this.cancelAction(event);
self.dispatchEvent({type: "tm-dropHandled", param: null});
return;
}
if (!!returned.name) { //only handle tiddler drops
if (!returned.onList) { //this means tiddler does not have the tag
this.addTag(returned.name);
}
this.parentWidget.setTiddlerList(returned.name, this.parseTreeNode.itemTitle);
//cancel normal action
this.cancelAction(event);
self.dispatchEvent({type: "tm-dropHandled", param: null});
}
//else let the event fall thru
};
TagListItemWidget.prototype.importDataTypes = [
{type: "text/vnd.tiddler", IECompatible: false, convertToFields: function(data) {
return JSON.parse(data);
}},
{type: "URL", IECompatible: true, convertToFields: function(data) {
// Check for tiddler data URI
var match = decodeURIComponent(data).match(/^data\:text\/vnd\.tiddler,(.*)/i);
if(match) {
return JSON.parse(match[1]);
} else {
return { // As URL string
text: data
};
}
}},
{type: "text/x-moz-url", IECompatible: false, convertToFields: function(data) {
// Check for tiddler data URI
var match = decodeURIComponent(data).match(/^data\:text\/vnd\.tiddler,(.*)/i);
if(match) {
return JSON.parse(match[1]);
} else {
return { // As URL string
text: data
};
}
}},
{type: "text/plain", IECompatible: false, convertToFields: function(data) {
return {
text: data
};
}},
{type: "Text", IECompatible: true, convertToFields: function(data) {
return {
text: data
};
}},
{type: "text/uri-list", IECompatible: false, convertToFields: function(data) {
return {
text: data
};
}}
];
TagListItemWidget.prototype.cancelAction =function(event) {
// Try each provided data type in turn
{
var self = this,
dataTransfer = event.dataTransfer;
event.preventDefault();
// Stop the drop ripple up to any parent handlers
event.stopPropagation();
};
};
TagListItemWidget.prototype.nameandOnListTag = function(dataTransfer) {
// Try each provided data type in turn
var self = this;
for(var t=0; t<this.importDataTypes.length; t++) {
if(!$tw.browser.isIE || this.importDataTypes[t].IECompatible) {
// Get the data
var dataType = this.importDataTypes[t];
var data = dataTransfer.getData(dataType.type);
// Import the tiddlers in the data
if(data !== "" && data !== null) {
var tiddlerFields = dataType.convertToFields(data);
if(!tiddlerFields.title) {
break;
}
if (tiddlerFields.tags && $tw.utils.parseStringArray(tiddlerFields.tags).indexOf(self.parseTreeNode.listtag) !== -1) {
return {name:tiddlerFields.title, onList:true};
}
else {//we have to add the tag to the tiddler
if (!!self.wiki.getTiddler(tiddlerFields.title)){//tid is in this tw
return {name:tiddlerFields.title, onList:false};
}
//return false;
}
}
}else alert("not found");
};
return {name:null, onList:false};
};
/*
Render this widget into the DOM
*/
TagListItemWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
var tag = "div";
if(this.parseTreeNode.htmltag && $tw.config.htmlUnsafeElements.indexOf(this.revealTag) === -1) {
tag = this.parseTreeNode.htmltag;
}
var domNode = this.document.createElement(tag);
// Add event handlers
$tw.utils.addEventListeners(domNode,[
{name: "dragover", handlerObject: this, handlerMethod: "handleDragOverEvent"},
{name: "drop", handlerObject: this, handlerMethod: "handleDropEvent"}
]);
// Insert element
parent.insertBefore(domNode,nextSibling);
this.renderChildren(domNode,null);
this.domNodes.push(domNode);
};
TagListItemWidget.prototype.handleDragOverEvent = function(event) {
//alert("OVER")
// Tell the browser that we're still interested in the drop
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
};
/*
Compute the internal state of the widget
*/
TagListItemWidget.prototype.execute = function() {
// Set the current list item title
this.setVariable(this.parseTreeNode.variableName,this.parseTreeNode.itemTitle);
// Construct the child widgets
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
TagListItemWidget.prototype.refresh = function(changedTiddlers) {
return this.refreshChildren(changedTiddlers);
};
exports.taglistitem = TagListItemWidget;
})();
/*\
title: $:/core/modules/widgets/text.js
type: application/javascript
module-type: widget
Text node widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var TextNodeWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
TextNodeWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
TextNodeWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
var text = this.getAttribute("text",this.parseTreeNode.text || "");
text = text.replace(/\r/mg,"");
var textNode = this.document.createTextNode(text);
parent.insertBefore(textNode,nextSibling);
this.domNodes.push(textNode);
};
/*
Compute the internal state of the widget
*/
TextNodeWidget.prototype.execute = function() {
// Nothing to do for a text node
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
TextNodeWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.text) {
this.refreshSelf();
return true;
} else {
return false;
}
};
exports.text = TextNodeWidget;
})();
/*\
title: $:/core/modules/widgets/tiddler.js
type: application/javascript
module-type: widget
Tiddler widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var TiddlerWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
TiddlerWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
TiddlerWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
TiddlerWidget.prototype.execute = function() {
this.tiddlerState = this.computeTiddlerState();
this.setVariable("currentTiddler",this.tiddlerState.currentTiddler);
this.setVariable("missingTiddlerClass",this.tiddlerState.missingTiddlerClass);
this.setVariable("shadowTiddlerClass",this.tiddlerState.shadowTiddlerClass);
this.setVariable("systemTiddlerClass",this.tiddlerState.systemTiddlerClass);
this.setVariable("tiddlerTagClasses",this.tiddlerState.tiddlerTagClasses);
// Construct the child widgets
this.makeChildWidgets();
};
/*
Compute the tiddler state flags
*/
TiddlerWidget.prototype.computeTiddlerState = function() {
// Get our parameters
this.tiddlerTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
// Compute the state
var state = {
currentTiddler: this.tiddlerTitle || "",
missingTiddlerClass: (this.wiki.tiddlerExists(this.tiddlerTitle) || this.wiki.isShadowTiddler(this.tiddlerTitle)) ? "tc-tiddler-exists" : "tc-tiddler-missing",
shadowTiddlerClass: this.wiki.isShadowTiddler(this.tiddlerTitle) ? "tc-tiddler-shadow" : "",
systemTiddlerClass: this.wiki.isSystemTiddler(this.tiddlerTitle) ? "tc-tiddler-system" : "",
tiddlerTagClasses: this.getTagClasses()
};
// Compute a simple hash to make it easier to detect changes
state.hash = state.currentTiddler + state.missingTiddlerClass + state.shadowTiddlerClass + state.systemTiddlerClass + state.tiddlerTagClasses;
return state;
};
/*
Create a string of CSS classes derived from the tags of the current tiddler
*/
TiddlerWidget.prototype.getTagClasses = function() {
var tiddler = this.wiki.getTiddler(this.tiddlerTitle);
if(tiddler) {
var tags = [];
$tw.utils.each(tiddler.fields.tags,function(tag) {
tags.push("tc-tagged-" + encodeURIComponent(tag));
});
return tags.join(" ");
} else {
return "";
}
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
TiddlerWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes(),
newTiddlerState = this.computeTiddlerState();
if(changedAttributes.tiddler || newTiddlerState.hash !== this.tiddlerState.hash) {
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
exports.tiddler = TiddlerWidget;
})();
/*\
title: $:/core/modules/widgets/transclude.js
type: application/javascript
module-type: widget
Transclude widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var TranscludeWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
TranscludeWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
TranscludeWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
TranscludeWidget.prototype.execute = function() {
// Get our parameters
this.transcludeTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
this.transcludeSubTiddler = this.getAttribute("subtiddler");
this.transcludeField = this.getAttribute("field");
this.transcludeIndex = this.getAttribute("index");
this.transcludeMode = this.getAttribute("mode");
// Parse the text reference
var parseAsInline = !this.parseTreeNode.isBlock;
if(this.transcludeMode === "inline") {
parseAsInline = true;
} else if(this.transcludeMode === "block") {
parseAsInline = false;
}
var parser = this.wiki.parseTextReference(
this.transcludeTitle,
this.transcludeField,
this.transcludeIndex,
{
parseAsInline: parseAsInline,
subTiddler: this.transcludeSubTiddler
}),
parseTreeNodes = parser ? parser.tree : this.parseTreeNode.children;
// Set context variables for recursion detection
var recursionMarker = this.makeRecursionMarker();
this.setVariable("transclusion",recursionMarker);
// Check for recursion
if(parser) {
if(this.parentWidget && this.parentWidget.hasVariable("transclusion",recursionMarker)) {
parseTreeNodes = [{type: "element", tag: "span", attributes: {
"class": {type: "string", value: "tc-error"}
}, children: [
{type: "text", text: "Recursive transclusion error in transclude widget"}
]}];
}
}
// Construct the child widgets
this.makeChildWidgets(parseTreeNodes);
};
/*
Compose a string comprising the title, field and/or index to identify this transclusion for recursion detection
*/
TranscludeWidget.prototype.makeRecursionMarker = function() {
var output = [];
output.push("{");
output.push(this.getVariable("currentTiddler",{defaultValue: ""}));
output.push("|");
output.push(this.transcludeTitle || "");
output.push("|");
output.push(this.transcludeField || "");
output.push("|");
output.push(this.transcludeIndex || "");
output.push("|");
output.push(this.transcludeSubTiddler || "");
output.push("}");
return output.join("");
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
TranscludeWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.tiddler || changedAttributes.field || changedAttributes.index || changedTiddlers[this.transcludeTitle]) {
this.refreshSelf();
return true;
} else {
return this.refreshChildren(changedTiddlers);
}
};
exports.transclude = TranscludeWidget;
})();
/*\
title: $:/core/modules/widgets/vars.js
type: application/javascript
module-type: widget
This widget allows multiple variables to be set in one go:
```
\define helloworld() Hello world!
<$vars greeting="Hi" me={{!!title}} sentence=<<helloworld>>>
<<greeting>>! I am <<me>> and I say: <<sentence>>
</$vars>
```
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var VarsWidget = function(parseTreeNode,options) {
// Call the constructor
Widget.call(this);
// Initialise
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
VarsWidget.prototype = Object.create(Widget.prototype);
/*
Render this widget into the DOM
*/
VarsWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
VarsWidget.prototype.execute = function() {
// Parse variables
var self = this;
$tw.utils.each(this.attributes,function(val,key) {
if(key.charAt(0) !== "$") {
self.setVariable(key,val);
}
});
// Construct the child widgets
this.makeChildWidgets();
};
/*
Refresh the widget by ensuring our attributes are up to date
*/
VarsWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(Object.keys(changedAttributes).length) {
this.refreshSelf();
return true;
}
return this.refreshChildren(changedTiddlers);
};
exports["vars"] = VarsWidget;
})();
/*\
title: $:/core/modules/widgets/view.js
type: application/javascript
module-type: widget
View widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var ViewWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
ViewWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
ViewWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
if(this.text) {
var textNode = this.document.createTextNode(this.text);
parent.insertBefore(textNode,nextSibling);
this.domNodes.push(textNode);
} else {
this.makeChildWidgets();
this.renderChildren(parent,nextSibling);
}
};
/*
Compute the internal state of the widget
*/
ViewWidget.prototype.execute = function() {
// Get parameters from our attributes
this.viewTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));
this.viewSubtiddler = this.getAttribute("subtiddler");
this.viewField = this.getAttribute("field","text");
this.viewIndex = this.getAttribute("index");
this.viewFormat = this.getAttribute("format","text");
this.viewTemplate = this.getAttribute("template","");
switch(this.viewFormat) {
case "htmlwikified":
this.text = this.getValueAsHtmlWikified();
break;
case "htmlencodedplainwikified":
this.text = this.getValueAsHtmlEncodedPlainWikified();
break;
case "htmlencoded":
this.text = this.getValueAsHtmlEncoded();
break;
case "urlencoded":
this.text = this.getValueAsUrlEncoded();
break;
case "doubleurlencoded":
this.text = this.getValueAsDoubleUrlEncoded();
break;
case "date":
this.text = this.getValueAsDate(this.viewTemplate);
break;
case "relativedate":
this.text = this.getValueAsRelativeDate();
break;
case "stripcomments":
this.text = this.getValueAsStrippedComments();
break;
case "jsencoded":
this.text = this.getValueAsJsEncoded();
break;
default: // "text"
this.text = this.getValueAsText();
break;
}
};
/*
The various formatter functions are baked into this widget for the moment. Eventually they will be replaced by macro functions
*/
/*
Retrieve the value of the widget. Options are:
asString: Optionally return the value as a string
*/
ViewWidget.prototype.getValue = function(options) {
options = options || {};
var value = options.asString ? "" : undefined;
if(this.viewIndex) {
value = this.wiki.extractTiddlerDataItem(this.viewTitle,this.viewIndex);
} else {
var tiddler;
if(this.viewSubtiddler) {
tiddler = this.wiki.getSubTiddler(this.viewTitle,this.viewSubtiddler);
} else {
tiddler = this.wiki.getTiddler(this.viewTitle);
}
if(tiddler) {
if(this.viewField === "text" && !this.viewSubtiddler) {
// Calling getTiddlerText() triggers lazy loading of skinny tiddlers
value = this.wiki.getTiddlerText(this.viewTitle);
} else {
if($tw.utils.hop(tiddler.fields,this.viewField)) {
if(options.asString) {
value = tiddler.getFieldString(this.viewField);
} else {
value = tiddler.fields[this.viewField];
}
}
}
} else {
if(this.viewField === "title") {
value = this.viewTitle;
}
}
}
return value;
};
ViewWidget.prototype.getValueAsText = function() {
return this.getValue({asString: true});
};
ViewWidget.prototype.getValueAsHtmlWikified = function() {
return this.wiki.renderText("text/html","text/vnd.tiddlywiki",this.getValueAsText(),{parentWidget: this});
};
ViewWidget.prototype.getValueAsHtmlEncodedPlainWikified = function() {
return $tw.utils.htmlEncode(this.wiki.renderText("text/plain","text/vnd.tiddlywiki",this.getValueAsText(),{parentWidget: this}));
};
ViewWidget.prototype.getValueAsHtmlEncoded = function() {
return $tw.utils.htmlEncode(this.getValueAsText());
};
ViewWidget.prototype.getValueAsUrlEncoded = function() {
return encodeURIComponent(this.getValueAsText());
};
ViewWidget.prototype.getValueAsDoubleUrlEncoded = function() {
return encodeURIComponent(encodeURIComponent(this.getValueAsText()));
};
ViewWidget.prototype.getValueAsDate = function(format) {
format = format || "YYYY MM DD 0hh:0mm";
var value = $tw.utils.parseDate(this.getValue());
if(value && $tw.utils.isDate(value) && value.toString() !== "Invalid Date") {
return $tw.utils.formatDateString(value,format);
} else {
return "";
}
};
ViewWidget.prototype.getValueAsRelativeDate = function(format) {
var value = $tw.utils.parseDate(this.getValue());
if(value && $tw.utils.isDate(value) && value.toString() !== "Invalid Date") {
return $tw.utils.getRelativeDate((new Date()) - (new Date(value))).description;
} else {
return "";
}
};
ViewWidget.prototype.getValueAsStrippedComments = function() {
var lines = this.getValueAsText().split("\n"),
out = [];
for(var line=0; line<lines.length; line++) {
var text = lines[line];
if(!/^\s*\/\/#/.test(text)) {
out.push(text);
}
}
return out.join("\n");
};
ViewWidget.prototype.getValueAsJsEncoded = function() {
return $tw.utils.stringify(this.getValueAsText());
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ViewWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.tiddler || changedAttributes.field || changedAttributes.index || changedAttributes.template || changedAttributes.format || changedTiddlers[this.viewTitle]) {
this.refreshSelf();
return true;
} else {
return false;
}
};
exports.view = ViewWidget;
})();
/*\
title: $:/core/modules/widgets/widget.js
type: application/javascript
module-type: widget
Widget base class
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Create a widget object for a parse tree node
parseTreeNode: reference to the parse tree node to be rendered
options: see below
Options include:
wiki: mandatory reference to wiki associated with this render tree
parentWidget: optional reference to a parent renderer node for the context chain
document: optional document object to use instead of global document
*/
var Widget = function(parseTreeNode,options) {
if(arguments.length > 0) {
this.initialise(parseTreeNode,options);
}
};
/*
Initialise widget properties. These steps are pulled out of the constructor so that we can reuse them in subclasses
*/
Widget.prototype.initialise = function(parseTreeNode,options) {
options = options || {};
// Save widget info
this.parseTreeNode = parseTreeNode;
this.wiki = options.wiki;
this.parentWidget = options.parentWidget;
this.variablesConstructor = function() {};
this.variablesConstructor.prototype = this.parentWidget ? this.parentWidget.variables : {};
this.variables = new this.variablesConstructor();
this.document = options.document;
this.attributes = {};
this.children = [];
this.domNodes = [];
this.eventListeners = {};
// Hashmap of the widget classes
if(!this.widgetClasses) {
Widget.prototype.widgetClasses = $tw.modules.applyMethods("widget");
}
};
/*
Render this widget into the DOM
*/
Widget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.execute();
this.renderChildren(parent,nextSibling);
};
/*
Compute the internal state of the widget
*/
Widget.prototype.execute = function() {
this.makeChildWidgets();
};
/*
Set the value of a context variable
name: name of the variable
value: value of the variable
params: array of {name:, default:} for each parameter
*/
Widget.prototype.setVariable = function(name,value,params) {
this.variables[name] = {value: value, params: params};
};
/*
Get the prevailing value of a context variable
name: name of variable
options: see below
Options include
params: array of {name:, value:} for each parameter
defaultValue: default value if the variable is not defined
*/
Widget.prototype.getVariable = function(name,options) {
options = options || {};
var actualParams = options.params || [],
parentWidget = this.parentWidget;
// Check for the variable defined in the parent widget (or an ancestor in the prototype chain)
if(parentWidget && name in parentWidget.variables) {
var variable = parentWidget.variables[name],
value = variable.value;
// Substitute any parameters specified in the definition
value = this.substituteVariableParameters(value,variable.params,actualParams);
value = this.substituteVariableReferences(value);
return value;
}
// If the variable doesn't exist in the parent widget then look for a macro module
return this.evaluateMacroModule(name,actualParams,options.defaultValue);
};
Widget.prototype.substituteVariableParameters = function(text,formalParams,actualParams) {
if(formalParams) {
var nextAnonParameter = 0, // Next candidate anonymous parameter in macro call
paramInfo, paramValue;
// Step through each of the parameters in the macro definition
for(var p=0; p<formalParams.length; p++) {
// Check if we've got a macro call parameter with the same name
paramInfo = formalParams[p];
paramValue = undefined;
for(var m=0; m<actualParams.length; m++) {
if(actualParams[m].name === paramInfo.name) {
paramValue = actualParams[m].value;
}
}
// If not, use the next available anonymous macro call parameter
while(nextAnonParameter < actualParams.length && actualParams[nextAnonParameter].name) {
nextAnonParameter++;
}
if(paramValue === undefined && nextAnonParameter < actualParams.length) {
paramValue = actualParams[nextAnonParameter++].value;
}
// If we've still not got a value, use the default, if any
paramValue = paramValue || paramInfo["default"] || "";
// Replace any instances of this parameter
text = text.replace(new RegExp("\\$" + $tw.utils.escapeRegExp(paramInfo.name) + "\\$","mg"),paramValue);
}
}
return text;
};
Widget.prototype.substituteVariableReferences = function(text) {
var self = this;
return (text || "").replace(/\$\(([^\)\$]+)\)\$/g,function(match,p1,offset,string) {
return self.getVariable(p1,{defaultValue: ""});
});
};
Widget.prototype.evaluateMacroModule = function(name,actualParams,defaultValue) {
if($tw.utils.hop($tw.macros,name)) {
var macro = $tw.macros[name],
args = [];
if(macro.params.length > 0) {
var nextAnonParameter = 0, // Next candidate anonymous parameter in macro call
paramInfo, paramValue;
// Step through each of the parameters in the macro definition
for(var p=0; p<macro.params.length; p++) {
// Check if we've got a macro call parameter with the same name
paramInfo = macro.params[p];
paramValue = undefined;
for(var m=0; m<actualParams.length; m++) {
if(actualParams[m].name === paramInfo.name) {
paramValue = actualParams[m].value;
}
}
// If not, use the next available anonymous macro call parameter
while(nextAnonParameter < actualParams.length && actualParams[nextAnonParameter].name) {
nextAnonParameter++;
}
if(paramValue === undefined && nextAnonParameter < actualParams.length) {
paramValue = actualParams[nextAnonParameter++].value;
}
// If we've still not got a value, use the default, if any
paramValue = paramValue || paramInfo["default"] || "";
// Save the parameter
args.push(paramValue);
}
}
else for(var i=0; i<actualParams.length; ++i) {
args.push(actualParams[i].value);
}
return (macro.run.apply(this,args) || "").toString();
} else {
return defaultValue;
}
};
/*
Check whether a given context variable value exists in the parent chain
*/
Widget.prototype.hasVariable = function(name,value) {
var node = this;
while(node) {
if($tw.utils.hop(node.variables,name) && node.variables[name].value === value) {
return true;
}
node = node.parentWidget;
}
return false;
};
/*
Construct a qualifying string based on a hash of concatenating the values of a given variable in the parent chain
*/
Widget.prototype.getStateQualifier = function(name) {
this.qualifiers = this.qualifiers || Object.create(null);
name = name || "transclusion";
if(this.qualifiers[name]) {
return this.qualifiers[name];
} else {
var output = [],
node = this;
while(node && node.parentWidget) {
if($tw.utils.hop(node.parentWidget.variables,name)) {
output.push(node.getVariable(name));
}
node = node.parentWidget;
}
var value = $tw.utils.hashString(output.join(""));
this.qualifiers[name] = value;
return value;
}
};
/*
Compute the current values of the attributes of the widget. Returns a hashmap of the names of the attributes that have changed
*/
Widget.prototype.computeAttributes = function() {
var changedAttributes = {},
self = this,
value;
$tw.utils.each(this.parseTreeNode.attributes,function(attribute,name) {
if(attribute.type === "indirect") {
value = self.wiki.getTextReference(attribute.textReference,"",self.getVariable("currentTiddler"));
} else if(attribute.type === "macro") {
value = self.getVariable(attribute.value.name,{params: attribute.value.params});
} else { // String attribute
value = attribute.value;
}
// Check whether the attribute has changed
if(self.attributes[name] !== value) {
self.attributes[name] = value;
changedAttributes[name] = true;
}
});
return changedAttributes;
};
/*
Check for the presence of an attribute
*/
Widget.prototype.hasAttribute = function(name) {
return $tw.utils.hop(this.attributes,name);
};
/*
Get the value of an attribute
*/
Widget.prototype.getAttribute = function(name,defaultText) {
if($tw.utils.hop(this.attributes,name)) {
return this.attributes[name];
} else {
return defaultText;
}
};
/*
Assign the computed attributes of the widget to a domNode
options include:
excludeEventAttributes: ignores attributes whose name begins with "on"
*/
Widget.prototype.assignAttributes = function(domNode,options) {
options = options || {};
var self = this;
$tw.utils.each(this.attributes,function(v,a) {
// Check exclusions
if(options.excludeEventAttributes && a.substr(0,2) === "on") {
v = undefined;
}
if(v !== undefined) {
var b = a.split(":");
// Setting certain attributes can cause a DOM error (eg xmlns on the svg element)
try {
if (b.length == 2 && b[0] == "xlink"){
domNode.setAttributeNS("http://www.w3.org/1999/xlink",b[1],v);
} else {
domNode.setAttributeNS(null,a,v);
}
} catch(e) {
}
}
});
};
/*
Make child widgets correspondng to specified parseTreeNodes
*/
Widget.prototype.makeChildWidgets = function(parseTreeNodes) {
this.children = [];
var self = this;
$tw.utils.each(parseTreeNodes || (this.parseTreeNode && this.parseTreeNode.children),function(childNode) {
self.children.push(self.makeChildWidget(childNode));
});
};
/*
Construct the widget object for a parse tree node
*/
Widget.prototype.makeChildWidget = function(parseTreeNode) {
var WidgetClass = this.widgetClasses[parseTreeNode.type];
if(!WidgetClass) {
WidgetClass = this.widgetClasses.text;
parseTreeNode = {type: "text", text: "Undefined widget '" + parseTreeNode.type + "'"};
}
return new WidgetClass(parseTreeNode,{
wiki: this.wiki,
variables: {},
parentWidget: this,
document: this.document
});
};
/*
Get the next sibling of this widget
*/
Widget.prototype.nextSibling = function() {
if(this.parentWidget) {
var index = this.parentWidget.children.indexOf(this);
if(index !== -1 && index < this.parentWidget.children.length-1) {
return this.parentWidget.children[index+1];
}
}
return null;
};
/*
Get the previous sibling of this widget
*/
Widget.prototype.previousSibling = function() {
if(this.parentWidget) {
var index = this.parentWidget.children.indexOf(this);
if(index !== -1 && index > 0) {
return this.parentWidget.children[index-1];
}
}
return null;
};
/*
Render the children of this widget into the DOM
*/
Widget.prototype.renderChildren = function(parent,nextSibling) {
$tw.utils.each(this.children,function(childWidget) {
childWidget.render(parent,nextSibling);
});
};
/*
Add a list of event listeners from an array [{type:,handler:},...]
*/
Widget.prototype.addEventListeners = function(listeners) {
var self = this;
$tw.utils.each(listeners,function(listenerInfo) {
self.addEventListener(listenerInfo.type,listenerInfo.handler);
});
};
/*
Add an event listener
*/
Widget.prototype.addEventListener = function(type,handler) {
var self = this;
if(typeof handler === "string") { // The handler is a method name on this widget
this.eventListeners[type] = function(event) {
return self[handler].call(self,event);
};
} else { // The handler is a function
this.eventListeners[type] = function(event) {
return handler.call(self,event);
};
}
};
/*
Dispatch an event to a widget. If the widget doesn't handle the event then it is also dispatched to the parent widget
*/
Widget.prototype.dispatchEvent = function(event) {
// Dispatch the event if this widget handles it
var listener = this.eventListeners[event.type];
if(listener) {
// Don't propagate the event if the listener returned false
if(!listener(event)) {
return false;
}
}
// Dispatch the event to the parent widget
if(this.parentWidget) {
return this.parentWidget.dispatchEvent(event);
}
return true;
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
Widget.prototype.refresh = function(changedTiddlers) {
return this.refreshChildren(changedTiddlers);
};
/*
Rebuild a previously rendered widget
*/
Widget.prototype.refreshSelf = function() {
var nextSibling = this.findNextSiblingDomNode();
this.removeChildDomNodes();
this.render(this.parentDomNode,nextSibling);
};
/*
Refresh all the children of a widget
*/
Widget.prototype.refreshChildren = function(changedTiddlers) {
var self = this,
refreshed = false;
$tw.utils.each(this.children,function(childWidget) {
refreshed = childWidget.refresh(changedTiddlers) || refreshed;
});
return refreshed;
};
/*
Find the next sibling in the DOM to this widget. This is done by scanning the widget tree through all next siblings and their descendents that share the same parent DOM node
*/
Widget.prototype.findNextSiblingDomNode = function(startIndex) {
// Refer to this widget by its index within its parents children
var parent = this.parentWidget,
index = startIndex !== undefined ? startIndex : parent.children.indexOf(this);
if(index === -1) {
throw "node not found in parents children";
}
// Look for a DOM node in the later siblings
while(++index < parent.children.length) {
var domNode = parent.children[index].findFirstDomNode();
if(domNode) {
return domNode;
}
}
// Go back and look for later siblings of our parent if it has the same parent dom node
var grandParent = parent.parentWidget;
if(grandParent && parent.parentDomNode === this.parentDomNode) {
index = grandParent.children.indexOf(parent);
if(index !== -1) {
return parent.findNextSiblingDomNode(index);
}
}
return null;
};
/*
Find the first DOM node generated by a widget or its children
*/
Widget.prototype.findFirstDomNode = function() {
// Return the first dom node of this widget, if we've got one
if(this.domNodes.length > 0) {
return this.domNodes[0];
}
// Otherwise, recursively call our children
for(var t=0; t<this.children.length; t++) {
var domNode = this.children[t].findFirstDomNode();
if(domNode) {
return domNode;
}
}
return null;
};
/*
Remove any DOM nodes created by this widget or its children
*/
Widget.prototype.removeChildDomNodes = function() {
// If this widget has directly created DOM nodes, delete them and exit. This assumes that any child widgets are contained within the created DOM nodes, which would normally be the case
if(this.domNodes.length > 0) {
$tw.utils.each(this.domNodes,function(domNode) {
domNode.parentNode.removeChild(domNode);
});
this.domNodes = [];
} else {
// Otherwise, ask the child widgets to delete their DOM nodes
$tw.utils.each(this.children,function(childWidget) {
childWidget.removeChildDomNodes();
});
}
};
/*
Invoke the action widgets that are descendents of the current widget.
*/
Widget.prototype.invokeActions = function(triggeringWidget,event) {
var handled = false;
// For each child widget
for(var t=0; t<this.children.length; t++) {
var child = this.children[t];
// Invoke the child if it is an action widget
if(child.invokeAction && child.invokeAction(triggeringWidget,event)) {
handled = true;
}
// Propagate through through the child if it permits it
if(child.allowActionPropagation() && child.invokeActions(triggeringWidget,event)) {
handled = true;
}
}
return handled;
};
Widget.prototype.allowActionPropagation = function() {
return true;
};
exports.widget = Widget;
})();
/*\
title: $:/core/modules/wiki-bulkops.js
type: application/javascript
module-type: wikimethod
Bulk tiddler operations such as rename.
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Rename a tiddler, and relink any tags or lists that reference it.
*/
exports.renameTiddler = function(fromTitle,toTitle) {
var self = this;
fromTitle = (fromTitle || "").trim();
toTitle = (toTitle || "").trim();
if(fromTitle && toTitle && fromTitle !== toTitle) {
// Rename the tiddler itself
var tiddler = this.getTiddler(fromTitle);
this.addTiddler(new $tw.Tiddler(tiddler,{title: toTitle},this.getModificationFields()));
this.deleteTiddler(fromTitle);
// Rename any tags or lists that reference it
this.each(function(tiddler,title) {
var tags = (tiddler.fields.tags || []).slice(0),
list = (tiddler.fields.list || []).slice(0),
isModified = false;
// Rename tags
$tw.utils.each(tags,function (title,index) {
if(title === fromTitle) {
tags[index] = toTitle;
isModified = true;
}
});
// Rename lists
$tw.utils.each(list,function (title,index) {
if(title === fromTitle) {
list[index] = toTitle;
isModified = true;
}
});
if(isModified) {
self.addTiddler(new $tw.Tiddler(tiddler,{tags: tags, list: list},self.getModificationFields()));
}
});
}
}
})();
/*\
title: $:/core/modules/wiki.js
type: application/javascript
module-type: wikimethod
Extension methods for the $tw.Wiki object
Adds the following properties to the wiki object:
* `eventListeners` is a hashmap by type of arrays of listener functions
* `changedTiddlers` is a hashmap describing changes to named tiddlers since wiki change events were last dispatched. Each entry is a hashmap containing two fields:
modified: true/false
deleted: true/false
* `changeCount` is a hashmap by tiddler title containing a numerical index that starts at zero and is incremented each time a tiddler is created changed or deleted
* `caches` is a hashmap by tiddler title containing a further hashmap of named cache objects. Caches are automatically cleared when a tiddler is modified or deleted
* `globalCache` is a hashmap by cache name of cache objects that are cleared whenever any tiddler change occurs
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var widget = require("$:/core/modules/widgets/widget.js");
var USER_NAME_TITLE = "$:/status/UserName";
/*
Get the value of a text reference. Text references can have any of these forms:
<tiddlertitle>
<tiddlertitle>!!<fieldname>
!!<fieldname> - specifies a field of the current tiddlers
<tiddlertitle>##<index>
*/
exports.getTextReference = function(textRef,defaultText,currTiddlerTitle) {
var tr = $tw.utils.parseTextReference(textRef),
title = tr.title || currTiddlerTitle;
if(tr.field) {
var tiddler = this.getTiddler(title);
if(tr.field === "title") { // Special case so we can return the title of a non-existent tiddler
return title;
} else if(tiddler && $tw.utils.hop(tiddler.fields,tr.field)) {
return tiddler.getFieldString(tr.field);
} else {
return defaultText;
}
} else if(tr.index) {
return this.extractTiddlerDataItem(title,tr.index,defaultText);
} else {
return this.getTiddlerText(title,defaultText);
}
};
exports.setTextReference = function(textRef,value,currTiddlerTitle) {
var tr = $tw.utils.parseTextReference(textRef),
title = tr.title || currTiddlerTitle;
this.setText(title,tr.field,tr.index,value);
};
exports.setText = function(title,field,index,value,options) {
options = options || {};
var creationFields = options.suppressTimestamp ? {} : this.getCreationFields(),
modificationFields = options.suppressTimestamp ? {} : this.getModificationFields();
// Check if it is a reference to a tiddler field
if(index) {
var data = this.getTiddlerData(title,Object.create(null));
if(value !== undefined) {
data[index] = value;
} else {
delete data[index];
}
this.setTiddlerData(title,data,modificationFields);
} else {
var tiddler = this.getTiddler(title),
fields = {title: title};
fields[field || "text"] = value;
this.addTiddler(new $tw.Tiddler(creationFields,tiddler,fields,modificationFields));
}
};
exports.deleteTextReference = function(textRef,currTiddlerTitle) {
var tr = $tw.utils.parseTextReference(textRef),
title,tiddler,fields;
// Check if it is a reference to a tiddler
if(tr.title && !tr.field) {
this.deleteTiddler(tr.title);
// Else check for a field reference
} else if(tr.field) {
title = tr.title || currTiddlerTitle;
tiddler = this.getTiddler(title);
if(tiddler && $tw.utils.hop(tiddler.fields,tr.field)) {
fields = Object.create(null);
fields[tr.field] = undefined;
this.addTiddler(new $tw.Tiddler(tiddler,fields,this.getModificationFields()));
}
}
};
exports.addEventListener = function(type,listener) {
this.eventListeners = this.eventListeners || {};
this.eventListeners[type] = this.eventListeners[type] || [];
this.eventListeners[type].push(listener);
};
exports.removeEventListener = function(type,listener) {
var listeners = this.eventListeners[type];
if(listeners) {
var p = listeners.indexOf(listener);
if(p !== -1) {
listeners.splice(p,1);
}
}
};
exports.dispatchEvent = function(type /*, args */) {
var args = Array.prototype.slice.call(arguments,1),
listeners = this.eventListeners[type];
if(listeners) {
for(var p=0; p<listeners.length; p++) {
var listener = listeners[p];
listener.apply(listener,args);
}
}
};
/*
Causes a tiddler to be marked as changed, incrementing the change count, and triggers event handlers.
This method should be called after the changes it describes have been made to the wiki.tiddlers[] array.
title: Title of tiddler
isDeleted: defaults to false (meaning the tiddler has been created or modified),
true if the tiddler has been deleted
*/
exports.enqueueTiddlerEvent = function(title,isDeleted) {
// Record the touch in the list of changed tiddlers
this.changedTiddlers = this.changedTiddlers || Object.create(null);
this.changedTiddlers[title] = this.changedTiddlers[title] || Object.create(null);
this.changedTiddlers[title][isDeleted ? "deleted" : "modified"] = true;
// Increment the change count
this.changeCount = this.changeCount || Object.create(null);
if($tw.utils.hop(this.changeCount,title)) {
this.changeCount[title]++;
} else {
this.changeCount[title] = 1;
}
// Trigger events
this.eventListeners = this.eventListeners || {};
if(!this.eventsTriggered) {
var self = this;
$tw.utils.nextTick(function() {
var changes = self.changedTiddlers;
self.changedTiddlers = Object.create(null);
self.eventsTriggered = false;
if($tw.utils.count(changes) > 0) {
self.dispatchEvent("change",changes);
}
});
this.eventsTriggered = true;
}
};
exports.getSizeOfTiddlerEventQueue = function() {
return $tw.utils.count(this.changedTiddlers);
};
exports.clearTiddlerEventQueue = function() {
this.changedTiddlers = Object.create(null);
this.changeCount = Object.create(null);
};
exports.getChangeCount = function(title) {
this.changeCount = this.changeCount || Object.create(null);
if($tw.utils.hop(this.changeCount,title)) {
return this.changeCount[title];
} else {
return 0;
}
};
/*
Generate an unused title from the specified base
*/
exports.generateNewTitle = function(baseTitle,options) {
options = options || {};
var c = 0,
title = baseTitle;
while(this.tiddlerExists(title) || this.isShadowTiddler(title) || this.findDraft(title)) {
title = baseTitle +
(options.prefix || " ") +
(++c);
}
return title;
};
exports.isSystemTiddler = function(title) {
return title && title.indexOf("$:/") === 0;
};
exports.isTemporaryTiddler = function(title) {
return title && title.indexOf("$:/temp/") === 0;
};
exports.isImageTiddler = function(title) {
var tiddler = this.getTiddler(title);
if(tiddler) {
var contentTypeInfo = $tw.config.contentTypeInfo[tiddler.fields.type || "text/vnd.tiddlywiki"];
return !!contentTypeInfo && contentTypeInfo.flags.indexOf("image") !== -1;
} else {
return null;
}
};
/*
Like addTiddler() except it will silently reject any plugin tiddlers that are older than the currently loaded version. Returns true if the tiddler was imported
*/
exports.importTiddler = function(tiddler) {
var existingTiddler = this.getTiddler(tiddler.fields.title);
// Check if we're dealing with a plugin
if(tiddler && tiddler.hasField("plugin-type") && tiddler.hasField("version") && existingTiddler && existingTiddler.hasField("plugin-type") && existingTiddler.hasField("version")) {
// Reject the incoming plugin if it is older
if(!$tw.utils.checkVersions(tiddler.fields.version,existingTiddler.fields.version)) {
return false;
}
}
// Fall through to adding the tiddler
this.addTiddler(tiddler);
return true;
};
/*
Return a hashmap of the fields that should be set when a tiddler is created
*/
exports.getCreationFields = function() {
var fields = {
created: new Date()
},
creator = this.getTiddlerText(USER_NAME_TITLE);
if(creator) {
fields.creator = creator;
}
return fields;
};
/*
Return a hashmap of the fields that should be set when a tiddler is modified
*/
exports.getModificationFields = function() {
var fields = Object.create(null),
modifier = this.getTiddlerText(USER_NAME_TITLE);
fields.modified = new Date();
if(modifier) {
fields.modifier = modifier;
}
return fields;
};
/*
Return a sorted array of tiddler titles. Options include:
sortField: field to sort by
excludeTag: tag to exclude
includeSystem: whether to include system tiddlers (defaults to false)
*/
exports.getTiddlers = function(options) {
options = options || Object.create(null);
var self = this,
sortField = options.sortField || "title",
tiddlers = [], t, titles = [];
this.each(function(tiddler,title) {
if(options.includeSystem || !self.isSystemTiddler(title)) {
if(!options.excludeTag || !tiddler.hasTag(options.excludeTag)) {
tiddlers.push(tiddler);
}
}
});
tiddlers.sort(function(a,b) {
var aa = a.fields[sortField].toLowerCase() || "",
bb = b.fields[sortField].toLowerCase() || "";
if(aa < bb) {
return -1;
} else {
if(aa > bb) {
return 1;
} else {
return 0;
}
}
});
for(t=0; t<tiddlers.length; t++) {
titles.push(tiddlers[t].fields.title);
}
return titles;
};
exports.countTiddlers = function(excludeTag) {
var tiddlers = this.getTiddlers({excludeTag: excludeTag});
return $tw.utils.count(tiddlers);
};
/*
Returns a function iterator(callback) that iterates through the specified titles, and invokes the callback with callback(tiddler,title)
*/
exports.makeTiddlerIterator = function(titles) {
var self = this;
if(!$tw.utils.isArray(titles)) {
titles = Object.keys(titles);
} else {
titles = titles.slice(0);
}
return function(callback) {
titles.forEach(function(title) {
callback(self.getTiddler(title),title);
});
};
};
/*
Sort an array of tiddler titles by a specified field
titles: array of titles (sorted in place)
sortField: name of field to sort by
isDescending: true if the sort should be descending
isCaseSensitive: true if the sort should consider upper and lower case letters to be different
*/
exports.sortTiddlers = function(titles,sortField,isDescending,isCaseSensitive,isNumeric) {
var self = this;
titles.sort(function(a,b) {
var x,y,
compareNumbers = function(x,y) {
var result =
isNaN(x) && !isNaN(y) ? (isDescending ? -1 : 1) :
!isNaN(x) && isNaN(y) ? (isDescending ? 1 : -1) :
(isDescending ? y - x : x - y);
return result;
};
if(sortField !== "title") {
var tiddlerA = self.getTiddler(a),
tiddlerB = self.getTiddler(b);
if(tiddlerA) {
a = tiddlerA.fields[sortField] || "";
} else {
a = "";
}
if(tiddlerB) {
b = tiddlerB.fields[sortField] || "";
} else {
b = "";
}
}
x = Number(a);
y = Number(b);
if(isNumeric && (!isNaN(x) || !isNaN(y))) {
return compareNumbers(x,y);
} else if($tw.utils.isDate(a) && $tw.utils.isDate(b)) {
return isDescending ? b - a : a - b;
} else {
a = String(a);
b = String(b);
if(!isCaseSensitive) {
a = a.toLowerCase();
b = b.toLowerCase();
}
return isDescending ? b.localeCompare(a) : a.localeCompare(b);
}
});
};
/*
For every tiddler invoke a callback(title,tiddler) with `this` set to the wiki object. Options include:
sortField: field to sort by
excludeTag: tag to exclude
includeSystem: whether to include system tiddlers (defaults to false)
*/
exports.forEachTiddler = function(/* [options,]callback */) {
var arg = 0,
options = arguments.length >= 2 ? arguments[arg++] : {},
callback = arguments[arg++],
titles = this.getTiddlers(options),
t, tiddler;
for(t=0; t<titles.length; t++) {
tiddler = this.getTiddler(titles[t]);
if(tiddler) {
callback.call(this,tiddler.fields.title,tiddler);
}
}
};
/*
Return an array of tiddler titles that are directly linked from the specified tiddler
*/
exports.getTiddlerLinks = function(title) {
var self = this;
// We'll cache the links so they only get computed if the tiddler changes
return this.getCacheForTiddler(title,"links",function() {
// Parse the tiddler
var parser = self.parseTiddler(title);
// Count up the links
var links = [],
checkParseTree = function(parseTree) {
for(var t=0; t<parseTree.length; t++) {
var parseTreeNode = parseTree[t];
if(parseTreeNode.type === "link" && parseTreeNode.attributes.to && parseTreeNode.attributes.to.type === "string") {
var value = parseTreeNode.attributes.to.value;
if(links.indexOf(value) === -1) {
links.push(value);
}
}
if(parseTreeNode.children) {
checkParseTree(parseTreeNode.children);
}
}
};
if(parser) {
checkParseTree(parser.tree);
}
return links;
});
};
/*
Return an array of tiddler titles that link to the specified tiddler
*/
exports.getTiddlerBacklinks = function(targetTitle) {
var self = this,
backlinks = [];
this.forEachTiddler(function(title,tiddler) {
var links = self.getTiddlerLinks(title);
if(links.indexOf(targetTitle) !== -1) {
backlinks.push(title);
}
});
return backlinks;
};
/*
Return a hashmap of tiddler titles that are referenced but not defined. Each value is the number of times the missing tiddler is referenced
*/
exports.getMissingTitles = function() {
var self = this,
missing = [];
// We should cache the missing tiddler list, even if we recreate it every time any tiddler is modified
this.forEachTiddler(function(title,tiddler) {
var links = self.getTiddlerLinks(title);
$tw.utils.each(links,function(link) {
if((!self.tiddlerExists(link) && !self.isShadowTiddler(link)) && missing.indexOf(link) === -1) {
missing.push(link);
}
});
});
return missing;
};
exports.getOrphanTitles = function() {
var self = this,
orphans = this.getTiddlers();
this.forEachTiddler(function(title,tiddler) {
var links = self.getTiddlerLinks(title);
$tw.utils.each(links,function(link) {
var p = orphans.indexOf(link);
if(p !== -1) {
orphans.splice(p,1);
}
});
});
return orphans; // Todo
};
/*
Retrieves a list of the tiddler titles that are tagged with a given tag
*/
exports.getTiddlersWithTag = function(tag) {
var self = this;
return this.getGlobalCache("taglist-" + tag,function() {
var tagmap = self.getTagMap();
return self.sortByList(tagmap[tag],tag);
});
};
/*
Get a hashmap by tag of arrays of tiddler titles
*/
exports.getTagMap = function() {
var self = this;
return this.getGlobalCache("tagmap",function() {
var tags = Object.create(null),
storeTags = function(tagArray,title) {
if(tagArray) {
for(var index=0; index<tagArray.length; index++) {
var tag = tagArray[index];
if($tw.utils.hop(tags,tag)) {
tags[tag].push(title);
} else {
tags[tag] = [title];
}
}
}
},
title, tiddler;
// Collect up all the tags
self.eachShadow(function(tiddler,title) {
if(!self.tiddlerExists(title)) {
tiddler = self.getTiddler(title);
storeTags(tiddler.fields.tags,title);
}
});
self.each(function(tiddler,title) {
storeTags(tiddler.fields.tags,title);
});
return tags;
});
};
/*
Lookup a given tiddler and return a list of all the tiddlers that include it in the specified list field
*/
exports.findListingsOfTiddler = function(targetTitle,fieldName) {
fieldName = fieldName || "list";
var titles = [];
this.each(function(tiddler,title) {
var list = $tw.utils.parseStringArray(tiddler.fields[fieldName]);
if(list && list.indexOf(targetTitle) !== -1) {
titles.push(title);
}
});
return titles;
};
/*
Sorts an array of tiddler titles according to an ordered list
*/
exports.sortByList = function(array,listTitle) {
var list = this.getTiddlerList(listTitle);
if(!array || array.length === 0) {
return [];
} else {
var titles = [], t, title;
// First place any entries that are present in the list
for(t=0; t<list.length; t++) {
title = list[t];
if(array.indexOf(title) !== -1) {
titles.push(title);
}
}
// Then place any remaining entries
for(t=0; t<array.length; t++) {
title = array[t];
if(list.indexOf(title) === -1) {
titles.push(title);
}
}
// Finally obey the list-before and list-after fields of each tiddler in turn
var sortedTitles = titles.slice(0);
for(t=0; t<sortedTitles.length; t++) {
title = sortedTitles[t];
var currPos = titles.indexOf(title),
newPos = -1,
tiddler = this.getTiddler(title);
if(tiddler) {
var beforeTitle = tiddler.fields["list-before"],
afterTitle = tiddler.fields["list-after"];
if(beforeTitle === "") {
newPos = 0;
} else if(beforeTitle) {
newPos = titles.indexOf(beforeTitle);
} else if(afterTitle) {
newPos = titles.indexOf(afterTitle);
if(newPos >= 0) {
++newPos;
}
}
if(newPos === -1) {
newPos = currPos;
}
if(newPos !== currPos) {
titles.splice(currPos,1);
if(newPos >= currPos) {
newPos--;
}
titles.splice(newPos,0,title);
}
}
}
return titles;
}
};
exports.getSubTiddler = function(title,subTiddlerTitle) {
var bundleInfo = this.getPluginInfo(title) || this.getTiddlerDataCached(title);
if(bundleInfo && bundleInfo.tiddlers) {
var subTiddler = bundleInfo.tiddlers[subTiddlerTitle];
if(subTiddler) {
return new $tw.Tiddler(subTiddler);
}
}
return null;
};
/*
Retrieve a tiddler as a JSON string of the fields
*/
exports.getTiddlerAsJson = function(title) {
var tiddler = this.getTiddler(title);
if(tiddler) {
var fields = Object.create(null);
$tw.utils.each(tiddler.fields,function(value,name) {
fields[name] = tiddler.getFieldString(name);
});
return JSON.stringify(fields);
} else {
return JSON.stringify({title: title});
}
};
/*
Get the content of a tiddler as a JavaScript object. How this is done depends on the type of the tiddler:
application/json: the tiddler JSON is parsed into an object
application/x-tiddler-dictionary: the tiddler is parsed as sequence of name:value pairs
Other types currently just return null.
titleOrTiddler: string tiddler title or a tiddler object
defaultData: default data to be returned if the tiddler is missing or doesn't contain data
Note that the same value is returned for repeated calls for the same tiddler data. The value is frozen to prevent modification; otherwise modifications would be visible to all callers
*/
exports.getTiddlerDataCached = function(titleOrTiddler,defaultData) {
var self = this,
tiddler = titleOrTiddler;
if(!(tiddler instanceof $tw.Tiddler)) {
tiddler = this.getTiddler(tiddler);
}
if(tiddler) {
return this.getCacheForTiddler(tiddler.fields.title,"data",function() {
// Return the frozen value
var value = self.getTiddlerData(tiddler.fields.title,defaultData);
$tw.utils.deepFreeze(value);
return value;
});
} else {
return defaultData;
}
};
/*
Alternative, uncached version of getTiddlerDataCached(). The return value can be mutated freely and reused
*/
exports.getTiddlerData = function(titleOrTiddler,defaultData) {
var tiddler = titleOrTiddler,
data;
if(!(tiddler instanceof $tw.Tiddler)) {
tiddler = this.getTiddler(tiddler);
}
if(tiddler && tiddler.fields.text) {
switch(tiddler.fields.type) {
case "application/json":
// JSON tiddler
try {
data = JSON.parse(tiddler.fields.text);
} catch(ex) {
return defaultData;
}
return data;
case "application/x-tiddler-dictionary":
return $tw.utils.parseFields(tiddler.fields.text);
}
}
return defaultData;
};
/*
Extract an indexed field from within a data tiddler
*/
exports.extractTiddlerDataItem = function(titleOrTiddler,index,defaultText) {
var data = this.getTiddlerData(titleOrTiddler,Object.create(null)),
text;
if(data && $tw.utils.hop(data,index)) {
text = data[index];
}
if(typeof text === "string" || typeof text === "number") {
return text.toString();
} else {
return defaultText;
}
};
/*
Set a tiddlers content to a JavaScript object. Currently this is done by setting the tiddler's type to "application/json" and setting the text to the JSON text of the data.
title: title of tiddler
data: object that can be serialised to JSON
fields: optional hashmap of additional tiddler fields to be set
*/
exports.setTiddlerData = function(title,data,fields) {
var existingTiddler = this.getTiddler(title),
newFields = {
title: title
};
if(existingTiddler && existingTiddler.fields.type === "application/x-tiddler-dictionary") {
newFields.text = $tw.utils.makeTiddlerDictionary(data);
} else {
newFields.type = "application/json";
newFields.text = JSON.stringify(data,null,$tw.config.preferences.jsonSpaces);
}
this.addTiddler(new $tw.Tiddler(this.getCreationFields(),existingTiddler,fields,newFields,this.getModificationFields()));
};
/*
Return the content of a tiddler as an array containing each line
*/
exports.getTiddlerList = function(title,field,index) {
if(index) {
return $tw.utils.parseStringArray(this.extractTiddlerDataItem(title,index,""));
}
field = field || "list";
var tiddler = this.getTiddler(title);
if(tiddler) {
return ($tw.utils.parseStringArray(tiddler.fields[field]) || []).slice(0);
}
return [];
};
// Return a named global cache object. Global cache objects are cleared whenever a tiddler change occurs
exports.getGlobalCache = function(cacheName,initializer) {
this.globalCache = this.globalCache || Object.create(null);
if($tw.utils.hop(this.globalCache,cacheName)) {
return this.globalCache[cacheName];
} else {
this.globalCache[cacheName] = initializer();
return this.globalCache[cacheName];
}
};
exports.clearGlobalCache = function() {
this.globalCache = Object.create(null);
};
// Return the named cache object for a tiddler. If the cache doesn't exist then the initializer function is invoked to create it
exports.getCacheForTiddler = function(title,cacheName,initializer) {
this.caches = this.caches || Object.create(null);
var caches = this.caches[title];
if(caches && caches[cacheName]) {
return caches[cacheName];
} else {
if(!caches) {
caches = Object.create(null);
this.caches[title] = caches;
}
caches[cacheName] = initializer();
return caches[cacheName];
}
};
// Clear all caches associated with a particular tiddler, or, if the title is null, clear all the caches for all the tiddlers
exports.clearCache = function(title) {
if(title) {
this.caches = this.caches || Object.create(null);
if($tw.utils.hop(this.caches,title)) {
delete this.caches[title];
}
} else {
this.caches = Object.create(null);
}
};
exports.initParsers = function(moduleType) {
// Install the parser modules
$tw.Wiki.parsers = {};
var self = this;
$tw.modules.forEachModuleOfType("parser",function(title,module) {
for(var f in module) {
if($tw.utils.hop(module,f)) {
$tw.Wiki.parsers[f] = module[f]; // Store the parser class
}
}
});
};
/*
Parse a block of text of a specified MIME type
type: content type of text to be parsed
text: text
options: see below
Options include:
parseAsInline: if true, the text of the tiddler will be parsed as an inline run
_canonical_uri: optional string of the canonical URI of this content
*/
exports.parseText = function(type,text,options) {
options = options || {};
// Select a parser
var Parser = $tw.Wiki.parsers[type];
if(!Parser && $tw.utils.getFileExtensionInfo(type)) {
Parser = $tw.Wiki.parsers[$tw.utils.getFileExtensionInfo(type).type];
}
if(!Parser) {
Parser = $tw.Wiki.parsers[options.defaultType || "text/vnd.tiddlywiki"];
}
if(!Parser) {
return null;
}
// Return the parser instance
return new Parser(type,text,{
parseAsInline: options.parseAsInline,
wiki: this,
_canonical_uri: options._canonical_uri
});
};
/*
Parse a tiddler according to its MIME type
*/
exports.parseTiddler = function(title,options) {
options = $tw.utils.extend({},options);
var cacheType = options.parseAsInline ? "inlineParseTree" : "blockParseTree",
tiddler = this.getTiddler(title),
self = this;
return tiddler ? this.getCacheForTiddler(title,cacheType,function() {
if(tiddler.hasField("_canonical_uri")) {
options._canonical_uri = tiddler.fields._canonical_uri;
}
return self.parseText(tiddler.fields.type,tiddler.fields.text,options);
}) : null;
};
exports.parseTextReference = function(title,field,index,options) {
var tiddler,text;
if(options.subTiddler) {
tiddler = this.getSubTiddler(title,options.subTiddler);
} else {
tiddler = this.getTiddler(title);
if(field === "text" || (!field && !index)) {
this.getTiddlerText(title); // Force the tiddler to be lazily loaded
return this.parseTiddler(title,options);
}
}
if(field === "text" || (!field && !index)) {
if(tiddler && tiddler.fields) {
return this.parseText(tiddler.fields.type || "text/vnd.tiddlywiki",tiddler.fields.text,options);
} else {
return null;
}
} else if(field) {
if(field === "title") {
text = title;
} else {
if(!tiddler || !tiddler.hasField(field)) {
return null;
}
text = tiddler.fields[field];
}
return this.parseText("text/vnd.tiddlywiki",text.toString(),options);
} else if(index) {
this.getTiddlerText(title); // Force the tiddler to be lazily loaded
text = this.extractTiddlerDataItem(tiddler,index,undefined);
if(text === undefined) {
return null;
}
return this.parseText("text/vnd.tiddlywiki",text,options);
}
};
/*
Make a widget tree for a parse tree
parser: parser object
options: see below
Options include:
document: optional document to use
variables: hashmap of variables to set
parentWidget: optional parent widget for the root node
*/
exports.makeWidget = function(parser,options) {
options = options || {};
var widgetNode = {
type: "widget",
children: []
},
currWidgetNode = widgetNode;
// Create set variable widgets for each variable
$tw.utils.each(options.variables,function(value,name) {
var setVariableWidget = {
type: "set",
attributes: {
name: {type: "string", value: name},
value: {type: "string", value: value}
},
children: []
};
currWidgetNode.children = [setVariableWidget];
currWidgetNode = setVariableWidget;
});
// Add in the supplied parse tree nodes
currWidgetNode.children = parser ? parser.tree : [];
// Create the widget
return new widget.widget(widgetNode,{
wiki: this,
document: options.document || $tw.fakeDocument,
parentWidget: options.parentWidget
});
};
/*
Make a widget tree for transclusion
title: target tiddler title
options: as for wiki.makeWidget() plus:
options.field: optional field to transclude (defaults to "text")
options.mode: transclusion mode "inline" or "block"
options.children: optional array of children for the transclude widget
*/
exports.makeTranscludeWidget = function(title,options) {
options = options || {};
var parseTree = {tree: [{
type: "element",
tag: "div",
children: [{
type: "transclude",
attributes: {
tiddler: {
name: "tiddler",
type: "string",
value: title}},
isBlock: !options.parseAsInline}]}
]};
if(options.field) {
parseTree.tree[0].children[0].attributes.field = {type: "string", value: options.field};
}
if(options.mode) {
parseTree.tree[0].children[0].attributes.mode = {type: "string", value: options.mode};
}
if(options.children) {
parseTree.tree[0].children[0].children = options.children;
}
return $tw.wiki.makeWidget(parseTree,options);
};
/*
Parse text in a specified format and render it into another format
outputType: content type for the output
textType: content type of the input text
text: input text
options: see below
Options include:
variables: hashmap of variables to set
parentWidget: optional parent widget for the root node
*/
exports.renderText = function(outputType,textType,text,options) {
options = options || {};
var parser = this.parseText(textType,text,options),
widgetNode = this.makeWidget(parser,options);
var container = $tw.fakeDocument.createElement("div");
widgetNode.render(container,null);
return outputType === "text/html" ? container.innerHTML : container.textContent;
};
/*
Parse text from a tiddler and render it into another format
outputType: content type for the output
title: title of the tiddler to be rendered
options: see below
Options include:
variables: hashmap of variables to set
parentWidget: optional parent widget for the root node
*/
exports.renderTiddler = function(outputType,title,options) {
options = options || {};
var parser = this.parseTiddler(title,options),
widgetNode = this.makeWidget(parser,options);
var container = $tw.fakeDocument.createElement("div");
widgetNode.render(container,null);
return outputType === "text/html" ? container.innerHTML : (outputType === "text/plain-formatted" ? container.formattedTextContent : container.textContent);
};
/*
Return an array of tiddler titles that match a search string
text: The text string to search for
options: see below
Options available:
source: an iterator function for the source tiddlers, called source(iterator), where iterator is called as iterator(tiddler,title)
exclude: An array of tiddler titles to exclude from the search
invert: If true returns tiddlers that do not contain the specified string
caseSensitive: If true forces a case sensitive search
literal: If true, searches for literal string, rather than separate search terms
field: If specified, restricts the search to the specified field
*/
exports.search = function(text,options) {
options = options || {};
var self = this,
t,
invert = !!options.invert;
// Convert the search string into a regexp for each term
var terms, searchTermsRegExps,
flags = options.caseSensitive ? "" : "i";
if(options.literal) {
if(text.length === 0) {
searchTermsRegExps = null;
} else {
searchTermsRegExps = [new RegExp("(" + $tw.utils.escapeRegExp(text) + ")",flags)];
}
} else {
terms = text.split(/ +/);
if(terms.length === 1 && terms[0] === "") {
searchTermsRegExps = null;
} else {
searchTermsRegExps = [];
for(t=0; t<terms.length; t++) {
searchTermsRegExps.push(new RegExp("(" + $tw.utils.escapeRegExp(terms[t]) + ")",flags));
}
}
}
// Function to check a given tiddler for the search term
var searchTiddler = function(title) {
if(!searchTermsRegExps) {
return true;
}
var tiddler = self.getTiddler(title);
if(!tiddler) {
tiddler = new $tw.Tiddler({title: title, text: "", type: "text/vnd.tiddlywiki"});
}
var contentTypeInfo = $tw.config.contentTypeInfo[tiddler.fields.type] || $tw.config.contentTypeInfo["text/vnd.tiddlywiki"],
match;
for(var t=0; t<searchTermsRegExps.length; t++) {
match = false;
if(options.field) {
match = searchTermsRegExps[t].test(tiddler.getFieldString(options.field));
} else {
// Search title, tags and body
if(contentTypeInfo.encoding === "utf8") {
match = match || searchTermsRegExps[t].test(tiddler.fields.text);
}
var tags = tiddler.fields.tags ? tiddler.fields.tags.join("\0") : "";
match = match || searchTermsRegExps[t].test(tags) || searchTermsRegExps[t].test(tiddler.fields.title);
}
if(!match) {
return false;
}
}
return true;
};
// Loop through all the tiddlers doing the search
var results = [],
source = options.source || this.each;
source(function(tiddler,title) {
if(searchTiddler(title) !== options.invert) {
results.push(title);
}
});
// Remove any of the results we have to exclude
if(options.exclude) {
for(t=0; t<options.exclude.length; t++) {
var p = results.indexOf(options.exclude[t]);
if(p !== -1) {
results.splice(p,1);
}
}
}
return results;
};
/*
Trigger a load for a tiddler if it is skinny. Returns the text, or undefined if the tiddler is missing, null if the tiddler is being lazily loaded.
*/
exports.getTiddlerText = function(title,defaultText) {
var tiddler = this.getTiddler(title);
// Return undefined if the tiddler isn't found
if(!tiddler) {
return defaultText;
}
if(tiddler.fields.text !== undefined) {
// Just return the text if we've got it
return tiddler.fields.text;
} else {
// Tell any listeners about the need to lazily load this tiddler
this.dispatchEvent("lazyLoad",title);
// Indicate that the text is being loaded
return null;
}
};
/*
Read an array of browser File objects, invoking callback(tiddlerFieldsArray) once they're all read
*/
exports.readFiles = function(files,callback) {
var result = [],
outstanding = files.length;
for(var f=0; f<files.length; f++) {
this.readFile(files[f],function(tiddlerFieldsArray) {
result.push.apply(result,tiddlerFieldsArray);
if(--outstanding === 0) {
callback(result);
}
});
}
return files.length;
};
/*
Read a browser File object, invoking callback(tiddlerFieldsArray) with an array of tiddler fields objects
*/
exports.readFile = function(file,callback) {
// Get the type, falling back to the filename extension
var self = this,
type = file.type;
if(type === "" || !type) {
var dotPos = file.name.lastIndexOf(".");
if(dotPos !== -1) {
var fileExtensionInfo = $tw.utils.getFileExtensionInfo(file.name.substr(dotPos));
if(fileExtensionInfo) {
type = fileExtensionInfo.type;
}
}
}
// Figure out if we're reading a binary file
var contentTypeInfo = $tw.config.contentTypeInfo[type],
isBinary = contentTypeInfo ? contentTypeInfo.encoding === "base64" : false;
// Log some debugging information
if($tw.log.IMPORT) {
console.log("Importing file '" + file.name + "', type: '" + type + "', isBinary: " + isBinary);
}
// Create the FileReader
var reader = new FileReader();
// Onload
reader.onload = function(event) {
// Deserialise the file contents
var text = event.target.result,
tiddlerFields = {title: file.name || "Untitled", type: type};
// Are we binary?
if(isBinary) {
// The base64 section starts after the first comma in the data URI
var commaPos = text.indexOf(",");
if(commaPos !== -1) {
tiddlerFields.text = text.substr(commaPos+1);
callback([tiddlerFields]);
}
} else {
// Check whether this is an encrypted TiddlyWiki file
var encryptedJson = $tw.utils.extractEncryptedStoreArea(text);
if(encryptedJson) {
// If so, attempt to decrypt it with the current password
$tw.utils.decryptStoreAreaInteractive(encryptedJson,function(tiddlers) {
callback(tiddlers);
});
} else {
// Otherwise, just try to deserialise any tiddlers in the file
callback(self.deserializeTiddlers(type,text,tiddlerFields));
}
}
};
// Kick off the read
if(isBinary) {
reader.readAsDataURL(file);
} else {
reader.readAsText(file);
}
};
/*
Find any existing draft of a specified tiddler
*/
exports.findDraft = function(targetTitle) {
var draftTitle = undefined;
this.forEachTiddler({includeSystem: true},function(title,tiddler) {
if(tiddler.fields["draft.title"] && tiddler.fields["draft.of"] === targetTitle) {
draftTitle = title;
}
});
return draftTitle;
}
/*
Check whether the specified draft tiddler has been modified
*/
exports.isDraftModified = function(title) {
var tiddler = this.getTiddler(title);
if(!tiddler.isDraft()) {
return false;
}
var ignoredFields = ["created", "modified", "title", "draft.title", "draft.of"],
origTiddler = this.getTiddler(tiddler.fields["draft.of"]);
if(!origTiddler) {
return tiddler.fields.text !== "";
}
return tiddler.fields["draft.title"] !== tiddler.fields["draft.of"] || !tiddler.isEqual(origTiddler,ignoredFields);
};
/*
Add a new record to the top of the history stack
title: a title string or an array of title strings
fromPageRect: page coordinates of the origin of the navigation
historyTitle: title of history tiddler (defaults to $:/HistoryList)
*/
exports.addToHistory = function(title,fromPageRect,historyTitle) {
var story = new $tw.Story({wiki: this, historyTitle: historyTitle});
story.addToHistory(title,fromPageRect);
};
/*
Invoke the available upgrader modules
titles: array of tiddler titles to be processed
tiddlers: hashmap by title of tiddler fields of pending import tiddlers. These can be modified by the upgraders. An entry with no fields indicates a tiddler that was pending import has been suppressed. When entries are added to the pending import the tiddlers hashmap may have entries that are not present in the titles array
Returns a hashmap of messages keyed by tiddler title.
*/
exports.invokeUpgraders = function(titles,tiddlers) {
// Collect up the available upgrader modules
var self = this;
if(!this.upgraderModules) {
this.upgraderModules = [];
$tw.modules.forEachModuleOfType("upgrader",function(title,module) {
if(module.upgrade) {
self.upgraderModules.push(module);
}
});
}
// Invoke each upgrader in turn
var messages = {};
for(var t=0; t<this.upgraderModules.length; t++) {
var upgrader = this.upgraderModules[t],
upgraderMessages = upgrader.upgrade(this,titles,tiddlers);
$tw.utils.extend(messages,upgraderMessages);
}
return messages;
};
})();
This plugin contains TiddlyWiki's core components, comprising:
* JavaScript code modules
* Icons
* Templates needed to create TiddlyWiki's user interface
* British English (''en-GB'') translations of the localisable strings used by the core
\define saveTiddlerFilter()
[is[tiddler]] -[prefix[$:/state/popup/]] -[[$:/HistoryList]] -[[$:/boot/boot.css]] -[type[application/javascript]library[yes]] -[[$:/boot/boot.js]] -[[$:/boot/bootprefix.js]] +[sort[title]] $(publishFilter)$
\end
{{$:/core/templates/tiddlywiki5.html}}
\define saveTiddlerFilter()
[is[system]] -[prefix[$:/state/popup/]] -[[$:/boot/boot.css]] -[type[application/javascript]library[yes]] -[[$:/boot/boot.js]] -[[$:/boot/bootprefix.js]] +[sort[title]]
\end
{{$:/core/templates/tiddlywiki5.html}}
\define saveTiddlerFilter()
[is[system]] -[prefix[$:/state/popup/]] -[[$:/HistoryList]] -[[$:/boot/boot.css]] -[type[application/javascript]library[yes]] -[[$:/boot/boot.js]] -[[$:/boot/bootprefix.js]] +[sort[title]]
\end
{{$:/core/templates/tiddlywiki5.html}}
\define saveTiddlerFilter()
[is[tiddler]] -[prefix[$:/state/popup/]] -[[$:/HistoryList]] -[[$:/boot/boot.css]] -[type[application/javascript]library[yes]] -[[$:/boot/boot.js]] -[[$:/boot/bootprefix.js]] -[!is[system]is[image]] +[sort[title]]
\end
{{$:/core/templates/tiddlywiki5.html}}
<!-- This template is provided for backwards compatibility with older versions of TiddlyWiki -->
<$set name="exportFilter" value="[!is[system]sort[title]]">
{{$:/core/templates/exporters/StaticRiver}}
</$set>
<!--
This template is used to assign the ''_canonical_uri'' field to external images.
Change the `./images/` part to a different base URI. The URI can be relative or absolute.
-->
./images/<$view field="title" format="doubleurlencoded"/>
<!--
This template is used to assign the ''_canonical_uri'' field to external text files.
Change the `./text/` part to a different base URI. The URI can be relative or absolute.
-->
./text/<$view field="title" format="doubleurlencoded"/>.tid
<!--
This template is used for saving CSS tiddlers as a style tag with data attributes representing the tiddler fields.
-->`<style`<$fields template=' data-tiddler-$name$="$encoded_value$"'></$fields>` type="text/css">`<$view field="text" format="text" />`</style>`
\define renderContent()
<$text text=<<csvtiddlers filter:"""$(exportFilter)$""" format:"quoted-comma-sep">>/>
\end
<<renderContent>>
\define renderContent()
<$text text=<<jsontiddlers filter:"""$(exportFilter)$""">>/>
\end
<<renderContent>>
\define tv-wikilink-template() #$uri_encoded$
\define tv-config-toolbar-icons() no
\define tv-config-toolbar-text() no
\define tv-config-toolbar-class() tc-btn-invisible
\rules only filteredtranscludeinline transcludeinline
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="generator" content="TiddlyWiki" />
<meta name="tiddlywiki-version" content="{{$:/core/templates/version}}" />
<meta name="format-detection" content="telephone=no">
<link id="faviconLink" rel="shortcut icon" href="favicon.ico">
<title>{{$:/core/wiki/title}}</title>
<div id="styleArea">
{{$:/boot/boot.css||$:/core/templates/css-tiddler}}
</div>
<style type="text/css">
{{$:/core/ui/PageStylesheet||$:/core/templates/wikified-tiddler}}
</style>
</head>
<body class="tc-body">
{{$:/StaticBanner||$:/core/templates/html-tiddler}}
<section class="tc-story-river">
{{$:/core/templates/exporters/StaticRiver/Content||$:/core/templates/html-tiddler}}
</section>
</body>
</html>
\define renderContent()
{{{ $(exportFilter)$ ||$:/core/templates/static-tiddler}}}
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<<renderContent>>
</$importvariables>
\define renderContent()
{{{ $(exportFilter)$ +[limit[1]] ||$:/core/templates/tid-tiddler}}}
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]"><<renderContent>></$importvariables>
<!--
This template is used for saving tiddlers as an HTML DIV tag with attributes representing the tiddler fields.
-->`<div`<$fields template=' $name$="$encoded_value$"'></$fields>`>
<pre>`<$view field="text" format="htmlencoded" />`</pre>
</div>`
<!--
This template is used for saving tiddlers as raw HTML
--><$view field="text" format="htmlwikified" />
<!--
This template is used for saving JavaScript tiddlers as a script tag with data attributes representing the tiddler fields.
-->`<script`<$fields template=' data-tiddler-$name$="$encoded_value$"'></$fields>` type="text/javascript">`<$view field="text" format="text" />`</script>`
<!--
This template is used for saving JavaScript tiddlers as a script tag with data attributes representing the tiddler fields. The body of the tiddler is wrapped in a call to the `$tw.modules.define` function in order to define the body of the tiddler as a module
-->`<script`<$fields template=' data-tiddler-$name$="$encoded_value$"'></$fields>` type="text/javascript" data-module="yes">$tw.modules.define("`<$view field="title" format="jsencoded" />`","`<$view field="module-type" format="jsencoded" />`",function(module,exports,require) {`<$view field="text" format="text" />`});
</script>`
\rules only filteredtranscludeinline transcludeinline entity
<!-- The following comment is called a MOTW comment and is necessary for the TiddlyIE Internet Explorer extension -->
<!-- saved from url=(0021)http://tiddlywiki.com -->
<$view field="text" format="text" />
<$set name="themeTitle" value={{$:/view}}>
<$set name="tempCurrentTiddler" value=<<currentTiddler>>>
<$set name="currentTiddler" value={{$:/language}}>
<$set name="languageTitle" value={{!!name}}>
<$set name="currentTiddler" value=<<tempCurrentTiddler>>>
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<$navigator story="$:/StoryList" history="$:/HistoryList">
<$transclude mode="block"/>
</$navigator>
</$importvariables>
</$set>
</$set>
</$set>
</$set>
</$set>
<$list filter="[!is[system]]">
tiddler: <$view field="title" format="urlencoded"/>.tid
</$list>
<a name=<<currentTiddler>>>
<$transclude tiddler="$:/core/ui/ViewTemplate"/>
</a>
<$reveal type="nomatch" state="$:/isEncrypted" text="yes">
{{$:/core/templates/static.content||$:/core/templates/html-tiddler}}
</$reveal>
<$reveal type="match" state="$:/isEncrypted" text="yes">
This file contains an encrypted ~TiddlyWiki. Enable ~JavaScript and enter the decryption password when prompted.
</$reveal>
<!-- For Google, and people without JavaScript-->
This [[TiddlyWiki|http://tiddlywiki.com]] contains the following tiddlers:
<ul>
<$list filter=<<saveTiddlerFilter>>>
<li><$view field="title" format="text"></$view></li>
</$list>
</ul>
{{$:/boot/boot.css||$:/core/templates/plain-text-tiddler}}
{{$:/core/ui/PageStylesheet||$:/core/templates/wikified-tiddler}}
\define tv-wikilink-template() static/$uri_doubleencoded$.html
\define tv-config-toolbar-icons() no
\define tv-config-toolbar-text() no
\define tv-config-toolbar-class() tc-btn-invisible
\rules only filteredtranscludeinline transcludeinline
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="generator" content="TiddlyWiki" />
<meta name="tiddlywiki-version" content="{{$:/core/templates/version}}" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="format-detection" content="telephone=no">
<link id="faviconLink" rel="shortcut icon" href="favicon.ico">
<title>{{$:/core/wiki/title}}</title>
<div id="styleArea">
{{$:/boot/boot.css||$:/core/templates/css-tiddler}}
</div>
<style type="text/css">
{{$:/core/ui/PageStylesheet||$:/core/templates/wikified-tiddler}}
</style>
</head>
<body class="tc-body">
{{$:/StaticBanner||$:/core/templates/html-tiddler}}
{{$:/core/ui/PageTemplate||$:/core/templates/html-tiddler}}
</body>
</html>
\define tv-wikilink-template() $uri_doubleencoded$.html
\define tv-config-toolbar-icons() no
\define tv-config-toolbar-text() no
\define tv-config-toolbar-class() tc-btn-invisible
`<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="generator" content="TiddlyWiki" />
<meta name="tiddlywiki-version" content="`{{$:/core/templates/version}}`" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="format-detection" content="telephone=no">
<link id="faviconLink" rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="static.css">
<title>`<$view field="caption"><$view field="title"/></$view>: {{$:/core/wiki/title}}`</title>
</head>
<body class="tc-body">
`{{$:/StaticBanner||$:/core/templates/html-tiddler}}`
<section class="tc-story-river">
`<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<$view tiddler="$:/core/ui/ViewTemplate" format="htmlwikified"/>
</$importvariables>`
</section>
</body>
</html>
`
<$reveal type="nomatch" state="$:/isEncrypted" text="yes">
`<div id="storeArea" style="display:none;">`
<$list filter=<<saveTiddlerFilter>> template="$:/core/templates/html-div-tiddler"/>
`</div>`
</$reveal>
<$reveal type="match" state="$:/isEncrypted" text="yes">
`<!--~~ Encrypted tiddlers ~~-->`
`<pre id="encryptedStoreArea" type="text/plain" style="display:none;">`
<$encrypt filter=<<saveTiddlerFilter>>/>
`</pre>`
</$reveal>
<!--
This template is used for saving tiddlers in TiddlyWeb *.tid format
--><$fields exclude='text bag' template='$name$: $value$
'></$fields>`
`<$view field="text" format="text" />
<!--
This template is used for saving tiddler metadata *.meta files
--><$fields exclude='text bag' template='$name$: $value$
'></$fields>
\rules only filteredtranscludeinline transcludeinline
<!doctype html>
{{$:/core/templates/MOTW.html}}<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- Force IE standards mode for Intranet and HTA - should be the first meta -->
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="application-name" content="TiddlyWiki" />
<meta name="generator" content="TiddlyWiki" />
<meta name="tiddlywiki-version" content="{{$:/core/templates/version}}" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="format-detection" content="telephone=no" />
<meta name="copyright" content="{{$:/core/copyright.txt}}" />
<link id="faviconLink" rel="shortcut icon" href="favicon.ico">
<title>{{$:/core/wiki/title}}</title>
<!--~~ This is a Tiddlywiki file. The points of interest in the file are marked with this pattern ~~-->
<!--~~ Raw markup ~~-->
{{{ [all[shadows+tiddlers]tag[$:/core/wiki/rawmarkup]] [all[shadows+tiddlers]tag[$:/tags/RawMarkup]] ||$:/core/templates/plain-text-tiddler}}}
</head>
<body class="tc-body">
<!--~~ Static styles ~~-->
<div id="styleArea">
{{$:/boot/boot.css||$:/core/templates/css-tiddler}}
</div>
<!--~~ Static content for Google and browsers without JavaScript ~~-->
<noscript>
<div id="splashArea">
{{$:/core/templates/static.area}}
</div>
</noscript>
<!--~~ Ordinary tiddlers ~~-->
{{$:/core/templates/store.area.template.html}}
<!--~~ Library modules ~~-->
<div id="libraryModules" style="display:none;">
{{{ [is[system]type[application/javascript]library[yes]] ||$:/core/templates/javascript-tiddler}}}
</div>
<!--~~ Boot kernel prologue ~~-->
<div id="bootKernelPrefix" style="display:none;">
{{ $:/boot/bootprefix.js ||$:/core/templates/javascript-tiddler}}
</div>
<!--~~ Boot kernel ~~-->
<div id="bootKernel" style="display:none;">
{{ $:/boot/boot.js ||$:/core/templates/javascript-tiddler}}
</div>
</body>
</html>
\define lingo-base() $:/language/AboveStory/ClassicPlugin/
<$list filter="[all[system+tiddlers]tag[systemConfig]limit[1]]">
<div class="tc-message-box">
<<lingo Warning>>
<ul>
<$list filter="[all[system+tiddlers]tag[systemConfig]limit[1]]">
<li>
<$link><$view field="title"/></$link>
</li>
</$list>
</ul>
</div>
</$list>
\define lingo-base() $:/language/Search/
<$linkcatcher to="$:/temp/advancedsearch">
<<lingo Filter/Hint>>
<div class="tc-search tc-advanced-search">
<$edit-text tiddler="$:/temp/advancedsearch" type="search" tag="input"/>
<$button popup=<<qualify "$:/state/filterDropdown">> class="tc-btn-invisible">
{{$:/core/images/down-arrow}}
</$button>
<$reveal state="$:/temp/advancedsearch" type="nomatch" text="">
<$button class="tc-btn-invisible">
<$action-setfield $tiddler="$:/temp/advancedsearch" $field="text" $value=""/>
{{$:/core/images/close-button}}
</$button>
<$macrocall $name="exportButton" exportFilter={{$:/temp/advancedsearch}} lingoBase="$:/language/Buttons/ExportTiddlers/"/>
</$reveal>
</div>
<div class="tc-block-dropdown-wrapper">
<$reveal state=<<qualify "$:/state/filterDropdown">> type="nomatch" text="" default="">
<div class="tc-block-dropdown tc-edit-type-dropdown">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/Filter]]"><$link to={{!!filter}}><$transclude field="description"/></$link>
</$list>
</div>
</$reveal>
</div>
</$linkcatcher>
<$reveal state="$:/temp/advancedsearch" type="nomatch" text="">
<$set name="resultCount" value="""<$count filter={{$:/temp/advancedsearch}}/>""">
<div class="tc-search-results">
<<lingo Filter/Matches>>
<$list filter={{$:/temp/advancedsearch}} template="$:/core/ui/ListItemTemplate"/>
</div>
</$set>
</$reveal>
\define lingo-base() $:/language/Search/
<$linkcatcher to="$:/temp/advancedsearch">
<<lingo Shadows/Hint>>
<div class="tc-search">
<$edit-text tiddler="$:/temp/advancedsearch" type="search" tag="input"/>
<$reveal state="$:/temp/advancedsearch" type="nomatch" text="">
<$button class="tc-btn-invisible">
<$action-setfield $tiddler="$:/temp/advancedsearch" $field="text" $value=""/>
{{$:/core/images/close-button}}
</$button>
</$reveal>
</div>
</$linkcatcher>
<$reveal state="$:/temp/advancedsearch" type="nomatch" text="">
<$set name="resultCount" value="""<$count filter="[all[shadows]search{$:/temp/advancedsearch}] -[[$:/temp/advancedsearch]]"/>""">
<div class="tc-search-results">
<<lingo Shadows/Matches>>
<$list filter="[all[shadows]search{$:/temp/advancedsearch}sort[title]limit[250]] -[[$:/temp/advancedsearch]]" template="$:/core/ui/ListItemTemplate"/>
</div>
</$set>
</$reveal>
<$reveal state="$:/temp/advancedsearch" type="match" text="">
</$reveal>
\define lingo-base() $:/language/Search/
<$linkcatcher to="$:/temp/advancedsearch">
<<lingo Standard/Hint>>
<div class="tc-search">
<$edit-text tiddler="$:/temp/advancedsearch" type="search" tag="input"/>
<$reveal state="$:/temp/advancedsearch" type="nomatch" text="">
<$button class="tc-btn-invisible">
<$action-setfield $tiddler="$:/temp/advancedsearch" $field="text" $value=""/>
{{$:/core/images/close-button}}
</$button>
</$reveal>
</div>
</$linkcatcher>
<$reveal state="$:/temp/advancedsearch" type="nomatch" text="">
<$set name="searchTiddler" value="$:/temp/advancedsearch">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/SearchResults]!has[draft.of]butfirst[]limit[1]]" emptyMessage="""
<$list filter="[all[shadows+tiddlers]tag[$:/tags/SearchResults]!has[draft.of]]">
<$transclude/>
</$list>
""">
<$macrocall $name="tabs" tabsList="[all[shadows+tiddlers]tag[$:/tags/SearchResults]!has[draft.of]]" default={{$:/config/SearchResults/Default}}/>
</$list>
</$set>
</$reveal>
\define lingo-base() $:/language/Search/
<$linkcatcher to="$:/temp/advancedsearch">
<<lingo System/Hint>>
<div class="tc-search">
<$edit-text tiddler="$:/temp/advancedsearch" type="search" tag="input"/>
<$reveal state="$:/temp/advancedsearch" type="nomatch" text="">
<$button class="tc-btn-invisible">
<$action-setfield $tiddler="$:/temp/advancedsearch" $field="text" $value=""/>
{{$:/core/images/close-button}}
</$button>
</$reveal>
</div>
</$linkcatcher>
<$reveal state="$:/temp/advancedsearch" type="nomatch" text="">
<$set name="resultCount" value="""<$count filter="[is[system]search{$:/temp/advancedsearch}] -[[$:/temp/advancedsearch]]"/>""">
<div class="tc-search-results">
<<lingo System/Matches>>
<$list filter="[is[system]search{$:/temp/advancedsearch}sort[title]limit[250]] -[[$:/temp/advancedsearch]]" template="$:/core/ui/ListItemTemplate"/>
</div>
</$set>
</$reveal>
<$reveal state="$:/temp/advancedsearch" type="match" text="">
</$reveal>
<div class="tc-alert">
<div class="tc-alert-toolbar">
<$button class="tc-btn-invisible"><$action-deletetiddler $tiddler=<<currentTiddler>>/>{{$:/core/images/delete-button}}</$button>
</div>
<div class="tc-alert-subtitle">
<$view field="component"/> - <$view field="modified" format="date" template="0hh:0mm:0ss DD MM YYYY"/> <$reveal type="nomatch" state="!!count" text=""><span class="tc-alert-highlight">(count: <$view field="count"/>)</span></$reveal>
</div>
<div class="tc-alert-body">
<$transclude/>
</div>
</div>
\define lingo-base() $:/language/BinaryWarning/
<div class="tc-binary-warning">
<<lingo Prompt>>
</div>
\define control-panel-button(class)
<$button to="$:/AdvancedSearch" tooltip={{$:/language/Buttons/AdvancedSearch/Hint}} aria-label={{$:/language/Buttons/AdvancedSearch/Caption}} class="""$(tv-config-toolbar-class)$ $class$""">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/advanced-search-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/AdvancedSearch/Caption}}/></span>
</$list>
</$button>
\end
<$list filter="[list[$:/StoryList]] +[field:title[$:/AdvancedSearch]]" emptyMessage=<<control-panel-button>>>
<<control-panel-button "tc-selected">>
</$list>
<$button message="tm-cancel-tiddler" tooltip={{$:/language/Buttons/Cancel/Hint}} aria-label={{$:/language/Buttons/Cancel/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/cancel-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Cancel/Caption}}/></span>
</$list>
</$button>
<$button message="tm-new-tiddler" param=<<currentTiddler>> tooltip={{$:/language/Buttons/Clone/Hint}} aria-label={{$:/language/Buttons/Clone/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/clone-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Clone/Caption}}/></span>
</$list>
</$button>
<$button message="tm-close-tiddler" tooltip={{$:/language/Buttons/Close/Hint}} aria-label={{$:/language/Buttons/Close/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/close-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Close/Caption}}/></span>
</$list>
</$button>
<$button message="tm-close-all-tiddlers" tooltip={{$:/language/Buttons/CloseAll/Hint}} aria-label={{$:/language/Buttons/CloseAll/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/close-all-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/CloseAll/Caption}}/></span>
</$list>
</$button>
<$button message="tm-close-other-tiddlers" param=<<currentTiddler>> tooltip={{$:/language/Buttons/CloseOthers/Hint}} aria-label={{$:/language/Buttons/CloseOthers/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/close-others-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/CloseOthers/Caption}}/></span>
</$list>
</$button>
\define control-panel-button(class)
<$button to="$:/ControlPanel" tooltip={{$:/language/Buttons/ControlPanel/Hint}} aria-label={{$:/language/Buttons/ControlPanel/Caption}} class="""$(tv-config-toolbar-class)$ $class$""">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/options-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/ControlPanel/Caption}}/></span>
</$list>
</$button>
\end
<$list filter="[list[$:/StoryList]] +[field:title[$:/ControlPanel]]" emptyMessage=<<control-panel-button>>>
<<control-panel-button "tc-selected">>
</$list>
<$button message="tm-delete-tiddler" tooltip={{$:/language/Buttons/Delete/Hint}} aria-label={{$:/language/Buttons/Delete/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/delete-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Delete/Caption}}/></span>
</$list>
</$button>
<$button message="tm-edit-tiddler" tooltip={{$:/language/Buttons/Edit/Hint}} aria-label={{$:/language/Buttons/Edit/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/edit-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Edit/Caption}}/></span>
</$list>
</$button>
<$reveal type="match" state="$:/isEncrypted" text="yes">
<$button message="tm-clear-password" tooltip={{$:/language/Buttons/Encryption/ClearPassword/Hint}} aria-label={{$:/language/Buttons/Encryption/ClearPassword/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/locked-padlock}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Encryption/ClearPassword/Caption}}/></span>
</$list>
</$button>
</$reveal>
<$reveal type="nomatch" state="$:/isEncrypted" text="yes">
<$button message="tm-set-password" tooltip={{$:/language/Buttons/Encryption/SetPassword/Hint}} aria-label={{$:/language/Buttons/Encryption/SetPassword/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/unlocked-padlock}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Encryption/SetPassword/Caption}}/></span>
</$list>
</$button>
</$reveal>
<$macrocall $name="exportButton" exportFilter="[!is[system]sort[title]]" lingoBase="$:/language/Buttons/ExportPage/"/>
\define makeExportFilter()
[[$(currentTiddler)$]]
\end
<$macrocall $name="exportButton" exportFilter=<<makeExportFilter>> lingoBase="$:/language/Buttons/ExportTiddler/" baseFilename=<<currentTiddler>>/>
<$reveal type="nomatch" state=<<folded-state>> text="hide" default="show"><$button tooltip={{$:/language/Buttons/Fold/Hint}} aria-label={{$:/language/Buttons/Fold/Caption}} class=<<tv-config-toolbar-class>>>
<$action-sendmessage $message="tm-fold-tiddler" $param=<<currentTiddler>> foldedState=<<folded-state>>/>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]" variable="listItem">
{{$:/core/images/fold-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text">
<$text text={{$:/language/Buttons/Fold/Caption}}/>
</span>
</$list>
</$button></$reveal><$reveal type="match" state=<<folded-state>> text="hide" default="show"><$button tooltip={{$:/language/Buttons/Unfold/Hint}} aria-label={{$:/language/Buttons/Unfold/Caption}} class=<<tv-config-toolbar-class>>>
<$action-sendmessage $message="tm-fold-tiddler" $param=<<currentTiddler>> foldedState=<<folded-state>>/>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]" variable="listItem">
{{$:/core/images/unfold-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text">
<$text text={{$:/language/Buttons/Unfold/Caption}}/>
</span>
</$list>
</$button></$reveal>
<$button tooltip={{$:/language/Buttons/FoldAll/Hint}} aria-label={{$:/language/Buttons/FoldAll/Caption}} class=<<tv-config-toolbar-class>>>
<$action-sendmessage $message="tm-fold-all-tiddlers" $param=<<currentTiddler>> foldedStatePrefix="$:/state/folded/"/>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]" variable="listItem">
{{$:/core/images/fold-all-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/FoldAll/Caption}}/></span>
</$list>
</$button>
<!-- This dummy toolbar button is here to allow visibility of the fold-bar to be controlled as if it were a toolbar button -->
<$button tooltip={{$:/language/Buttons/FoldOthers/Hint}} aria-label={{$:/language/Buttons/FoldOthers/Caption}} class=<<tv-config-toolbar-class>>>
<$action-sendmessage $message="tm-fold-other-tiddlers" $param=<<currentTiddler>> foldedStatePrefix="$:/state/folded/"/>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]" variable="listItem">
{{$:/core/images/fold-others-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/FoldOthers/Caption}}/></span>
</$list>
</$button>
<$button message="tm-full-screen" tooltip={{$:/language/Buttons/FullScreen/Hint}} aria-label={{$:/language/Buttons/FullScreen/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/full-screen-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/FullScreen/Caption}}/></span>
</$list>
</$button>
<$button message="tm-home" tooltip={{$:/language/Buttons/Home/Hint}} aria-label={{$:/language/Buttons/Home/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/home-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Home/Caption}}/></span>
</$list>
</$button>
<div class="tc-file-input-wrapper">
<$button tooltip={{$:/language/Buttons/Import/Hint}} aria-label={{$:/language/Buttons/Import/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/import-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Import/Caption}}/></span>
</$list>
</$button>
<$browse tooltip={{$:/language/Buttons/Import/Hint}}/>
</div>
<$button popup=<<tiddlerInfoState>> tooltip={{$:/language/Buttons/Info/Hint}} aria-label={{$:/language/Buttons/Info/Caption}} class=<<tv-config-toolbar-class>> selectedClass="tc-selected">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/info-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Info/Caption}}/></span>
</$list>
</$button>
\define flag-title()
$(languagePluginTitle)$/icon
\end
<span class="tc-popup-keep">
<$button popup=<<qualify "$:/state/popup/language">> tooltip={{$:/language/Buttons/Language/Hint}} aria-label={{$:/language/Buttons/Language/Caption}} class=<<tv-config-toolbar-class>> selectedClass="tc-selected">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
<span class="tc-image-button">
<$set name="languagePluginTitle" value={{$:/language}}>
<$image source=<<flag-title>>/>
</$set>
</span>
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Language/Caption}}/></span>
</$list>
</$button>
</span>
<$reveal state=<<qualify "$:/state/popup/language">> type="popup" position="below" animate="yes">
<div class="tc-drop-down tc-drop-down-language-chooser">
<$linkcatcher to="$:/language">
<$list filter="[[$:/languages/en-GB]] [plugin-type[language]sort[description]]">
<$link>
<span class="tc-drop-down-bullet">
<$reveal type="match" state="$:/language" text=<<currentTiddler>>>
•
</$reveal>
<$reveal type="nomatch" state="$:/language" text=<<currentTiddler>>>
</$reveal>
</span>
<span class="tc-image-button">
<$set name="languagePluginTitle" value=<<currentTiddler>>>
<$transclude subtiddler=<<flag-title>>>
<$list filter="[all[current]field:title[$:/languages/en-GB]]">
<$transclude tiddler="$:/languages/en-GB/icon"/>
</$list>
</$transclude>
</$set>
</span>
<$view field="description">
<$view field="name">
<$view field="title"/>
</$view>
</$view>
</$link>
</$list>
</$linkcatcher>
</div>
</$reveal>
\define config-title()
$:/config/PageControlButtons/Visibility/$(listItem)$
\end
<$button popup=<<qualify "$:/state/popup/more">> tooltip={{$:/language/Buttons/More/Hint}} aria-label={{$:/language/Buttons/More/Caption}} class=<<tv-config-toolbar-class>> selectedClass="tc-selected">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/down-arrow}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/More/Caption}}/></span>
</$list>
</$button><$reveal state=<<qualify "$:/state/popup/more">> type="popup" position="below" animate="yes">
<div class="tc-drop-down">
<$set name="tv-config-toolbar-icons" value="yes">
<$set name="tv-config-toolbar-text" value="yes">
<$set name="tv-config-toolbar-class" value="tc-btn-invisible">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/PageControls]!has[draft.of]] -[[$:/core/ui/Buttons/more-page-actions]]" variable="listItem">
<$reveal type="match" state=<<config-title>> text="hide">
<$transclude tiddler=<<listItem>> mode="inline"/>
</$reveal>
</$list>
</$set>
</$set>
</$set>
</div>
</$reveal>
\define config-title()
$:/config/ViewToolbarButtons/Visibility/$(listItem)$
\end
<$button popup=<<qualify "$:/state/popup/more">> tooltip={{$:/language/Buttons/More/Hint}} aria-label={{$:/language/Buttons/More/Caption}} class=<<tv-config-toolbar-class>> selectedClass="tc-selected">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/down-arrow}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/More/Caption}}/></span>
</$list>
</$button><$reveal state=<<qualify "$:/state/popup/more">> type="popup" position="below" animate="yes">
<div class="tc-drop-down">
<$set name="tv-config-toolbar-icons" value="yes">
<$set name="tv-config-toolbar-text" value="yes">
<$set name="tv-config-toolbar-class" value="tc-btn-invisible">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/ViewToolbar]!has[draft.of]] -[[$:/core/ui/Buttons/more-tiddler-actions]]" variable="listItem">
<$reveal type="match" state=<<config-title>> text="hide">
<$transclude tiddler=<<listItem>> mode="inline"/>
</$reveal>
</$list>
</$set>
</$set>
</$set>
</div>
</$reveal>
\define newHereButtonTags()
[[$(currentTiddler)$]]
\end
\define newHereButton()
<$button tooltip={{$:/language/Buttons/NewHere/Hint}} aria-label={{$:/language/Buttons/NewHere/Caption}} class=<<tv-config-toolbar-class>>>
<$action-sendmessage $message="tm-new-tiddler" tags=<<newHereButtonTags>>/>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/new-here-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/NewHere/Caption}}/></span>
</$list>
</$button>
\end
<<newHereButton>>
\define journalButton()
<$button tooltip={{$:/language/Buttons/NewJournal/Hint}} aria-label={{$:/language/Buttons/NewJournal/Caption}} class=<<tv-config-toolbar-class>>>
<$action-sendmessage $message="tm-new-tiddler" title=<<now "$(journalTitleTemplate)$">> tags="$(journalTags)$"/>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/new-journal-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/NewJournal/Caption}}/></span>
</$list>
</$button>
\end
<$set name="journalTitleTemplate" value={{$:/config/NewJournal/Title}}>
<$set name="journalTags" value={{$:/config/NewJournal/Tags}}>
<<journalButton>>
</$set></$set>
\define journalButtonTags()
[[$(currentTiddlerTag)$]] $(journalTags)$
\end
\define journalButton()
<$button tooltip={{$:/language/Buttons/NewJournalHere/Hint}} aria-label={{$:/language/Buttons/NewJournalHere/Caption}} class=<<tv-config-toolbar-class>>>
<$action-sendmessage $message="tm-new-tiddler" title=<<now "$(journalTitleTemplate)$">> tags=<<journalButtonTags>>/>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/new-journal-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/NewJournalHere/Caption}}/></span>
</$list>
</$button>
\end
<$set name="journalTitleTemplate" value={{$:/config/NewJournal/Title}}>
<$set name="journalTags" value={{$:/config/NewJournal/Tags}}>
<$set name="currentTiddlerTag" value=<<currentTiddler>>>
<<journalButton>>
</$set></$set></$set>
<$button message="tm-new-tiddler" tooltip={{$:/language/Buttons/NewTiddler/Hint}} aria-label={{$:/language/Buttons/NewTiddler/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/new-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/NewTiddler/Caption}}/></span>
</$list>
</$button>
<$button message="tm-open-window" tooltip={{$:/language/Buttons/OpenWindow/Hint}} aria-label={{$:/language/Buttons/OpenWindow/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/open-window}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/OpenWindow/Caption}}/></span>
</$list>
</$button>
<span class="tc-popup-keep">
<$button popup=<<qualify "$:/state/popup/palette">> tooltip={{$:/language/Buttons/Palette/Hint}} aria-label={{$:/language/Buttons/Palette/Caption}} class=<<tv-config-toolbar-class>> selectedClass="tc-selected">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/palette}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Palette/Caption}}/></span>
</$list>
</$button>
</span>
<$reveal state=<<qualify "$:/state/popup/palette">> type="popup" position="below" animate="yes">
<div class="tc-drop-down" style="font-size:0.7em;">
{{$:/snippets/paletteswitcher}}
</div>
</$reveal>
<$button message="tm-permalink" tooltip={{$:/language/Buttons/Permalink/Hint}} aria-label={{$:/language/Buttons/Permalink/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/permalink-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Permalink/Caption}}/></span>
</$list>
</$button>
<$button message="tm-permaview" tooltip={{$:/language/Buttons/Permaview/Hint}} aria-label={{$:/language/Buttons/Permaview/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/permaview-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Permaview/Caption}}/></span>
</$list>
</$button>
<$button message="tm-browser-refresh" tooltip={{$:/language/Buttons/Refresh/Hint}} aria-label={{$:/language/Buttons/Refresh/Caption}} class=<<tv-config-toolbar-class>>>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/refresh-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Refresh/Caption}}/></span>
</$list>
</$button>
<$fieldmangler>
<$button tooltip={{$:/language/Buttons/Save/Hint}} aria-label={{$:/language/Buttons/Save/Caption}} class=<<tv-config-toolbar-class>>>
<$action-sendmessage $message="tm-add-tag" $param={{$:/temp/NewTagName}}/>
<$action-deletetiddler $tiddler="$:/temp/NewTagName"/>
<$action-sendmessage $message="tm-add-field" $name={{$:/temp/newfieldname}} $value={{$:/temp/newfieldvalue}}/>
<$action-deletetiddler $tiddler="$:/temp/newfieldname"/>
<$action-deletetiddler $tiddler="$:/temp/newfieldvalue"/>
<$action-sendmessage $message="tm-save-tiddler"/>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/done-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Save/Caption}}/></span>
</$list>
</$button>
</$fieldmangler>
<$button message="tm-save-wiki" param={{$:/config/SaveWikiButton/Template}} tooltip={{$:/language/Buttons/SaveWiki/Hint}} aria-label={{$:/language/Buttons/SaveWiki/Caption}} class=<<tv-config-toolbar-class>>>
<span class="tc-dirty-indicator">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/save-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/SaveWiki/Caption}}/></span>
</$list>
</span>
</$button>
\define icon()
$:/core/images/storyview-$(storyview)$
\end
<span class="tc-popup-keep">
<$button popup=<<qualify "$:/state/popup/storyview">> tooltip={{$:/language/Buttons/StoryView/Hint}} aria-label={{$:/language/Buttons/StoryView/Caption}} class=<<tv-config-toolbar-class>> selectedClass="tc-selected">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
<$set name="storyview" value={{$:/view}}>
<$transclude tiddler=<<icon>>/>
</$set>
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/StoryView/Caption}}/></span>
</$list>
</$button>
</span>
<$reveal state=<<qualify "$:/state/popup/storyview">> type="popup" position="below" animate="yes">
<div class="tc-drop-down">
<$linkcatcher to="$:/view">
<$list filter="[storyviews[]]" variable="storyview">
<$link to=<<storyview>>>
<span class="tc-drop-down-bullet">
<$reveal type="match" state="$:/view" text=<<storyview>>>
•
</$reveal>
<$reveal type="nomatch" state="$:/view" text=<<storyview>>>
</$reveal>
</span>
<$transclude tiddler=<<icon>>/>
<$text text=<<storyview>>/></$link>
</$list>
</$linkcatcher>
</div>
</$reveal>
\define control-panel-button(class)
<$button to="$:/TagManager" tooltip={{$:/language/Buttons/TagManager/Hint}} aria-label={{$:/language/Buttons/TagManager/Caption}} class="""$(tv-config-toolbar-class)$ $class$""">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/tag-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/TagManager/Caption}}/></span>
</$list>
</$button>
\end
<$list filter="[list[$:/StoryList]] +[field:title[$:/TagManager]]" emptyMessage=<<control-panel-button>>>
<<control-panel-button "tc-selected">>
</$list>
<span class="tc-popup-keep">
<$button popup=<<qualify "$:/state/popup/theme">> tooltip={{$:/language/Buttons/Theme/Hint}} aria-label={{$:/language/Buttons/Theme/Caption}} class=<<tv-config-toolbar-class>> selectedClass="tc-selected">
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]">
{{$:/core/images/theme-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/Theme/Caption}}/></span>
</$list>
</$button>
</span>
<$reveal state=<<qualify "$:/state/popup/theme">> type="popup" position="below" animate="yes">
<div class="tc-drop-down">
<$linkcatcher to="$:/theme">
<$list filter="[plugin-type[theme]sort[title]]" variable="themeTitle">
<$link to=<<themeTitle>>>
<span class="tc-drop-down-bullet">
<$reveal type="match" state="$:/theme" text=<<themeTitle>>>
•
</$reveal>
<$reveal type="nomatch" state="$:/theme" text=<<themeTitle>>>
</$reveal>
</span>
<$view tiddler=<<themeTitle>> field="name"/>
</$link>
</$list>
</$linkcatcher>
</div>
</$reveal>
<$button tooltip={{$:/language/Buttons/UnfoldAll/Hint}} aria-label={{$:/language/Buttons/UnfoldAll/Caption}} class=<<tv-config-toolbar-class>>>
<$action-sendmessage $message="tm-unfold-all-tiddlers" $param=<<currentTiddler>> foldedStatePrefix="$:/state/folded/"/>
<$list filter="[<tv-config-toolbar-icons>prefix[yes]]" variable="listItem">
{{$:/core/images/unfold-all-button}}
</$list>
<$list filter="[<tv-config-toolbar-text>prefix[yes]]">
<span class="tc-btn-text"><$text text={{$:/language/Buttons/UnfoldAll/Caption}}/></span>
</$list>
</$button>
<$link>
<$set name="backgroundColor" value={{!!color}}>
<span style=<<tag-styles>> class="tc-tag-label">
<$view field="title" format="text"/>
</span>
</$set>
</$link>
{{$:/language/ControlPanel/Advanced/Hint}}
<div class="tc-control-panel">
<<tabs "[all[shadows+tiddlers]tag[$:/tags/ControlPanel/Advanced]!has[draft.of]]" "$:/core/ui/ControlPanel/TiddlerFields">>
</div>
{{$:/language/ControlPanel/Appearance/Hint}}
<div class="tc-control-panel">
<<tabs "[all[shadows+tiddlers]tag[$:/tags/ControlPanel/Appearance]!has[draft.of]]" "$:/core/ui/ControlPanel/Theme">>
</div>
\define lingo-base() $:/language/ControlPanel/Basics/
\define show-filter-count(filter)
<$button class="tc-btn-invisible">
<$action-setfield $tiddler="$:/temp/advancedsearch" $value="""$filter$"""/>
<$action-setfield $tiddler="$:/state/tab--1498284803" $value="$:/core/ui/AdvancedSearch/Filter"/>
<$action-navigate $to="$:/AdvancedSearch"/>
''<$count filter="""$filter$"""/>''
{{$:/core/images/advanced-search-button}}
</$button>
\end
|<<lingo Version/Prompt>> |''<<version>>'' |
|<$link to="$:/SiteTitle"><<lingo Title/Prompt>></$link> |<$edit-text tiddler="$:/SiteTitle" default="" tag="input"/> |
|<$link to="$:/SiteSubtitle"><<lingo Subtitle/Prompt>></$link> |<$edit-text tiddler="$:/SiteSubtitle" default="" tag="input"/> |
|<$link to="$:/status/UserName"><<lingo Username/Prompt>></$link> |<$edit-text tiddler="$:/status/UserName" default="" tag="input"/> |
|<$link to="$:/config/AnimationDuration"><<lingo AnimDuration/Prompt>></$link> |<$edit-text tiddler="$:/config/AnimationDuration" default="" tag="input"/> |
|<$link to="$:/DefaultTiddlers"><<lingo DefaultTiddlers/Prompt>></$link> |<<lingo DefaultTiddlers/TopHint>><br> <$edit-text tag="textarea" tiddler="$:/DefaultTiddlers"/><br>//<<lingo DefaultTiddlers/BottomHint>>// |
|<$link to="$:/config/NewJournal/Title"><<lingo NewJournal/Title/Prompt>></$link> |<$edit-text tiddler="$:/config/NewJournal/Title" default="" tag="input"/> |
|<$link to="$:/config/NewJournal/Tags"><<lingo NewJournal/Tags/Prompt>></$link> |<$edit-text tiddler="$:/config/NewJournal/Tags" default="" tag="input"/> |
|<<lingo Language/Prompt>> |{{$:/snippets/minilanguageswitcher}} |
|<<lingo Tiddlers/Prompt>> |<<show-filter-count "[!is[system]sort[title]]">> |
|<<lingo Tags/Prompt>> |<<show-filter-count "[tags[]sort[title]]">> |
|<<lingo SystemTiddlers/Prompt>> |<<show-filter-count "[is[system]sort[title]]">> |
|<<lingo ShadowTiddlers/Prompt>> |<<show-filter-count "[all[shadows]sort[title]]">> |
|<<lingo OverriddenShadowTiddlers/Prompt>> |<<show-filter-count "[is[tiddler]is[shadow]sort[title]]">> |
\define lingo-base() $:/language/ControlPanel/EditorTypes/
<<lingo Hint>>
<table>
<tbody>
<tr>
<th><<lingo Type/Caption>></th>
<th><<lingo Editor/Caption>></th>
</tr>
<$list filter="[all[shadows+tiddlers]prefix[$:/config/EditorTypeMappings/]sort[title]]">
<tr>
<td>
<$link>
<$list filter="[all[current]removeprefix[$:/config/EditorTypeMappings/]]">
<$text text={{!!title}}/>
</$list>
</$link>
</td>
<td>
<$view field="text"/>
</td>
</tr>
</$list>
</tbody>
</table>
{{$:/language/ControlPanel/Info/Hint}}
<div class="tc-control-panel">
<<tabs "[all[shadows+tiddlers]tag[$:/tags/ControlPanel/Info]!has[draft.of]]" "$:/core/ui/ControlPanel/Basics">>
</div>
\define lingo-base() $:/language/ControlPanel/
<<lingo LoadedModules/Hint>>
{{$:/snippets/modules}}
\define lingo-base() $:/language/ControlPanel/Plugins/
\define install-plugin-button()
<$button>
<$action-sendmessage $message="tm-load-plugin-from-library" url={{!!url}} title={{$(assetInfo)$!!original-title}}/>
<$list filter="[<assetInfo>get[original-title]get[version]]" variable="installedVersion" emptyMessage="""{{$:/language/ControlPanel/Plugins/Install}}""">
{{$:/language/ControlPanel/Plugins/Reinstall}}
</$list>
</$button>
\end
\define popup-state-macro()
$:/state/add-plugin-info/$(connectionTiddler)$/$(assetInfo)$
\end
\define display-plugin-info(type)
<$set name="popup-state" value=<<popup-state-macro>>>
<div class="tc-plugin-info">
<div class="tc-plugin-info-chunk tc-small-icon">
<$reveal type="nomatch" state=<<popup-state>> text="yes">
<$button class="tc-btn-invisible tc-btn-dropdown" set=<<popup-state>> setTo="yes">
{{$:/core/images/right-arrow}}
</$button>
</$reveal>
<$reveal type="match" state=<<popup-state>> text="yes">
<$button class="tc-btn-invisible tc-btn-dropdown" set=<<popup-state>> setTo="no">
{{$:/core/images/down-arrow}}
</$button>
</$reveal>
</div>
<div class="tc-plugin-info-chunk">
<$list filter="[<assetInfo>has[icon]]" emptyMessage="""<$transclude tiddler="$:/core/images/plugin-generic-$type$"/>""">
<img src={{$(assetInfo)$!!icon}}/>
</$list>
</div>
<div class="tc-plugin-info-chunk">
<h1><$view tiddler=<<assetInfo>> field="description"/></h1>
<h2><$view tiddler=<<assetInfo>> field="original-title"/></h2>
<div><em><$view tiddler=<<assetInfo>> field="version"/></em></div>
</div>
<div class="tc-plugin-info-chunk">
<<install-plugin-button>>
</div>
</div>
<$reveal type="match" text="yes" state=<<popup-state>>>
<div class="tc-plugin-info-dropdown">
<div class="tc-plugin-info-dropdown-message">
<$list filter="[<assetInfo>get[original-title]get[version]]" variable="installedVersion" emptyMessage="""This plugin is not currently installed""">
<em>
This plugin is already installed at version <$text text=<<installedVersion>>/>
</em>
</$list>
</div>
<div class="tc-plugin-info-dropdown-body">
<$transclude tiddler=<<assetInfo>> field="readme" mode="block"/>
</div>
</div>
</$reveal>
</$set>
\end
\define load-plugin-library-button()
<$button class="tc-btn-big-green">
<$action-sendmessage $message="tm-load-plugin-library" url={{!!url}} infoTitlePrefix="$:/temp/RemoteAssetInfo/"/>
{{$:/core/images/chevron-right}} {{$:/language/ControlPanel/Plugins/OpenPluginLibrary}}
</$button>
\end
\define display-server-assets(type)
{{$:/language/Search/Search}}: <$edit-text tiddler="""$:/temp/RemoteAssetSearch/$(currentTiddler)$""" default="" type="search" tag="input"/>
<$reveal state="""$:/temp/RemoteAssetSearch/$(currentTiddler)$""" type="nomatch" text="">
<$button class="tc-btn-invisible">
<$action-setfield $tiddler="""$:/temp/RemoteAssetSearch/$(currentTiddler)$""" $field="text" $value=""/>
{{$:/core/images/close-button}}
</$button>
</$reveal>
<div class="tc-plugin-library-listing">
<$list filter="[all[tiddlers+shadows]tag[$:/tags/RemoteAssetInfo]server-url{!!url}original-plugin-type[$type$]search{$:/temp/RemoteAssetSearch/$(currentTiddler)$}sort[description]]" variable="assetInfo">
<<display-plugin-info "$type$">>
</$list>
</div>
\end
\define display-server-connection()
<$list filter="[all[tiddlers+shadows]tag[$:/tags/ServerConnection]suffix{!!url}]" variable="connectionTiddler" emptyMessage=<<load-plugin-library-button>>>
<<tabs "[[$:/core/ui/ControlPanel/Plugins/Add/Plugins]] [[$:/core/ui/ControlPanel/Plugins/Add/Themes]] [[$:/core/ui/ControlPanel/Plugins/Add/Languages]]" "$:/core/ui/ControlPanel/Plugins/Add/Plugins">>
</$list>
\end
\define plugin-library-listing()
<$list filter="[all[tiddlers+shadows]tag[$:/tags/PluginLibrary]]">
<div class="tc-plugin-library">
!! <$link><$transclude field="caption"><$view field="title"/></$transclude></$link>
//<$view field="url"/>//
<$transclude/>
<<display-server-connection>>
</div>
</$list>
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<div>
<<plugin-library-listing>>
</div>
</$importvariables>
\define lingo-base() $:/language/ControlPanel/Palette/
{{$:/snippets/paletteswitcher}}
<$reveal type="nomatch" state="$:/state/ShowPaletteEditor" text="yes">
<$button set="$:/state/ShowPaletteEditor" setTo="yes"><<lingo ShowEditor/Caption>></$button>
</$reveal>
<$reveal type="match" state="$:/state/ShowPaletteEditor" text="yes">
<$button set="$:/state/ShowPaletteEditor" setTo="no"><<lingo HideEditor/Caption>></$button>
{{$:/snippets/paletteeditor}}
</$reveal>
\define lingo-base() $:/language/ControlPanel/Parsing/
\define parsing-inner(typeCap)
<li>
<$checkbox tiddler="""$:/config/WikiParserRules/$typeCap$/$(currentTiddler)$""" field="text" checked="enable" unchecked="disable" default="enable"> ''<$text text=<<currentTiddler>>/>'': </$checkbox>
</li>
\end
\define parsing-outer(typeLower,typeCap)
<ul>
<$list filter="[wikiparserrules[$typeLower$]]">
<<parsing-inner typeCap:"$typeCap$">>
</$list>
</ul>
\end
<<lingo Hint>>
! <<lingo Pragma/Caption>>
<<parsing-outer typeLower:"pragma" typeCap:"Pragma">>
! <<lingo Inline/Caption>>
<<parsing-outer typeLower:"inline" typeCap:"Inline">>
! <<lingo Block/Caption>>
<<parsing-outer typeLower:"block" typeCap:"Block">>
\define lingo-base() $:/language/ControlPanel/Plugins/
\define popup-state-macro()
$(qualified-state)$-$(currentTiddler)$
\end
\define tabs-state-macro()
$(popup-state)$-$(pluginInfoType)$
\end
\define plugin-icon-title()
$(currentTiddler)$/icon
\end
\define plugin-disable-title()
$:/config/Plugins/Disabled/$(currentTiddler)$
\end
\define plugin-table-body(type,disabledMessage)
<div class="tc-plugin-info-chunk tc-small-icon">
<$reveal type="nomatch" state=<<popup-state>> text="yes">
<$button class="tc-btn-invisible tc-btn-dropdown" set=<<popup-state>> setTo="yes">
{{$:/core/images/right-arrow}}
</$button>
</$reveal>
<$reveal type="match" state=<<popup-state>> text="yes">
<$button class="tc-btn-invisible tc-btn-dropdown" set=<<popup-state>> setTo="no">
{{$:/core/images/down-arrow}}
</$button>
</$reveal>
</div>
<div class="tc-plugin-info-chunk">
<$transclude tiddler=<<currentTiddler>> subtiddler=<<plugin-icon-title>>>
<$transclude tiddler="$:/core/images/plugin-generic-$type$"/>
</$transclude>
</div>
<div class="tc-plugin-info-chunk">
<h1>
''<$view field="description"><$view field="title"/></$view>'' $disabledMessage$
</h1>
<h2>
<$view field="title"/>
</h2>
<h2>
<div><em><$view field="version"/></em></div>
</h2>
</div>
\end
\define plugin-table(type)
<$set name="qualified-state" value=<<qualify "$:/state/plugin-info">>>
<$list filter="[!has[draft.of]plugin-type[$type$]sort[description]]" emptyMessage=<<lingo "Empty/Hint">>>
<$set name="popup-state" value=<<popup-state-macro>>>
<$reveal type="nomatch" state=<<plugin-disable-title>> text="yes">
<$link to={{!!title}} class="tc-plugin-info">
<<plugin-table-body type:"$type$">>
</$link>
</$reveal>
<$reveal type="match" state=<<plugin-disable-title>> text="yes">
<$link to={{!!title}} class="tc-plugin-info tc-plugin-info-disabled">
<<plugin-table-body type:"$type$" disabledMessage:"<$macrocall $name='lingo' title='Disabled/Status'/>">>
</$link>
</$reveal>
<$reveal type="match" text="yes" state=<<popup-state>>>
<div class="tc-plugin-info-dropdown">
<div class="tc-plugin-info-dropdown-body">
<$list filter="[all[current]] -[[$:/core]]">
<div style="float:right;">
<$reveal type="nomatch" state=<<plugin-disable-title>> text="yes">
<$button set=<<plugin-disable-title>> setTo="yes" tooltip={{$:/language/ControlPanel/Plugins/Disable/Hint}} aria-label={{$:/language/ControlPanel/Plugins/Disable/Caption}}>
<<lingo Disable/Caption>>
</$button>
</$reveal>
<$reveal type="match" state=<<plugin-disable-title>> text="yes">
<$button set=<<plugin-disable-title>> setTo="no" tooltip={{$:/language/ControlPanel/Plugins/Enable/Hint}} aria-label={{$:/language/ControlPanel/Plugins/Enable/Caption}}>
<<lingo Enable/Caption>>
</$button>
</$reveal>
</div>
</$list>
<$reveal type="nomatch" text="" state="!!list">
<$macrocall $name="tabs" state=<<tabs-state-macro>> tabsList={{!!list}} default="readme" template="$:/core/ui/PluginInfo"/>
</$reveal>
<$reveal type="match" text="" state="!!list">
No information provided
</$reveal>
</div>
</div>
</$reveal>
</$set>
</$list>
</$set>
\end
{{$:/core/ui/ControlPanel/Plugins/AddPlugins}}
<<lingo Installed/Hint>>
<<tabs "[[$:/core/ui/ControlPanel/Plugins/Installed/Plugins]] [[$:/core/ui/ControlPanel/Plugins/Installed/Themes]] [[$:/core/ui/ControlPanel/Plugins/Installed/Languages]]" "$:/core/ui/ControlPanel/Plugins/Installed/Plugins">>
<<display-server-assets language>>
<<display-server-assets plugin>>
<<display-server-assets theme>>
\define lingo-base() $:/language/ControlPanel/Plugins/
<$button message="tm-modal" param="$:/core/ui/ControlPanel/Modals/AddPlugins" tooltip={{$:/language/ControlPanel/Plugins/Add/Hint}} class="tc-btn-big-green" style="background:blue;">
{{$:/core/images/download-button}} <<lingo Add/Caption>>
</$button>
<<plugin-table language>>
\define lingo-base() $:/language/ControlPanel/Saving/
\define backupURL()
http://$(userName)$.tiddlyspot.com/backup/
\end
\define backupLink()
<$reveal type="nomatch" state="$:/UploadName" text="">
<$set name="userName" value={{$:/UploadName}}>
<$reveal type="match" state="$:/UploadURL" text="">
<<backupURL>>
</$reveal>
<$reveal type="nomatch" state="$:/UploadURL" text="">
<$macrocall $name=resolvePath source={{$:/UploadBackupDir}} root={{$:/UploadURL}}>>
</$reveal>
</$set>
</$reveal>
\end
! <<lingo TiddlySpot/Heading>>
<<lingo TiddlySpot/Description>>
|<<lingo TiddlySpot/UserName>> |<$edit-text tiddler="$:/UploadName" default="" tag="input"/> |
|<<lingo TiddlySpot/Password>> |<$password name="upload"/> |
|<<lingo TiddlySpot/Backups>> |<<backupLink>> |
''<<lingo TiddlySpot/Advanced/Heading>>''
|<<lingo TiddlySpot/ServerURL>> |<$edit-text tiddler="$:/UploadURL" default="" tag="input"/> |
|<<lingo TiddlySpot/Filename>> |<$edit-text tiddler="$:/UploadFilename" default="index.html" tag="input"/> |
|<<lingo TiddlySpot/UploadDir>> |<$edit-text tiddler="$:/UploadDir" default="." tag="input"/> |
|<<lingo TiddlySpot/BackupDir>> |<$edit-text tiddler="$:/UploadBackupDir" default="." tag="input"/> |
<<lingo TiddlySpot/Hint>>
\define lingo-base() $:/language/ControlPanel/Settings/
<<lingo Hint>>
<$list filter="[all[shadows+tiddlers]tag[$:/tags/ControlPanel/Settings]]">
<div style="border-top:1px solid #eee;">
!! <$link><$transclude field="caption"/></$link>
<$transclude/>
</div>
</$list>
\define lingo-base() $:/language/ControlPanel/Settings/AutoSave/
<$link to="$:/config/AutoSave"><<lingo Hint>></$link>
<$radio tiddler="$:/config/AutoSave" value="yes"> <<lingo Enabled/Description>> </$radio>
<$radio tiddler="$:/config/AutoSave" value="no"> <<lingo Disabled/Description>> </$radio>
\define lingo-base() $:/language/ControlPanel/Settings/CamelCase/
<<lingo Hint>>
<$checkbox tiddler="$:/config/WikiParserRules/Inline/wikilink" field="text" checked="enable" unchecked="disable" default="enable"> <$link to="$:/config/WikiParserRules/Inline/wikilink"><<lingo Description>></$link> </$checkbox>
\define lingo-base() $:/language/ControlPanel/Settings/DefaultSidebarTab/
<$link to="$:/config/DefaultSidebarTab"><<lingo Hint>></$link>
<$select tiddler="$:/config/DefaultSidebarTab">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/SideBar]!has[draft.of]]">
<option value=<<currentTiddler>>><$transclude field="caption"><$text text=<<currentTiddler>>/></$transclude></option>
</$list>
</$select>
\define lingo-base() $:/language/ControlPanel/Settings/LinkToBehaviour/
<$link to="$:/config/Navigation/openLinkFromInsideRiver"><<lingo "InsideRiver/Hint">></$link>
<$select tiddler="$:/config/Navigation/openLinkFromInsideRiver">
<option value="above"><<lingo "OpenAbove">></option>
<option value="below"><<lingo "OpenBelow">></option>
<option value="top"><<lingo "OpenAtTop">></option>
<option value="bottom"><<lingo "OpenAtBottom">></option>
</$select>
<$link to="$:/config/Navigation/openLinkFromOutsideRiver"><<lingo "OutsideRiver/Hint">></$link>
<$select tiddler="$:/config/Navigation/openLinkFromOutsideRiver">
<option value="top"><<lingo "OpenAtTop">></option>
<option value="bottom"><<lingo "OpenAtBottom">></option>
</$select>
\define lingo-base() $:/language/ControlPanel/Settings/NavigationAddressBar/
<$link to="$:/config/Navigation/UpdateAddressBar"><<lingo Hint>></$link>
<$radio tiddler="$:/config/Navigation/UpdateAddressBar" value="permaview"> <<lingo Permaview/Description>> </$radio>
<$radio tiddler="$:/config/Navigation/UpdateAddressBar" value="permalink"> <<lingo Permalink/Description>> </$radio>
<$radio tiddler="$:/config/Navigation/UpdateAddressBar" value="no"> <<lingo No/Description>> </$radio>
\define lingo-base() $:/language/ControlPanel/Settings/NavigationHistory/
<$link to="$:/config/Navigation/UpdateHistory"><<lingo Hint>></$link>
<$radio tiddler="$:/config/Navigation/UpdateHistory" value="yes"> <<lingo Yes/Description>> </$radio>
<$radio tiddler="$:/config/Navigation/UpdateHistory" value="no"> <<lingo No/Description>> </$radio>
\define lingo-base() $:/language/ControlPanel/Settings/PerformanceInstrumentation/
<<lingo Hint>>
<$checkbox tiddler="$:/config/Performance/Instrumentation" field="text" checked="yes" unchecked="no" default="no"> <$link to="$:/config/Performance/Instrumentation"><<lingo Description>></$link> </$checkbox>
\define lingo-base() $:/language/ControlPanel/Settings/TitleLinks/
<$link to="$:/config/Tiddlers/TitleLinks"><<lingo Hint>></$link>
<$radio tiddler="$:/config/Tiddlers/TitleLinks" value="yes"> <<lingo Yes/Description>> </$radio>
<$radio tiddler="$:/config/Tiddlers/TitleLinks" value="no"> <<lingo No/Description>> </$radio>
\define lingo-base() $:/language/ControlPanel/Settings/ToolbarButtons/
<<lingo Hint>>
<$checkbox tiddler="$:/config/Toolbar/Icons" field="text" checked="yes" unchecked="no" default="yes"> <$link to="$:/config/Toolbar/Icons"><<lingo Icons/Description>></$link> </$checkbox>
<$checkbox tiddler="$:/config/Toolbar/Text" field="text" checked="yes" unchecked="no" default="no"> <$link to="$:/config/Toolbar/Text"><<lingo Text/Description>></$link> </$checkbox>
\define lingo-base() $:/language/ControlPanel/Settings/ToolbarButtonStyle/
<$link to="$:/config/Toolbar/ButtonClass"><<lingo "Hint">></$link>
<$select tiddler="$:/config/Toolbar/ButtonClass">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/ToolbarButtonStyle]]">
<option value={{!!text}}>{{!!caption}}</option>
</$list>
</$select>
{{$:/snippets/viewswitcher}}
{{$:/snippets/themeswitcher}}
\define lingo-base() $:/language/ControlPanel/
<<lingo TiddlerFields/Hint>>
{{$:/snippets/allfields}}
{{$:/language/ControlPanel/Toolbars/Hint}}
<div class="tc-control-panel">
<<tabs "[all[shadows+tiddlers]tag[$:/tags/ControlPanel/Toolbars]!has[draft.of]]" "$:/core/ui/ControlPanel/Toolbars/ViewToolbar" "$:/state/tabs/controlpanel/toolbars" "tc-vertical">>
</div>
\define lingo-base() $:/language/TiddlerInfo/
\define config-title()
$:/config/EditToolbarButtons/Visibility/$(listItem)$
\end
{{$:/language/ControlPanel/Toolbars/EditToolbar/Hint}}
<$set name="tv-config-toolbar-icons" value="yes">
<$set name="tv-config-toolbar-text" value="yes">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/EditToolbar]!has[draft.of]]" variable="listItem">
<$checkbox tiddler=<<config-title>> field="text" checked="show" unchecked="hide" default="show"/> <$transclude tiddler=<<listItem>> field="caption"/> <i class="tc-muted">-- <$transclude tiddler=<<listItem>> field="description"/></i>
</$list>
</$set>
</$set>
\define lingo-base() $:/language/TiddlerInfo/
\define config-title()
$:/config/PageControlButtons/Visibility/$(listItem)$
\end
{{$:/language/ControlPanel/Toolbars/PageControls/Hint}}
<$set name="tv-config-toolbar-icons" value="yes">
<$set name="tv-config-toolbar-text" value="yes">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/PageControls]!has[draft.of]]" variable="listItem">
<$checkbox tiddler=<<config-title>> field="text" checked="show" unchecked="hide" default="show"/> <$transclude tiddler=<<listItem>> field="caption"/> <i class="tc-muted">-- <$transclude tiddler=<<listItem>> field="description"/></i>
</$list>
</$set>
</$set>
\define lingo-base() $:/language/TiddlerInfo/
\define config-title()
$:/config/ViewToolbarButtons/Visibility/$(listItem)$
\end
{{$:/language/ControlPanel/Toolbars/ViewToolbar/Hint}}
<$set name="tv-config-toolbar-icons" value="yes">
<$set name="tv-config-toolbar-text" value="yes">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/ViewToolbar]!has[draft.of]]" variable="listItem">
<$checkbox tiddler=<<config-title>> field="text" checked="show" unchecked="hide" default="show"/> <$transclude tiddler=<<listItem>> field="caption"/> <i class="tc-muted">-- <$transclude tiddler=<<listItem>> field="description"/></i>
</$list>
</$set>
</$set>
\define searchResultList()
//<small>{{$:/language/Search/Matches/Title}}</small>//
<$list filter="[!is[system]search:title{$(searchTiddler)$}sort[title]limit[250]]" template="$:/core/ui/ListItemTemplate"/>
//<small>{{$:/language/Search/Matches/All}}</small>//
<$list filter="[!is[system]search{$(searchTiddler)$}sort[title]limit[250]]" template="$:/core/ui/ListItemTemplate"/>
\end
<<searchResultList>>
\define frame-classes()
tc-tiddler-frame tc-tiddler-edit-frame $(missingTiddlerClass)$ $(shadowTiddlerClass)$ $(systemTiddlerClass)$
\end
<div class=<<frame-classes>>>
<$set name="storyTiddler" value=<<currentTiddler>>>
<$keyboard key={{$:/config/shortcuts/cancel-edit-tiddler}} message="tm-cancel-tiddler">
<$keyboard key={{$:/config/shortcuts/save-tiddler}} message="tm-save-tiddler">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/EditTemplate]!has[draft.of]]" variable="listItem">
<$transclude tiddler=<<listItem>>/>
</$list>
</$keyboard>
</$keyboard>
</$set>
</div>
\define lingo-base() $:/language/EditTemplate/Body/
<$list filter="[is[current]has[_canonical_uri]]">
<div class="tc-message-box">
<<lingo External/Hint>>
<a href={{!!_canonical_uri}}><$text text={{!!_canonical_uri}}/></a>
<$edit-text field="_canonical_uri" class="tc-edit-fields"></$edit-text>
</div>
</$list>
<$list filter="[is[current]!has[_canonical_uri]]">
<$reveal state="$:/state/showeditpreview" type="match" text="yes">
<em class="tc-edit"><<lingo Hint>></em> <$button type="set" set="$:/state/showeditpreview" setTo="no"><<lingo Preview/Button/Hide>></$button>
<div class="tc-tiddler-preview">
<div class="tc-tiddler-preview-preview">
<$set name="tv-tiddler-preview" value="yes">
<$transclude />
</$set>
</div>
<div class="tc-tiddler-preview-edit">
<$edit field="text" class="tc-edit-texteditor" placeholder={{$:/language/EditTemplate/Body/Placeholder}}/>
</div>
</div>
</$reveal>
<$reveal state="$:/state/showeditpreview" type="nomatch" text="yes">
<em class="tc-edit"><<lingo Hint>></em> <$button type="set" set="$:/state/showeditpreview" setTo="yes"><<lingo Preview/Button/Show>></$button>
<$edit field="text" class="tc-edit-texteditor" placeholder={{$:/language/EditTemplate/Body/Placeholder}}/>
</$reveal>
</$list>
\define config-title()
$:/config/EditToolbarButtons/Visibility/$(listItem)$
\end
<div class="tc-tiddler-title tc-tiddler-edit-title">
<$view field="title"/>
<span class="tc-tiddler-controls tc-titlebar"><$list filter="[all[shadows+tiddlers]tag[$:/tags/EditToolbar]!has[draft.of]]" variable="listItem"><$reveal type="nomatch" state=<<config-title>> text="hide"><$transclude tiddler=<<listItem>>/></$reveal></$list></span>
<div style="clear: both;"></div>
</div>
\define lingo-base() $:/language/EditTemplate/
\define config-title()
$:/config/EditTemplateFields/Visibility/$(currentField)$
\end
\define config-filter()
[[hide]] -[title{$(config-title)$}]
\end
\define new-field-inner()
<$reveal type="nomatch" text="" default=<<name>>>
<$button>
<$action-sendmessage $message="tm-add-field" $name=<<name>> $value=<<value>>/>
<$action-deletetiddler $tiddler="$:/temp/newfieldname"/>
<$action-deletetiddler $tiddler="$:/temp/newfieldvalue"/>
<<lingo Fields/Add/Button>>
</$button>
</$reveal>
<$reveal type="match" text="" default=<<name>>>
<$button>
<<lingo Fields/Add/Button>>
</$button>
</$reveal>
\end
\define new-field()
<$set name="name" value={{$:/temp/newfieldname}}>
<$set name="value" value={{$:/temp/newfieldvalue}}>
<<new-field-inner>>
</$set>
</$set>
\end
<div class="tc-edit-fields">
<table class="tc-edit-fields">
<tbody>
<$list filter="[all[current]fields[]] +[sort[title]]" variable="currentField">
<$list filter=<<config-filter>> variable="temp">
<tr class="tc-edit-field">
<td class="tc-edit-field-name">
<$text text=<<currentField>>/>:</td>
<td class="tc-edit-field-value">
<$edit-text tiddler=<<currentTiddler>> field=<<currentField>> placeholder={{$:/language/EditTemplate/Fields/Add/Value/Placeholder}}/>
</td>
<td class="tc-edit-field-remove">
<$button class="tc-btn-invisible" tooltip={{$:/language/EditTemplate/Field/Remove/Hint}} aria-label={{$:/language/EditTemplate/Field/Remove/Caption}}>
<$action-deletefield $field=<<currentField>>/>
{{$:/core/images/delete-button}}
</$button>
</td>
</tr>
</$list>
</$list>
</tbody>
</table>
</div>
<$fieldmangler>
<div class="tc-edit-field-add">
<em class="tc-edit">
<<lingo Fields/Add/Prompt>>
</em>
<span class="tc-edit-field-add-name">
<$edit-text tiddler="$:/temp/newfieldname" tag="input" default="" placeholder={{$:/language/EditTemplate/Fields/Add/Name/Placeholder}} focusPopup=<<qualify "$:/state/popup/field-dropdown">> class="tc-edit-texteditor tc-popup-handle"/>
</span>
<$button popup=<<qualify "$:/state/popup/field-dropdown">> class="tc-btn-invisible tc-btn-dropdown" tooltip={{$:/language/EditTemplate/Field/Dropdown/Hint}} aria-label={{$:/language/EditTemplate/Field/Dropdown/Caption}}>{{$:/core/images/down-arrow}}</$button>
<$reveal state=<<qualify "$:/state/popup/field-dropdown">> type="nomatch" text="" default="">
<div class="tc-block-dropdown tc-edit-type-dropdown">
<$linkcatcher to="$:/temp/newfieldname">
<div class="tc-dropdown-item">
<<lingo Fields/Add/Dropdown/User>>
</div>
<$list filter="[!is[shadow]!is[system]fields[]sort[]] -created -creator -draft.of -draft.title -modified -modifier -tags -text -title -type" variable="currentField">
<$link to=<<currentField>>>
<<currentField>>
</$link>
</$list>
<div class="tc-dropdown-item">
<<lingo Fields/Add/Dropdown/System>>
</div>
<$list filter="[fields[]sort[]] -[!is[shadow]!is[system]fields[]]" variable="currentField">
<$link to=<<currentField>>>
<<currentField>>
</$link>
</$list>
</$linkcatcher>
</div>
</$reveal>
<span class="tc-edit-field-add-value">
<$edit-text tiddler="$:/temp/newfieldvalue" tag="input" default="" placeholder={{$:/language/EditTemplate/Fields/Add/Value/Placeholder}} class="tc-edit-texteditor"/>
</span>
<span class="tc-edit-field-add-button">
<$macrocall $name="new-field"/>
</span>
</div>
</$fieldmangler>
\define lingo-base() $:/language/EditTemplate/Shadow/
\define pluginLinkBody()
<$link to="""$(pluginTitle)$""">
<$text text="""$(pluginTitle)$"""/>
</$link>
\end
<$list filter="[all[current]get[draft.of]is[shadow]!is[tiddler]]">
<$list filter="[all[current]shadowsource[]]" variable="pluginTitle">
<$set name="pluginLink" value=<<pluginLinkBody>>>
<div class="tc-message-box">
<<lingo Warning>>
</div>
</$set>
</$list>
</$list>
<$list filter="[all[current]get[draft.of]is[shadow]is[tiddler]]">
<$list filter="[all[current]shadowsource[]]" variable="pluginTitle">
<$set name="pluginLink" value=<<pluginLinkBody>>>
<div class="tc-message-box">
<<lingo OverriddenWarning>>
</div>
</$set>
</$list>
</$list>
\define lingo-base() $:/language/EditTemplate/
\define tag-styles()
background-color:$(backgroundColor)$;
\end
<div class="tc-edit-tags">
<$fieldmangler>
<$list filter="[all[current]tags[]sort[title]]" storyview="pop"><$set name="backgroundColor" value={{!!color}}><span style=<<tag-styles>> class="tc-tag-label">
<$view field="title" format="text" />
<$button message="tm-remove-tag" param={{!!title}} class="tc-btn-invisible tc-remove-tag-button">×</$button></span>
</$set>
</$list>
<div class="tc-edit-add-tag">
<span class="tc-add-tag-name">
<$edit-text tiddler="$:/temp/NewTagName" tag="input" default="" placeholder={{$:/language/EditTemplate/Tags/Add/Placeholder}} focusPopup=<<qualify "$:/state/popup/tags-auto-complete">> class="tc-edit-texteditor tc-popup-handle"/>
</span> <$button popup=<<qualify "$:/state/popup/tags-auto-complete">> class="tc-btn-invisible tc-btn-dropdown" tooltip={{$:/language/EditTemplate/Tags/Dropdown/Hint}} aria-label={{$:/language/EditTemplate/Tags/Dropdown/Caption}}>{{$:/core/images/down-arrow}}</$button> <span class="tc-add-tag-button">
<$button message="tm-add-tag" param={{$:/temp/NewTagName}} set="$:/temp/NewTagName" setTo="" class="">
<<lingo Tags/Add/Button>>
</$button>
</span>
</div>
<div class="tc-block-dropdown-wrapper">
<$reveal state=<<qualify "$:/state/popup/tags-auto-complete">> type="nomatch" text="" default="">
<div class="tc-block-dropdown">
<$linkcatcher set="$:/temp/NewTagName" setTo="" message="tm-add-tag">
<$list filter="[tags[]!is[system]search:title{$:/temp/NewTagName}sort[]]">
{{||$:/core/ui/Components/tag-link}}
</$list>
<hr>
<$list filter="[tags[]is[system]search:title{$:/temp/NewTagName}sort[]]">
{{||$:/core/ui/Components/tag-link}}
</$list>
</$linkcatcher>
</div>
</$reveal>
</div>
</$fieldmangler>
</div>
<$edit-text field="draft.title" class="tc-titlebar tc-edit-texteditor" focus="true"/>
\define lingo-base() $:/language/EditTemplate/
<div class="tc-type-selector"><$fieldmangler>
<em class="tc-edit"><<lingo Type/Prompt>></em> <$edit-text field="type" tag="input" default="" placeholder={{$:/language/EditTemplate/Type/Placeholder}} focusPopup=<<qualify "$:/state/popup/type-dropdown">> class="tc-edit-typeeditor tc-popup-handle"/> <$button popup=<<qualify "$:/state/popup/type-dropdown">> class="tc-btn-invisible tc-btn-dropdown" tooltip={{$:/language/EditTemplate/Type/Dropdown/Hint}} aria-label={{$:/language/EditTemplate/Type/Dropdown/Caption}}>{{$:/core/images/down-arrow}}</$button> <$button message="tm-remove-field" param="type" class="tc-btn-invisible tc-btn-icon" tooltip={{$:/language/EditTemplate/Type/Delete/Hint}} aria-label={{$:/language/EditTemplate/Type/Delete/Caption}}>{{$:/core/images/delete-button}}</$button>
</$fieldmangler></div>
<div class="tc-block-dropdown-wrapper">
<$reveal state=<<qualify "$:/state/popup/type-dropdown">> type="nomatch" text="" default="">
<div class="tc-block-dropdown tc-edit-type-dropdown">
<$linkcatcher to="!!type">
<$list filter='[all[shadows+tiddlers]prefix[$:/language/Docs/Types/]each[group]sort[group]]'>
<div class="tc-dropdown-item">
<$text text={{!!group}}/>
</div>
<$list filter="[all[shadows+tiddlers]prefix[$:/language/Docs/Types/]group{!!group}] +[sort[description]]"><$link to={{!!name}}><$view field="description"/> (<$view field="name"/>)</$link>
</$list>
</$list>
</$linkcatcher>
</div>
</$reveal>
</div>
\define lingo-base() $:/language/Import/
\define messageField()
message-$(payloadTiddler)$
\end
\define selectionField()
selection-$(payloadTiddler)$
\end
\define previewPopupState()
$(currentTiddler)$!!popup-$(payloadTiddler)$
\end
<table>
<tbody>
<tr>
<th>
<<lingo Listing/Select/Caption>>
</th>
<th>
<<lingo Listing/Title/Caption>>
</th>
<th>
<<lingo Listing/Status/Caption>>
</th>
</tr>
<$list filter="[all[current]plugintiddlers[]sort[title]]" variable="payloadTiddler">
<tr>
<td>
<$checkbox field=<<selectionField>> checked="checked" unchecked="unchecked" default="checked"/>
</td>
<td>
<$reveal type="nomatch" state=<<previewPopupState>> text="yes">
<$button class="tc-btn-invisible tc-btn-dropdown" set=<<previewPopupState>> setTo="yes">
{{$:/core/images/right-arrow}} <$text text=<<payloadTiddler>>/>
</$button>
</$reveal>
<$reveal type="match" state=<<previewPopupState>> text="yes">
<$button class="tc-btn-invisible tc-btn-dropdown" set=<<previewPopupState>> setTo="no">
{{$:/core/images/down-arrow}} <$text text=<<payloadTiddler>>/>
</$button>
</$reveal>
</td>
<td>
<$view field=<<messageField>>/>
</td>
</tr>
<tr>
<td colspan="3">
<$reveal type="match" text="yes" state=<<previewPopupState>>>
<$transclude subtiddler=<<payloadTiddler>> mode="block"/>
</$reveal>
</td>
</tr>
</$list>
</tbody>
</table>
<div class="tc-menu-list-item">
<$link to={{!!title}}>
<$view field="title"/>
</$link>
</div>
<div class="tc-tiddler-missing">
<$button popup=<<qualify "$:/state/popup/missing">> class="tc-btn-invisible tc-missing-tiddler-label">
<$view field="title" format="text" />
</$button>
<$reveal state=<<qualify "$:/state/popup/missing">> type="popup" position="below" animate="yes">
<div class="tc-drop-down">
<$transclude tiddler="$:/core/ui/ListItemTemplate"/>
<hr>
<$list filter="[all[current]backlinks[]sort[title]]" template="$:/core/ui/ListItemTemplate"/>
</div>
</$reveal>
</div>
<$list filter={{$:/core/Filters/AllTiddlers!!filter}} template="$:/core/ui/ListItemTemplate"/>
<$list filter={{$:/core/Filters/Drafts!!filter}} template="$:/core/ui/ListItemTemplate"/>
<$list filter={{$:/core/Filters/Missing!!filter}} template="$:/core/ui/MissingTemplate"/>
<$list filter={{$:/core/Filters/Orphans!!filter}} template="$:/core/ui/ListItemTemplate"/>
<$macrocall $name="timeline" format={{$:/language/RecentChanges/DateFormat}}/>
<$list filter={{$:/core/Filters/ShadowTiddlers!!filter}} template="$:/core/ui/ListItemTemplate"/>
<$list filter={{$:/core/Filters/SystemTiddlers!!filter}} template="$:/core/ui/ListItemTemplate"/>
<$set name="tv-config-toolbar-icons" value="yes">
<$set name="tv-config-toolbar-text" value="yes">
<$set name="tv-config-toolbar-class" value="">
{{$:/core/ui/Buttons/tag-manager}}
</$set>
</$set>
</$set>
<$list filter={{$:/core/Filters/AllTags!!filter}}>
<$transclude tiddler="$:/core/ui/TagTemplate"/>
</$list>
<hr class="tc-untagged-separator">
{{$:/core/ui/UntaggedTemplate}}
<$list filter={{$:/core/Filters/TypedTiddlers!!filter}}>
<div class="tc-menu-list-item">
<$view field="type"/>
<$list filter="[type{!!type}!is[system]sort[title]]">
<div class="tc-menu-list-subitem">
<$link to={{!!title}}><$view field="title"/></$link>
</div>
</$list>
</div>
</$list>
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<$set name="currentTiddler" value={{$:/language}}>
<$set name="languageTitle" value={{!!name}}>
<$list filter="[all[shadows+tiddlers]tag[$:/tags/Stylesheet]!has[draft.of]]">
<$transclude mode="block"/>
</$list>
</$set>
</$set>
</$importvariables>
\define containerClasses()
tc-page-container tc-page-view-$(themeTitle)$ tc-language-$(languageTitle)$
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<$set name="tv-config-toolbar-icons" value={{$:/config/Toolbar/Icons}}>
<$set name="tv-config-toolbar-text" value={{$:/config/Toolbar/Text}}>
<$set name="tv-config-toolbar-class" value={{$:/config/Toolbar/ButtonClass}}>
<$set name="themeTitle" value={{$:/view}}>
<$set name="currentTiddler" value={{$:/language}}>
<$set name="languageTitle" value={{!!name}}>
<$set name="currentTiddler" value="">
<div class=<<containerClasses>>>
<$navigator story="$:/StoryList" history="$:/HistoryList" openLinkFromInsideRiver={{$:/config/Navigation/openLinkFromInsideRiver}} openLinkFromOutsideRiver={{$:/config/Navigation/openLinkFromOutsideRiver}}>
<$list filter="[all[shadows+tiddlers]tag[$:/tags/PageTemplate]!has[draft.of]]" variable="listItem">
<$transclude tiddler=<<listItem>>/>
</$list>
</$navigator>
</div>
</$set>
</$set>
</$set>
</$set>
</$set>
</$set>
</$set>
</$importvariables>
<div class="tc-alerts">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/Alert]!has[draft.of]]" template="$:/core/ui/AlertTemplate" storyview="pop"/>
</div>
\define config-title()
$:/config/PageControlButtons/Visibility/$(listItem)$
\end
<div class="tc-page-controls">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/PageControls]!has[draft.of]]" variable="listItem">
<$reveal type="nomatch" state=<<config-title>> text="hide">
<$transclude tiddler=<<listItem>> mode="inline"/>
</$reveal>
</$list>
</div>
\define lingo-base() $:/language/
<$list filter="[has[plugin-type]haschanged[]!plugin-type[import]limit[1]]">
<$reveal type="nomatch" state="$:/temp/HidePluginWarning" text="yes">
<div class="tc-plugin-reload-warning">
<$set name="tv-config-toolbar-class" value="">
<<lingo PluginReloadWarning>> <$button set="$:/temp/HidePluginWarning" setTo="yes" class="tc-btn-invisible">{{$:/core/images/close-button}}</$button>
</$set>
</div>
</$reveal>
</$list>
<$scrollable fallthrough="no" class="tc-sidebar-scrollable">
<div class="tc-sidebar-header">
<$reveal state="$:/state/sidebar" type="match" text="yes" default="yes" retain="yes" animate="yes">
<h1 class="tc-site-title">
<$transclude tiddler="$:/SiteTitle" mode="inline"/>
</h1>
<div class="tc-site-subtitle">
<$transclude tiddler="$:/SiteSubtitle" mode="inline"/>
</div>
{{||$:/core/ui/PageTemplate/pagecontrols}}
<$transclude tiddler="$:/core/ui/SideBarLists" mode="inline"/>
</$reveal>
</div>
</$scrollable>
<section class="tc-story-river">
<section class="story-backdrop">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/AboveStory]!has[draft.of]]">
<$transclude/>
</$list>
</section>
<$list filter="[list[$:/StoryList]]" history="$:/HistoryList" template="$:/core/ui/ViewTemplate" editTemplate="$:/core/ui/EditTemplate" storyview={{$:/view}} emptyMessage={{$:/config/EmptyStoryMessage}}/>
<section class="story-frontdrop">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/BelowStory]!has[draft.of]]">
<$transclude/>
</$list>
</section>
</section>
<span class="tc-topbar tc-topbar-left">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/TopLeftBar]!has[draft.of]]" variable="listItem">
<$transclude tiddler=<<listItem>> mode="inline"/>
</$list>
</span>
<span class="tc-topbar tc-topbar-right">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/TopRightBar]!has[draft.of]]" variable="listItem">
<$transclude tiddler=<<listItem>> mode="inline"/>
</$list>
</span>
\define localised-info-tiddler-title()
$(currentTiddler)$/$(languageTitle)$/$(currentTab)$
\end
\define info-tiddler-title()
$(currentTiddler)$/$(currentTab)$
\end
<$transclude tiddler=<<localised-info-tiddler-title>> mode="block">
<$transclude tiddler=<<currentTiddler>> subtiddler=<<localised-info-tiddler-title>> mode="block">
<$transclude tiddler=<<currentTiddler>> subtiddler=<<info-tiddler-title>> mode="block">
No ''"<$text text=<<currentTab>>/>"'' found
</$transclude>
</$transclude>
</$transclude>
<div class="tc-search-results">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/SearchResults]!has[draft.of]butfirst[]limit[1]]" emptyMessage="""
<$list filter="[all[shadows+tiddlers]tag[$:/tags/SearchResults]!has[draft.of]]">
<$transclude mode="block"/>
</$list>
""">
<$macrocall $name="tabs" tabsList="[all[shadows+tiddlers]tag[$:/tags/SearchResults]!has[draft.of]]" default={{$:/config/SearchResults/Default}}/>
</$list>
</div>
<div class="tc-more-sidebar">
<<tabs "[all[shadows+tiddlers]tag[$:/tags/MoreSideBar]!has[draft.of]]" "$:/core/ui/MoreSideBar/Tags" "$:/state/tab/moresidebar" "tc-vertical">>
</div>
\define lingo-base() $:/language/CloseAll/
<$list filter="[list[$:/StoryList]]" history="$:/HistoryList" storyview="pop">
<$button message="tm-close-tiddler" tooltip={{$:/language/Buttons/Close/Hint}} aria-label={{$:/language/Buttons/Close/Caption}} class="tc-btn-invisible tc-btn-mini">×</$button> <$link to={{!!title}}><$view field="title"/></$link>
</$list>
<$button message="tm-close-all-tiddlers" class="tc-btn-invisible tc-btn-mini"><<lingo Button>></$button>
<$macrocall $name="timeline" format={{$:/language/RecentChanges/DateFormat}}/>
\define lingo-base() $:/language/ControlPanel/
\define config-title()
$:/config/PageControlButtons/Visibility/$(listItem)$
\end
<<lingo Basics/Version/Prompt>> <<version>>
<$set name="tv-config-toolbar-icons" value="yes">
<$set name="tv-config-toolbar-text" value="yes">
<$set name="tv-config-toolbar-class" value="">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/PageControls]!has[draft.of]]" variable="listItem">
<div style="position:relative;">
<$checkbox tiddler=<<config-title>> field="text" checked="show" unchecked="hide" default="show"/> <$transclude tiddler=<<listItem>>/> <i class="tc-muted"><$transclude tiddler=<<listItem>> field="description"/></i>
</div>
</$list>
</$set>
</$set>
</$set>
<div class="tc-sidebar-lists">
<$set name="searchTiddler" value="$:/temp/search">
<div class="tc-search">
<$edit-text tiddler="$:/temp/search" type="search" tag="input" focus={{$:/config/Search/AutoFocus}} focusPopup=<<qualify "$:/state/popup/search-dropdown">> class="tc-popup-handle"/>
<$reveal state="$:/temp/search" type="nomatch" text="">
<$button tooltip={{$:/language/Buttons/AdvancedSearch/Hint}} aria-label={{$:/language/Buttons/AdvancedSearch/Caption}} class="tc-btn-invisible">
<$action-setfield $tiddler="$:/temp/advancedsearch" text={{$:/temp/search}}/>
<$action-setfield $tiddler="$:/temp/search" text=""/>
<$action-navigate $to="$:/AdvancedSearch"/>
{{$:/core/images/advanced-search-button}}
</$button>
<$button class="tc-btn-invisible">
<$action-setfield $tiddler="$:/temp/search" text="" />
{{$:/core/images/close-button}}
</$button>
<$button popup=<<qualify "$:/state/popup/search-dropdown">> class="tc-btn-invisible">
<$set name="resultCount" value="""<$count filter="[!is[system]search{$(searchTiddler)$}]"/>""">
{{$:/core/images/down-arrow}} {{$:/language/Search/Matches}}
</$set>
</$button>
</$reveal>
<$reveal state="$:/temp/search" type="match" text="">
<$button to="$:/AdvancedSearch" tooltip={{$:/language/Buttons/AdvancedSearch/Hint}} aria-label={{$:/language/Buttons/AdvancedSearch/Caption}} class="tc-btn-invisible">
{{$:/core/images/advanced-search-button}}
</$button>
</$reveal>
</div>
<$reveal tag="div" class="tc-block-dropdown-wrapper" state="$:/temp/search" type="nomatch" text="">
<$reveal tag="div" class="tc-block-dropdown tc-search-drop-down tc-popup-handle" state=<<qualify "$:/state/popup/search-dropdown">> type="nomatch" text="" default="">
{{$:/core/ui/SearchResults}}
</$reveal>
</$reveal>
</$set>
<$macrocall $name="tabs" tabsList="[all[shadows+tiddlers]tag[$:/tags/SideBar]!has[draft.of]]" default={{$:/config/DefaultSidebarTab}} state="$:/state/tab/sidebar" />
</div>
\define tag-styles()
background-color:$(backgroundColor)$;
fill:$(foregroundColor)$;
color:$(foregroundColor)$;
\end
\define tag-body-inner(colour,fallbackTarget,colourA,colourB)
<$set name="foregroundColor" value=<<contrastcolour target:"""$colour$""" fallbackTarget:"""$fallbackTarget$""" colourA:"""$colourA$""" colourB:"""$colourB$""">>>
<$set name="backgroundColor" value="""$colour$""">
<$button popup=<<qualify "$:/state/popup/tag">> class="tc-btn-invisible tc-tag-label" style=<<tag-styles>>>
<$transclude tiddler={{!!icon}}/> <$view field="title" format="text" />
</$button>
<$reveal state=<<qualify "$:/state/popup/tag">> type="popup" position="below" animate="yes"><div class="tc-drop-down"><$transclude tiddler="$:/core/ui/ListItemTemplate"/>
<hr>
<$list filter="[all[current]tagging[]]" template="$:/core/ui/ListItemTemplate"/>
</div>
</$reveal>
</$set>
</$set>
\end
\define tag-body(colour,palette)
<span class="tc-tag-list-item">
<$macrocall $name="tag-body-inner" colour="""$colour$""" fallbackTarget={{$palette$##tag-background}} colourA={{$palette$##foreground}} colourB={{$palette$##background}}/>
</span>
\end
<$macrocall $name="tag-body" colour={{!!color}} palette={{$:/palette}}/>
<table class="tc-view-field-table">
<tbody>
<$list filter="[all[current]fields[]sort[title]] -text" template="$:/core/ui/TiddlerFieldTemplate" variable="listItem"/>
</tbody>
</table>
<tr class="tc-view-field">
<td class="tc-view-field-name">
<$text text=<<listItem>>/>
</td>
<td class="tc-view-field-value">
<$view field=<<listItem>>/>
</td>
</tr>
<$macrocall $name="tabs" tabsList="[all[shadows+tiddlers]tag[$:/tags/TiddlerInfo]!has[draft.of]]" default={{$:/config/TiddlerInfo/Default}}/>
<$list filter="[all[shadows+tiddlers]tag[$:/tags/TiddlerInfo/Advanced]!has[draft.of]]" variable="listItem">
<$transclude tiddler=<<listItem>>/>
</$list>
\define lingo-base() $:/language/TiddlerInfo/Advanced/PluginInfo/
<$list filter="[all[current]has[plugin-type]]">
! <<lingo Heading>>
<<lingo Hint>>
<ul>
<$list filter="[all[current]plugintiddlers[]sort[title]]" emptyMessage=<<lingo Empty/Hint>>>
<li>
<$link to={{!!title}}>
<$view field="title"/>
</$link>
</li>
</$list>
</ul>
</$list>
\define lingo-base() $:/language/TiddlerInfo/Advanced/ShadowInfo/
<$set name="infoTiddler" value=<<currentTiddler>>>
''<<lingo Heading>>''
<$list filter="[all[current]!is[shadow]]">
<<lingo NotShadow/Hint>>
</$list>
<$list filter="[all[current]is[shadow]]">
<<lingo Shadow/Hint>>
<$list filter="[all[current]shadowsource[]]">
<$set name="pluginTiddler" value=<<currentTiddler>>>
<<lingo Shadow/Source>>
</$set>
</$list>
<$list filter="[all[current]is[shadow]is[tiddler]]">
<<lingo OverriddenShadow/Hint>>
</$list>
</$list>
</$set>
<$transclude tiddler="$:/core/ui/TiddlerFields"/>
\define lingo-base() $:/language/TiddlerInfo/
<$list filter="[list{!!title}]" emptyMessage=<<lingo List/Empty>> template="$:/core/ui/ListItemTemplate"/>
\define lingo-base() $:/language/TiddlerInfo/
<$list filter="[all[current]listed[]!is[system]]" emptyMessage=<<lingo Listed/Empty>> template="$:/core/ui/ListItemTemplate"/>
\define lingo-base() $:/language/TiddlerInfo/
<$list filter="[all[current]backlinks[]sort[title]]" emptyMessage=<<lingo References/Empty>> template="$:/core/ui/ListItemTemplate">
</$list>
\define lingo-base() $:/language/TiddlerInfo/
<$list filter="[all[current]tagging[]]" emptyMessage=<<lingo Tagging/Empty>> template="$:/core/ui/ListItemTemplate"/>
\define lingo-base() $:/language/TiddlerInfo/
\define config-title()
$:/config/ViewToolbarButtons/Visibility/$(listItem)$
\end
<$set name="tv-config-toolbar-icons" value="yes">
<$set name="tv-config-toolbar-text" value="yes">
<$set name="tv-config-toolbar-class" value="">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/ViewToolbar]!has[draft.of]]" variable="listItem">
<$checkbox tiddler=<<config-title>> field="text" checked="show" unchecked="hide" default="show"/> <$transclude tiddler=<<listItem>>/> <i class="tc-muted"><$transclude tiddler=<<listItem>> field="description"/></i>
</$list>
</$set>
</$set>
</$set>
<$reveal state="$:/state/sidebar" type="nomatch" text="no">
<$button set="$:/state/sidebar" setTo="no" tooltip={{$:/language/Buttons/HideSideBar/Hint}} aria-label={{$:/language/Buttons/HideSideBar/Caption}} class="tc-btn-invisible">{{$:/core/images/chevron-right}}</$button>
</$reveal>
<$reveal state="$:/state/sidebar" type="match" text="no">
<$button set="$:/state/sidebar" setTo="yes" tooltip={{$:/language/Buttons/ShowSideBar/Hint}} aria-label={{$:/language/Buttons/ShowSideBar/Caption}} class="tc-btn-invisible">{{$:/core/images/chevron-left}}</$button>
</$reveal>
\define lingo-base() $:/language/SideBar/
<$button popup=<<qualify "$:/state/popup/tag">> class="tc-btn-invisible tc-untagged-label tc-tag-label">
<<lingo Tags/Untagged/Caption>>
</$button>
<$reveal state=<<qualify "$:/state/popup/tag">> type="popup" position="below">
<div class="tc-drop-down">
<$list filter="[untagged[]!is[system]] -[tags[]] +[sort[title]]" template="$:/core/ui/ListItemTemplate"/>
</div>
</$reveal>
\define frame-classes()
tc-tiddler-frame tc-tiddler-view-frame $(missingTiddlerClass)$ $(shadowTiddlerClass)$ $(systemTiddlerClass)$ $(tiddlerTagClasses)$
\end
\define folded-state()
$:/state/folded/$(currentTiddler)$
\end
<$set name="storyTiddler" value=<<currentTiddler>>><$set name="tiddlerInfoState" value=<<qualify "$:/state/popup/tiddler-info">>><$tiddler tiddler=<<currentTiddler>>><div class=<<frame-classes>>><$list filter="[all[shadows+tiddlers]tag[$:/tags/ViewTemplate]!has[draft.of]]" variable="listItem"><$transclude tiddler=<<listItem>>/></$list>
</div>
</$tiddler></$set></$set>
<$reveal tag="div" class="tc-tiddler-body" type="nomatch" state=<<folded-state>> text="hide" retain="yes" animate="yes">
<$list filter="[all[current]!has[plugin-type]!field:hide-body[yes]]">
<$transclude>
<$transclude tiddler="$:/language/MissingTiddler/Hint"/>
</$transclude>
</$list>
</$reveal>
\define lingo-base() $:/language/ClassicWarning/
<$list filter="[all[current]type[text/x-tiddlywiki]]">
<div class="tc-message-box">
<<lingo Hint>>
<$button set="!!type" setTo="text/vnd.tiddlywiki"><<lingo Upgrade/Caption>></$button>
</div>
</$list>
\define lingo-base() $:/language/Import/
<$list filter="[all[current]field:plugin-type[import]]">
<div class="tc-import">
<<lingo Listing/Hint>>
<$button message="tm-delete-tiddler" param=<<currentTiddler>>><<lingo Listing/Cancel/Caption>></$button>
<$button message="tm-perform-import" param=<<currentTiddler>>><<lingo Listing/Import/Caption>></$button>
{{||$:/core/ui/ImportListing}}
<$button message="tm-delete-tiddler" param=<<currentTiddler>>><<lingo Listing/Cancel/Caption>></$button>
<$button message="tm-perform-import" param=<<currentTiddler>>><<lingo Listing/Import/Caption>></$button>
</div>
</$list>
<$list filter="[all[current]has[plugin-type]] -[all[current]field:plugin-type[import]]">
{{||$:/core/ui/TiddlerInfo/Advanced/PluginInfo}}
</$list>
<$reveal type="nomatch" state=<<folded-state>> text="hide" tag="div" retain="yes" animate="yes">
<div class="tc-subtitle">
<$link to={{!!modifier}}>
<$view field="modifier"/>
</$link> <$view field="modified" format="date" template={{$:/language/Tiddler/DateFormat}}/>
</div>
</$reveal>
<$reveal type="nomatch" state=<<folded-state>> text="hide" tag="div" retain="yes" animate="yes">
<div class="tc-tags-wrapper"><$list filter="[all[current]tags[]sort[title]]" template="$:/core/ui/TagTemplate" storyview="pop"/></div>
</$reveal>
\define title-styles()
fill:$(foregroundColor)$;
\end
\define config-title()
$:/config/ViewToolbarButtons/Visibility/$(listItem)$
\end
<div class="tc-tiddler-title">
<div class="tc-titlebar">
<span class="tc-tiddler-controls">
<$list filter="[all[shadows+tiddlers]tag[$:/tags/ViewToolbar]!has[draft.of]]" variable="listItem"><$reveal type="nomatch" state=<<config-title>> text="hide"><$transclude tiddler=<<listItem>>/></$reveal></$list>
</span>
<$set name="tv-wikilinks" value={{$:/config/Tiddlers/TitleLinks}}>
<$link>
<$set name="foregroundColor" value={{!!color}}>
<span class="tc-tiddler-title-icon" style=<<title-styles>>>
<$transclude tiddler={{!!icon}}/>
</span>
</$set>
<$list filter="[all[current]removeprefix[$:/]]">
<h2 class="tc-title" title={{$:/language/SystemTiddler/Tooltip}}>
<span class="tc-system-title-prefix">$:/</span><$text text=<<currentTiddler>>/>
</h2>
</$list>
<$list filter="[all[current]!prefix[$:/]]">
<h2 class="tc-title">
<$view field="title"/>
</h2>
</$list>
</$link>
</$set>
</div>
<$reveal type="nomatch" text="" default="" state=<<tiddlerInfoState>> class="tc-tiddler-info tc-popup-handle" animate="yes" retain="yes">
<$transclude tiddler="$:/core/ui/TiddlerInfo"/>
</$reveal>
</div>
<$reveal tag="div" type="nomatch" state="$:/config/ViewToolbarButtons/Visibility/$:/core/ui/Buttons/fold-bar" text="hide">
<$reveal tag="div" type="nomatch" state=<<folded-state>> text="hide" default="show" retain="yes" animate="yes">
<$button tooltip={{$:/language/Buttons/Fold/Hint}} aria-label={{$:/language/Buttons/Fold/Caption}} class="tc-fold-banner">
<$action-sendmessage $message="tm-fold-tiddler" $param=<<currentTiddler>> foldedState=<<folded-state>>/>
{{$:/core/images/chevron-up}}
</$button>
</$reveal>
<$reveal tag="div" type="nomatch" state=<<folded-state>> text="show" default="show" retain="yes" animate="yes">
<$button tooltip={{$:/language/Buttons/Unfold/Hint}} aria-label={{$:/language/Buttons/Unfold/Caption}} class="tc-unfold-banner">
<$action-sendmessage $message="tm-fold-tiddler" $param=<<currentTiddler>> foldedState=<<folded-state>>/>
{{$:/core/images/chevron-down}}
</$button>
</$reveal>
</$reveal>
{{$:/SiteTitle}} --- {{$:/SiteSubtitle}}
The following tiddlers were imported:
# [[$:/plugins/bj/jtinker/jtinker]]
It looks like you are trying to load a plugin designed for ~TiddlyWiki Classic. Please note that [[these plugins do not work with TiddlyWiki version 5.x.x|http://tiddlywiki.com/#TiddlyWikiClassic]]. ~TiddlyWiki Classic plugins detected:
This tiddler contains binary data
Discard changes to this tiddler
Clear the password and save this wiki without encryption
Set or clear a password for saving this wiki
Set a password for saving this wiki with encryption
Optional bars to fold and unfold tiddlers
Fold the body of this tiddler
Fold the bodies of all opened tiddlers
Fold the bodies of other opened tiddlers
Enter or leave full-screen mode
Open the default tiddlers
Import many types of file including text, image, TiddlyWiki or JSON
Show information for this tiddler
Choose the user interface language
Create a new tiddler tagged with this one
Create a new journal tiddler
Create a new journal tiddler tagged with this one
Open tiddler in new window
Choose the colour palette
Set browser address bar to a direct link to this tiddler
Set browser address bar to a direct link to all the tiddlers in this story
Perform a full refresh of the wiki
Confirm changes to this tiddler
Choose the story visualisation
Unfold the body of this tiddler
Unfold the bodies of all opened tiddlers
This tiddler is written in TiddlyWiki Classic wiki text format, which is not fully compatible with TiddlyWiki version 5. See http://tiddlywiki.com/static/Upgrading.html for more details.
Do you wish to discard changes to the tiddler "<$text text=<<title>>/>"?
Do you wish to delete the tiddler "<$text text=<<title>>/>"?
You are about to edit a ShadowTiddler. Any changes will override the default system making future upgrades non-trivial. Are you sure you want to edit "<$text text=<<title>>/>"?
Do you wish to overwrite the tiddler "<$text text=<<title>>/>"?
Internal information about this TiddlyWiki
Ways to customise the appearance of your TiddlyWiki.
Use [[double square brackets]] for titles with spaces. Or you can choose to <$button set="$:/DefaultTiddlers" setTo="[list[$:/StoryList]]">retain story ordering</$button>
Choose which tiddlers are displayed at startup:
Tags for new journal tiddlers
Title of new journal tiddlers
Number of overridden shadow tiddlers:
Number of shadow tiddlers:
Number of system tiddlers:
Title of this ~TiddlyWiki:
Username for signing edits:
These tiddlers determine which editor is used to edit specific tiddler types.
Information about this TiddlyWiki
These are the currently loaded tiddler modules linked to their source tiddlers. Any italicised modules lack a source tiddler, typically because they were setup during the boot process.
It is recommended that you clone this shadow palette before editing it
This shadow palette has been modified
Here you can globally disable individual wiki parser rules. Take care as disabling some parser rules can prevent ~TiddlyWiki functioning correctly (you can restore normal operation with [[safe mode|http://tiddlywiki.com/#SafeMode]] )
Install plugins from the official library
Disable this plugin when reloading page
Enable this plugin when reloading page
Currently installed plugins:
These settings are only used when saving to http://tiddlyspot.com or a compatible remote server
//The server URL defaults to `http://<wikiname>.tiddlyspot.com/store.cgi` and can be changed to use a custom server address, e.g. `http://example.com/store.php`.//
Do not save changes automatically
Save changes automatically
Automatically save changes during editing
Enable automatic ~CamelCase linking
You can globally disable automatic linking of ~CamelCase phrases. Requires reload to take effect
Specify which sidebar tab is displayed by default
These settings let you customise the behaviour of TiddlyWiki.
Tiddler Opening Behaviour
Navigation from //within// the story river
Open above the current tiddler
Open at the bottom of the story river
Open at the top of the story river
Open below the current tiddler
Navigation from //outside// the story river
Behaviour of the browser address bar when navigating to a tiddler:
Do not update the address bar
Include the target tiddler
Include the target tiddler and the current story sequence
Update browser history when navigating to a tiddler:
Performance Instrumentation
Enable performance instrumentation
Displays performance statistics in the browser developer console. Requires reload to take effect
Optionally display tiddler titles as links
Do not display tiddler titles as links
Display tiddler titles as links
Default toolbar button appearance:
Choose the style for toolbar buttons:
This is the full set of TiddlerFields in use in this wiki (including system tiddlers but excluding shadow tiddlers).
Choose which buttons are displayed for tiddlers in edit mode
Select which toolbar buttons are displayed
Choose which buttons are displayed on the main page toolbar
Choose which buttons are displayed for tiddlers in view mode
The full URI of an external image tiddler
The name of the bag from which a tiddler came
The text to be displayed on a tab or button
The CSS color value associated with a tiddler
The name of the component responsible for an [[alert tiddler|AlertMechanism]]
The date a tiddler was created
The name of the person who created a tiddler
Used to cache the top tiddler in a [[history list|HistoryMechanism]]
For a plugin, lists the dependent plugin titles
The descriptive text for a plugin, or a modal dialogue
For draft tiddlers, contains the title of the tiddler of which this is a draft
For draft tiddlers, contains the proposed new title of the tiddler
The footer text for a wizard
A temporary storage field used in [[$:/core/templates/static.content]]
The title of the tiddler containing the icon associated with a tiddler
If set to "yes" indicates that a tiddler should be saved as a JavaScript library
An ordered list of tiddler titles associated with a tiddler
If set, the title of the tiddler after which this tiddler should be added to the ordered list of tiddler titles
If set, the title of a tiddler before which this tiddler should be added to the ordered list of tiddler titles, or at the start of the list if this field is present but empty
The date and time at which a tiddler was last modified
The tiddler title associated with the person who last modified a tiddler
The human readable name associated with a plugin tiddler
A numerical value indicating the priority of a plugin tiddler
The type of plugin in a plugin tiddler
Date of a TiddlyWiki release
The revision of the tiddler held at the server
The source URL associated with a tiddler
The subtitle text for a wizard
A list of tags associated with a tiddler
The body text of a tiddler
The unique name of a tiddler
The content type of a tiddler
Version information for a plugin
Animations that may be used with the RevealWidget.
Commands that can be executed under Node.js.
Data to be inserted into `$tw.config`.
Individual filter operator methods.
Global data to be inserted into `$tw`.
Operands for the ''is'' filter operator.
JavaScript macro definitions.
Parsers for different content types.
Savers handle different methods for saving files from the browser.
Story views customise the animation and behaviour of list widgets.
Converts different content types into tiddlers.
Defines the behaviour of an individual tiddler field.
Adds methods to the `$tw.Tiddler` prototype.
Applies upgrade processing to tiddlers during an upgrade/import.
Adds methods to `$tw.utils`.
Adds Node.js-specific methods to `$tw.utils`.
Widgets encapsulate DOM rendering and refreshing.
Adds methods to `$tw.Wiki`.
Individual parser rules for the main WikiText parser.
Default button background
Default button foreground
Unsaved changes indicator
Download button background
Download button foreground
Dropdown tab background for selected tabs
External link background hover
External link background visited
External link foreground hover
External link foreground visited
Preformatted code background
Sidebar button foreground
Sidebar controls foreground
Sidebar controls foreground hover
Sidebar foreground shadow
Sidebar muted foreground hover
Sidebar tab background for selected tabs
Sidebar tab border for selected tabs
Sidebar tab foreground for selected tabs
Sidebar tiddler link foreground
Sidebar tiddler link foreground hover
Tab background for selected tabs
Tab border for selected tabs
Tab foreground for selected tabs
Tiddler controls foreground
Tiddler controls foreground hover
Tiddler controls foreground for selected controls
Tiddler editor background
Tiddler editor border image
Tiddler editor background for even fields
Tiddler editor background for odd fields
Tiddler info panel background
Tiddler info panel border
Tiddler info panel tab background
Tiddler subtitle foreground
Toolbar 'cancel' button foreground
Toolbar 'close' button foreground
Toolbar 'delete' button foreground
Toolbar 'done' button foreground
Toolbar 'edit' button foreground
Toolbar 'info' button foreground
Toolbar 'new tiddler' button foreground
Toolbar 'options' button foreground
Toolbar 'save' button foreground
Drop here (or use the 'Escape' key to cancel)
This is an external tiddler stored outside of the main TiddlyWiki file. You can edit the tags and fields but cannot directly edit the content itself
Use [[wiki text|http://tiddlywiki.com/static/WikiText.html]] to add formatting, images, and dynamic features
Type the text for this tiddler
This is a modified shadow tiddler. You can revert to the default version in the plugin <<pluginLink>> by deleting this tiddler
This is a shadow tiddler. Any changes you make will override the default version from the plugin <<pluginLink>>
Do you wish to clear the password? This will remove the encryption applied when saving this wiki
Set a new password for this TiddlyWiki
All tags except system tags
All tiddlers except system tiddlers
Overridden shadow tiddlers
Recently modified tiddlers, including system tiddlers
Recently modified tiddlers
Build the specified build targets for the current wiki. If no build targets are specified then all available targets will be built.
```
--build <target> [<target> ...]
```
Build targets are defined in the `tiddlywiki.info` file of a wiki folder.
Clear the password for subsequent crypto operations
```
--clearpassword
```
\define commandTitle()
$:/language/Help/$(command)$
\end
```
usage: tiddlywiki [<wikifolder>] [--<command> [<args>...]...]
```
Available commands:
<ul>
<$list filter="[commands[]sort[title]]" variable="command">
<li><$link to=<<commandTitle>>><$macrocall $name="command" $type="text/plain" $output="text/plain"/></$link>: <$transclude tiddler=<<commandTitle>> field="description"/></li>
</$list>
</ul>
To get detailed help on a command:
```
tiddlywiki --help <command>
```
Lists the names and descriptions of the available editions. You can create a new wiki of a specified edition with the `--init` command.
```
--editions
```
Displays help text for a command:
```
--help [<command>]
```
If the command name is omitted then a list of available commands is displayed.
Initialise an empty [[WikiFolder|WikiFolders]] with a copy of the specified edition.
```
--init <edition> [<edition> ...]
```
For example:
```
tiddlywiki ./MyWikiFolder --init empty
```
Note:
* The wiki folder directory will be created if necessary
* The "edition" defaults to ''empty''
* The init command will fail if the wiki folder is not empty
* The init command removes any `includeWikis` definitions in the edition's `tiddlywiki.info` file
* When multiple editions are specified, editions initialised later will overwrite any files shared with earlier editions (so, the final `tiddlywiki.info` file will be copied from the last edition)
* `--editions` returns a list of available editions
Load tiddlers from 2.x.x TiddlyWiki files (`.html`), `.tiddler`, `.tid`, `.json` or other files
```
--load <filepath>
```
To load tiddlers from an encrypted TiddlyWiki file you should first specify the password with the PasswordCommand. For example:
```
tiddlywiki ./MyWiki --password pa55w0rd --load my_encrypted_wiki.html
```
Note that TiddlyWiki will not load an older version of an already loaded plugin.
Constructs the `$:/UpgradeLibrary` tiddler for the upgrade process.
The upgrade library is formatted as an ordinary plugin tiddler with the plugin type `library`. It contains a copy of each of the plugins, themes and language packs available within the TiddlyWiki5 repository.
This command is intended for internal use; it is only relevant to users constructing a custom upgrade procedure.
```
--makelibrary <title>
```
The title argument defaults to `$:/UpgradeLibrary`.
Sets the base output directory for subsequent commands. The default output directory is the `output` subdirectory of the edition directory.
```
--output <pathname>
```
If the specified pathname is relative then it is resolved relative to the current working directory. For example `--output .` sets the output directory to the current working directory.
Set a password for subsequent crypto operations
```
--password <password>
```
''Note'': This should not be used for serving TiddlyWiki with password protection. Instead, see the password option under the [[ServerCommand]].
Render an individual tiddler as a specified ContentType, defaulting to `text/html` and save it to the specified filename. Optionally a template can be specified, in which case the template tiddler is rendered with the "currentTiddler" variable set to the tiddler that is being rendered (the first parameter value).
```
--rendertiddler <title> <filename> [<type>] [<template>]
```
By default, the filename is resolved relative to the `output` subdirectory of the edition directory. The `--output` command can be used to direct output to a different directory.
Any missing directories in the path to the filename are automatically created.
Render a set of tiddlers matching a filter to separate files of a specified ContentType (defaults to `text/html`) and extension (defaults to `.html`).
```
--rendertiddlers <filter> <template> <pathname> [<type>] [<extension>] ["noclean"]
```
For example:
```
--rendertiddlers [!is[system]] $:/core/templates/static.tiddler.html ./static text/plain
```
By default, the pathname is resolved relative to the `output` subdirectory of the edition directory. The `--output` command can be used to direct output to a different directory.
Any files in the target directory are deleted unless the ''noclean'' flag is specified. The target directory is recursively created if it is missing.
Saves an individual tiddler in its raw text or binary format to the specified filename.
```
--savetiddler <title> <filename>
```
By default, the filename is resolved relative to the `output` subdirectory of the edition directory. The `--output` command can be used to direct output to a different directory.
Any missing directories in the path to the filename are automatically created.
Saves a group of tiddlers in their raw text or binary format to the specified directory.
```
--savetiddlers <filter> <pathname> ["noclean"]
```
By default, the pathname is resolved relative to the `output` subdirectory of the edition directory. The `--output` command can be used to direct output to a different directory.
The output directory is cleared of existing files before saving the specified files. The deletion can be disabled by specifying the ''noclean'' flag.
Any missing directories in the pathname are automatically created.
The server built in to TiddlyWiki5 is very simple. Although compatible with TiddlyWeb it doesn't support many of the features needed for robust Internet-facing usage.
At the root, it serves a rendering of a specified tiddler. Away from the root, it serves individual tiddlers encoded in JSON, and supports the basic HTTP operations for `GET`, `PUT` and `DELETE`.
```
--server <port> <roottiddler> <rendertype> <servetype> <username> <password> <host> <pathprefix>
```
The parameters are:
* ''port'' - port number to serve from (defaults to "8080")
* ''roottiddler'' - the tiddler to serve at the root (defaults to "$:/core/save/all")
* ''rendertype'' - the content type to which the root tiddler should be rendered (defaults to "text/plain")
* ''servetype'' - the content type with which the root tiddler should be served (defaults to "text/html")
* ''username'' - the default username for signing edits
* ''password'' - optional password for basic authentication
* ''host'' - optional hostname to serve from (defaults to "127.0.0.1" aka "localhost")
* ''pathprefix'' - optional prefix for paths
If the password parameter is specified then the browser will prompt the user for the username and password. Note that the password is transmitted in plain text so this implementation isn't suitable for general use.
For example:
```
--server 8080 $:/core/save/all text/plain text/html MyUserName passw0rd
```
The username and password can be specified as empty strings if you need to set the hostname or pathprefix and don't want to require a password:
```
--server 8080 $:/core/save/all text/plain text/html "" "" 192.168.0.245
```
To run multiple TiddlyWiki servers at the same time you'll need to put each one on a different port.
//Note that this command is experimental and may change or be replaced before being finalised//
Sets the specified field of a group of tiddlers to the result of wikifying a template tiddler with the `currentTiddler` variable set to the tiddler.
```
--setfield <filter> <fieldname> <templatetitle> <rendertype>
```
The parameters are:
* ''filter'' - filter identifying the tiddlers to be affected
* ''fieldname'' - the field to modify (defaults to "text")
* ''templatetitle'' - the tiddler to wikify into the specified field. If blank or missing then the specified field is deleted
* ''rendertype'' - the text type to render (defaults to "text/plain"; "text/html" can be used to include HTML tags)
Extract the payload tiddlers from a plugin, creating them as ordinary tiddlers:
```
--unpackplugin <title>
```
Triggers verbose output, useful for debugging
```
--verbose
```
Displays the version number of TiddlyWiki.
```
--version
```
The following tiddlers were imported:
These tiddlers are ready to import:
Blocked incompatible or obsolete plugin
Blocked plugin (due to incoming <<incoming>> being older than existing <<existing>>)
Upgraded plugin from <<incoming>> to <<upgraded>>
Blocked temporary state tiddler
Migrated theme tweak from <$text text=<<from>>/>
Well, this is embarrassing. It is recommended that you restart TiddlyWiki by refreshing your browser
Internal JavaScript Error
Illegal characters in field name "<$text text=<<fieldName>>/>". Fields can only contain lowercase letters, digits and the characters underscore (`_`), hyphen (`-`) and period (`.`)
<p>Loading external text from ''<$text text={{!!_canonical_uri}}/>''</p><p>If this message doesn't disappear you may be using a browser that doesn't support external text in this configuration. See http://tiddlywiki.com/#ExternalText</p>
Missing tiddler "<$text text=<<currentTiddler>>/>" - click {{$:/core/images/edit-button}} to create
Your browser only supports manual saving.
To save your modified wiki, right click on the download link below and select "Download file" or "Save file", and then choose the folder and filename.
//You can marginally speed things up by clicking the link with the control key (Windows) or the options/alt key (Mac OS X). You will not be prompted for the folder or filename, but your browser is likely to give it an unrecognisable name -- you may need to rename the file to include an `.html` extension before you can do anything useful with it.//
On smartphones that do not allow files to be downloaded you can instead bookmark the link, and then sync your bookmarks to a desktop computer from where the wiki can be saved normally.
Your changes to this wiki need to be saved as a ~TiddlyWiki HTML file.
!!! Desktop browsers
# Select ''Save As'' from the ''File'' menu
# Choose a filename and location
#* Some browsers also require you to explicitly specify the file saving format as ''Webpage, HTML only'' or similar
# Close this tab
!!! Smartphone browsers
# Create a bookmark to this page
#* If you've got iCloud or Google Sync set up then the bookmark will automatically sync to your desktop where you can open it and save it as above
# Close this tab
//If you open the bookmark again in Mobile Safari you will see this message again. If you want to go ahead and use the file, just click the ''close'' button below//
Official ~TiddlyWiki Plugin Library
The official ~TiddlyWiki plugin library at tiddlywiki.com. Plugins, themes and language packs are maintained by the core team.
Please save {{$:/core/ui/Buttons/save-wiki}} and reload {{$:/core/ui/Buttons/refresh}} to allow changes to plugins to take effect
<<period>> hours from now
<<period>> minutes from now
<<period>> months from now
<<period>> seconds from now
<<period>> years from now
Search via a [[filter expression|http://tiddlywiki.com/static/Filters.html]]
//<small><<resultCount>> matches</small>//
//<small><<resultCount>> matches</small>//
Search for shadow tiddlers
//<small><<resultCount>> matches</small>//
Search for standard tiddlers
//<small><<resultCount>> matches</small>//
Search for system tiddlers
//<small><<resultCount>> matches</small>//
DDth MMM YYYY at hh12:0mmam
This plugin contains the following shadow tiddlers:
The tiddler <$link to=<<infoTiddler>>><$text text=<<infoTiddler>>/></$link> is not a shadow tiddler
It is overridden by an ordinary tiddler
The tiddler <$link to=<<infoTiddler>>><$text text=<<infoTiddler>>/></$link> is a shadow tiddler
It is defined in the plugin <$link to=<<pluginTiddler>>><$text text=<<pluginTiddler>>/></$link>
This tiddler does not have a list
This tiddler is not listed by any others
No tiddlers link to this one
No tiddlers are tagged with this one
You have unsaved changes in TiddlyWiki
Stub pseudo-plugin for the default language
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 30" width="1200" height="600">
<clipPath id="t">
<path d="M30,15 h30 v15 z v15 h-30 z h-30 v-15 z v-15 h30 z"/>
</clipPath>
<path d="M0,0 v30 h60 v-30 z" fill="#00247d"/>
<path d="M0,0 L60,30 M60,0 L0,30" stroke="#fff" stroke-width="6"/>
<path d="M0,0 L60,30 M60,0 L0,30" clip-path="url(#t)" stroke="#cf142b" stroke-width="4"/>
<path d="M30,0 v30 M0,15 h60" stroke="#fff" stroke-width="10"/>
<path d="M30,0 v30 M0,15 h60" stroke="#cf142b" stroke-width="6"/>
</svg>
alert-background: #ffe476
alert-border: #b99e2f
alert-highlight: #881122
alert-muted-foreground: #b99e2f
background: #ffffff
blockquote-bar: <<colour muted-foreground>>
button-background:
button-foreground:
button-border:
code-background: #f7f7f9
code-border: #e1e1e8
code-foreground: #dd1144
dirty-indicator: #ff0000
download-background: #66cccc
download-foreground: <<colour background>>
dragger-background: <<colour foreground>>
dragger-foreground: <<colour background>>
dropdown-background: <<colour background>>
dropdown-border: <<colour muted-foreground>>
dropdown-tab-background-selected: #fff
dropdown-tab-background: #ececec
dropzone-background: rgba(0,200,0,0.7)
external-link-background-hover: inherit
external-link-background-visited: inherit
external-link-background: inherit
external-link-foreground-hover: inherit
external-link-foreground-visited: #0000aa
external-link-foreground: #0000ee
foreground: #333333
message-background: #ecf2ff
message-border: #cfd6e6
message-foreground: #547599
modal-backdrop: <<colour foreground>>
modal-background: <<colour background>>
modal-border: #999999
modal-footer-background: #f5f5f5
modal-footer-border: #dddddd
modal-header-border: #eeeeee
muted-foreground: #999999
notification-background: #ffffdd
notification-border: #999999
page-background: #ffffff
pre-background: #f5f5f5
pre-border: #cccccc
primary: #7897f3
sidebar-button-foreground: <<colour foreground>>
sidebar-controls-foreground-hover: #000000
sidebar-controls-foreground: #ccc
sidebar-foreground-shadow: rgba(255,255,255, 0.8)
sidebar-foreground: #acacac
sidebar-muted-foreground-hover: #444444
sidebar-muted-foreground: #c0c0c0
sidebar-tab-background-selected: #ffffff
sidebar-tab-background: <<colour tab-background>>
sidebar-tab-border-selected: <<colour tab-border-selected>>
sidebar-tab-border: <<colour tab-border>>
sidebar-tab-divider: <<colour tab-divider>>
sidebar-tab-foreground-selected:
sidebar-tab-foreground: <<colour tab-foreground>>
sidebar-tiddler-link-foreground-hover: #444444
sidebar-tiddler-link-foreground: #7897f3
site-title-foreground: <<colour tiddler-title-foreground>>
static-alert-foreground: #aaaaaa
tab-background-selected: #ffffff
tab-background: #eeeeee
tab-border-selected: #cccccc
tab-border: #cccccc
tab-divider: #d8d8d8
tab-foreground-selected: <<colour tab-foreground>>
tab-foreground: #666666
table-border: #dddddd
table-footer-background: #a8a8a8
table-header-background: #f0f0f0
tag-background: #ffeedd
tag-foreground: #000
tiddler-background: <<colour background>>
tiddler-border: #eee
tiddler-controls-foreground-hover: #888888
tiddler-controls-foreground-selected: #444444
tiddler-controls-foreground: #cccccc
tiddler-editor-background: #f8f8f8
tiddler-editor-border-image: #ffffff
tiddler-editor-border: #cccccc
tiddler-editor-fields-even: #e0e8e0
tiddler-editor-fields-odd: #f0f4f0
tiddler-info-background: #f8f8f8
tiddler-info-border: #dddddd
tiddler-info-tab-background: #f8f8f8
tiddler-link-background: <<colour background>>
tiddler-link-foreground: <<colour primary>>
tiddler-subtitle-foreground: #c0c0c0
tiddler-title-foreground: #ff9900
toolbar-new-button:
toolbar-options-button:
toolbar-save-button:
toolbar-info-button:
toolbar-edit-button:
toolbar-close-button:
toolbar-delete-button:
toolbar-cancel-button:
toolbar-done-button:
untagged-background: #999999
very-muted-foreground: #888888
alert-background: #ffe476
alert-border: #b99e2f
alert-highlight: #881122
alert-muted-foreground: #b99e2f
background: #fff
blockquote-bar: <<colour muted-foreground>>
button-background:
button-foreground:
button-border:
code-background: #f7f7f9
code-border: #e1e1e8
code-foreground: #dd1144
dirty-indicator: #ff0000
download-background: #34c734
download-foreground: <<colour foreground>>
dragger-background: <<colour foreground>>
dragger-foreground: <<colour background>>
dropdown-background: <<colour background>>
dropdown-border: <<colour muted-foreground>>
dropdown-tab-background-selected: #fff
dropdown-tab-background: #ececec
dropzone-background: rgba(0,200,0,0.7)
external-link-background-hover: inherit
external-link-background-visited: inherit
external-link-background: inherit
external-link-foreground-hover: inherit
external-link-foreground-visited: #0000aa
external-link-foreground: #0000ee
foreground: #333353
message-background: #ecf2ff
message-border: #cfd6e6
message-foreground: #547599
modal-backdrop: <<colour foreground>>
modal-background: <<colour background>>
modal-border: #999999
modal-footer-background: #f5f5f5
modal-footer-border: #dddddd
modal-header-border: #eeeeee
muted-foreground: #999999
notification-background: #ffffdd
notification-border: #999999
page-background: #ddddff
pre-background: #f5f5f5
pre-border: #cccccc
primary: #5778d8
sidebar-button-foreground: <<colour foreground>>
sidebar-controls-foreground-hover: #000000
sidebar-controls-foreground: #ffffff
sidebar-foreground-shadow: rgba(255,255,255, 0.8)
sidebar-foreground: #acacac
sidebar-muted-foreground-hover: #444444
sidebar-muted-foreground: #c0c0c0
sidebar-tab-background-selected: <<colour page-background>>
sidebar-tab-background: <<colour tab-background>>
sidebar-tab-border-selected: <<colour tab-border-selected>>
sidebar-tab-border: <<colour tab-border>>
sidebar-tab-divider: <<colour tab-divider>>
sidebar-tab-foreground-selected:
sidebar-tab-foreground: <<colour tab-foreground>>
sidebar-tiddler-link-foreground-hover: #444444
sidebar-tiddler-link-foreground: #5959c0
site-title-foreground: <<colour tiddler-title-foreground>>
static-alert-foreground: #aaaaaa
tab-background-selected: <<colour background>>
tab-background: #ccccdd
tab-border-selected: #ccccdd
tab-border: #cccccc
tab-divider: #d8d8d8
tab-foreground-selected: <<colour tab-foreground>>
tab-foreground: #666666
table-border: #dddddd
table-footer-background: #a8a8a8
table-header-background: #f0f0f0
tag-background: #eeeeff
tag-foreground: #000
tiddler-background: <<colour background>>
tiddler-border: <<colour background>>
tiddler-controls-foreground-hover: #666666
tiddler-controls-foreground-selected: #444444
tiddler-controls-foreground: #cccccc
tiddler-editor-background: #f8f8f8
tiddler-editor-border-image: #ffffff
tiddler-editor-border: #cccccc
tiddler-editor-fields-even: #e0e8e0
tiddler-editor-fields-odd: #f0f4f0
tiddler-info-background: #ffffff
tiddler-info-border: #dddddd
tiddler-info-tab-background: #ffffff
tiddler-link-background: <<colour background>>
tiddler-link-foreground: <<colour primary>>
tiddler-subtitle-foreground: #c0c0c0
tiddler-title-foreground: #5959c0
toolbar-new-button: #5eb95e
toolbar-options-button: rgb(128, 88, 165)
toolbar-save-button: #0e90d2
toolbar-info-button: #0e90d2
toolbar-edit-button: rgb(243, 123, 29)
toolbar-close-button: #dd514c
toolbar-delete-button: #dd514c
toolbar-cancel-button: rgb(243, 123, 29)
toolbar-done-button: #5eb95e
untagged-background: #999999
very-muted-foreground: #888888
alert-background: #f00
alert-border: <<colour background>>
alert-highlight: <<colour foreground>>
alert-muted-foreground: #800
background: #000
blockquote-bar: <<colour muted-foreground>>
button-background: <<colour background>>
button-foreground: <<colour foreground>>
button-border: <<colour foreground>>
code-background: <<colour background>>
code-border: <<colour foreground>>
code-foreground: <<colour foreground>>
dirty-indicator: #f00
download-background: #080
download-foreground: <<colour background>>
dragger-background: <<colour foreground>>
dragger-foreground: <<colour background>>
dropdown-background: <<colour background>>
dropdown-border: <<colour muted-foreground>>
dropdown-tab-background-selected: <<colour foreground>>
dropdown-tab-background: <<colour foreground>>
dropzone-background: rgba(0,200,0,0.7)
external-link-background-hover: inherit
external-link-background-visited: inherit
external-link-background: inherit
external-link-foreground-hover: inherit
external-link-foreground-visited: #00a
external-link-foreground: #00e
foreground: #fff
message-background: <<colour foreground>>
message-border: <<colour background>>
message-foreground: <<colour background>>
modal-backdrop: <<colour foreground>>
modal-background: <<colour background>>
modal-border: <<colour foreground>>
modal-footer-background: <<colour background>>
modal-footer-border: <<colour foreground>>
modal-header-border: <<colour foreground>>
muted-foreground: <<colour foreground>>
notification-background: <<colour background>>
notification-border: <<colour foreground>>
page-background: <<colour background>>
pre-background: <<colour background>>
pre-border: <<colour foreground>>
primary: #00f
sidebar-button-foreground: <<colour foreground>>
sidebar-controls-foreground-hover: <<colour background>>
sidebar-controls-foreground: <<colour foreground>>
sidebar-foreground-shadow: rgba(0,0,0, 0)
sidebar-foreground: <<colour foreground>>
sidebar-muted-foreground-hover: #444444
sidebar-muted-foreground: <<colour foreground>>
sidebar-tab-background-selected: <<colour background>>
sidebar-tab-background: <<colour tab-background>>
sidebar-tab-border-selected: <<colour tab-border-selected>>
sidebar-tab-border: <<colour tab-border>>
sidebar-tab-divider: <<colour tab-divider>>
sidebar-tab-foreground-selected: <<colour foreground>>
sidebar-tab-foreground: <<colour tab-foreground>>
sidebar-tiddler-link-foreground-hover: <<colour foreground>>
sidebar-tiddler-link-foreground: <<colour primary>>
site-title-foreground: <<colour tiddler-title-foreground>>
static-alert-foreground: #aaaaaa
tab-background-selected: <<colour background>>
tab-background: <<colour foreground>>
tab-border-selected: <<colour foreground>>
tab-border: <<colour foreground>>
tab-divider: <<colour foreground>>
tab-foreground-selected: <<colour foreground>>
tab-foreground: <<colour background>>
table-border: #dddddd
table-footer-background: #a8a8a8
table-header-background: #f0f0f0
tag-background: #fff
tag-foreground: #000
tiddler-background: <<colour background>>
tiddler-border: <<colour foreground>>
tiddler-controls-foreground-hover: #ddd
tiddler-controls-foreground-selected: #fdd
tiddler-controls-foreground: <<colour foreground>>
tiddler-editor-background: <<colour background>>
tiddler-editor-border-image: <<colour foreground>>
tiddler-editor-border: #cccccc
tiddler-editor-fields-even: <<colour background>>
tiddler-editor-fields-odd: <<colour background>>
tiddler-info-background: <<colour background>>
tiddler-info-border: <<colour foreground>>
tiddler-info-tab-background: <<colour background>>
tiddler-link-background: <<colour background>>
tiddler-link-foreground: <<colour primary>>
tiddler-subtitle-foreground: <<colour foreground>>
tiddler-title-foreground: <<colour foreground>>
toolbar-new-button:
toolbar-options-button:
toolbar-save-button:
toolbar-info-button:
toolbar-edit-button:
toolbar-close-button:
toolbar-delete-button:
toolbar-cancel-button:
toolbar-done-button:
untagged-background: <<colour foreground>>
very-muted-foreground: #888888
alert-background: #f00
alert-border: <<colour background>>
alert-highlight: <<colour foreground>>
alert-muted-foreground: #800
background: #fff
blockquote-bar: <<colour muted-foreground>>
button-background: <<colour background>>
button-foreground: <<colour foreground>>
button-border: <<colour foreground>>
code-background: <<colour background>>
code-border: <<colour foreground>>
code-foreground: <<colour foreground>>
dirty-indicator: #f00
download-background: #080
download-foreground: <<colour background>>
dragger-background: <<colour foreground>>
dragger-foreground: <<colour background>>
dropdown-background: <<colour background>>
dropdown-border: <<colour muted-foreground>>
dropdown-tab-background-selected: <<colour foreground>>
dropdown-tab-background: <<colour foreground>>
dropzone-background: rgba(0,200,0,0.7)
external-link-background-hover: inherit
external-link-background-visited: inherit
external-link-background: inherit
external-link-foreground-hover: inherit
external-link-foreground-visited: #00a
external-link-foreground: #00e
foreground: #000
message-background: <<colour foreground>>
message-border: <<colour background>>
message-foreground: <<colour background>>
modal-backdrop: <<colour foreground>>
modal-background: <<colour background>>
modal-border: <<colour foreground>>
modal-footer-background: <<colour background>>
modal-footer-border: <<colour foreground>>
modal-header-border: <<colour foreground>>
muted-foreground: <<colour foreground>>
notification-background: <<colour background>>
notification-border: <<colour foreground>>
page-background: <<colour background>>
pre-background: <<colour background>>
pre-border: <<colour foreground>>
primary: #00f
sidebar-button-foreground: <<colour foreground>>
sidebar-controls-foreground-hover: <<colour background>>
sidebar-controls-foreground: <<colour foreground>>
sidebar-foreground-shadow: rgba(0,0,0, 0)
sidebar-foreground: <<colour foreground>>
sidebar-muted-foreground-hover: #444444
sidebar-muted-foreground: <<colour foreground>>
sidebar-tab-background-selected: <<colour background>>
sidebar-tab-background: <<colour tab-background>>
sidebar-tab-border-selected: <<colour tab-border-selected>>
sidebar-tab-border: <<colour tab-border>>
sidebar-tab-divider: <<colour tab-divider>>
sidebar-tab-foreground-selected: <<colour foreground>>
sidebar-tab-foreground: <<colour tab-foreground>>
sidebar-tiddler-link-foreground-hover: <<colour foreground>>
sidebar-tiddler-link-foreground: <<colour primary>>
site-title-foreground: <<colour tiddler-title-foreground>>
static-alert-foreground: #aaaaaa
tab-background-selected: <<colour background>>
tab-background: <<colour foreground>>
tab-border-selected: <<colour foreground>>
tab-border: <<colour foreground>>
tab-divider: <<colour foreground>>
tab-foreground-selected: <<colour foreground>>
tab-foreground: <<colour background>>
table-border: #dddddd
table-footer-background: #a8a8a8
table-header-background: #f0f0f0
tag-background: #000
tag-foreground: #fff
tiddler-background: <<colour background>>
tiddler-border: <<colour foreground>>
tiddler-controls-foreground-hover: #ddd
tiddler-controls-foreground-selected: #fdd
tiddler-controls-foreground: <<colour foreground>>
tiddler-editor-background: <<colour background>>
tiddler-editor-border-image: <<colour foreground>>
tiddler-editor-border: #cccccc
tiddler-editor-fields-even: <<colour background>>
tiddler-editor-fields-odd: <<colour background>>
tiddler-info-background: <<colour background>>
tiddler-info-border: <<colour foreground>>
tiddler-info-tab-background: <<colour background>>
tiddler-link-background: <<colour background>>
tiddler-link-foreground: <<colour primary>>
tiddler-subtitle-foreground: <<colour foreground>>
tiddler-title-foreground: <<colour foreground>>
toolbar-new-button:
toolbar-options-button:
toolbar-save-button:
toolbar-info-button:
toolbar-edit-button:
toolbar-close-button:
toolbar-delete-button:
toolbar-cancel-button:
toolbar-done-button:
untagged-background: <<colour foreground>>
very-muted-foreground: #888888
alert-background: #ffe476
alert-border: #b99e2f
alert-highlight: #881122
alert-muted-foreground: #b99e2f
background: #ffffff
blockquote-bar: <<colour muted-foreground>>
button-background:
button-foreground:
button-border:
code-background: #f7f7f9
code-border: #e1e1e8
code-foreground: #dd1144
dirty-indicator: #ff0000
download-background: #34c734
download-foreground: <<colour background>>
dragger-background: <<colour foreground>>
dragger-foreground: <<colour background>>
dropdown-background: <<colour background>>
dropdown-border: <<colour muted-foreground>>
dropdown-tab-background-selected: #fff
dropdown-tab-background: #ececec
dropzone-background: rgba(0,200,0,0.7)
external-link-background-hover: inherit
external-link-background-visited: inherit
external-link-background: inherit
external-link-foreground-hover: inherit
external-link-foreground-visited: #0000aa
external-link-foreground: #0000ee
foreground: #333333
message-background: #ecf2ff
message-border: #cfd6e6
message-foreground: #547599
modal-backdrop: <<colour foreground>>
modal-background: <<colour background>>
modal-border: #999999
modal-footer-background: #f5f5f5
modal-footer-border: #dddddd
modal-header-border: #eeeeee
muted-foreground: #ddd
notification-background: #ffffdd
notification-border: #999999
page-background: #336438
pre-background: #f5f5f5
pre-border: #cccccc
primary: #5778d8
sidebar-button-foreground: <<colour foreground>>
sidebar-controls-foreground-hover: #ccf
sidebar-controls-foreground: #fff
sidebar-foreground-shadow: rgba(0,0,0, 0.5)
sidebar-foreground: #fff
sidebar-muted-foreground-hover: #444444
sidebar-muted-foreground: #eee
sidebar-tab-background-selected: rgba(255,255,255, 0.8)
sidebar-tab-background: rgba(255,255,255, 0.4)
sidebar-tab-border-selected: <<colour tab-border-selected>>
sidebar-tab-border: <<colour tab-border>>
sidebar-tab-divider: rgba(255,255,255, 0.2)
sidebar-tab-foreground-selected:
sidebar-tab-foreground: <<colour tab-foreground>>
sidebar-tiddler-link-foreground-hover: #aaf
sidebar-tiddler-link-foreground: #ddf
site-title-foreground: #fff
static-alert-foreground: #aaaaaa
tab-background-selected: #ffffff
tab-background: #d8d8d8
tab-border-selected: #d8d8d8
tab-border: #cccccc
tab-divider: #d8d8d8
tab-foreground-selected: <<colour tab-foreground>>
tab-foreground: #666666
table-border: #dddddd
table-footer-background: #a8a8a8
table-header-background: #f0f0f0
tag-background: #ec6
tag-foreground: #ffffff
tiddler-background: <<colour background>>
tiddler-border: <<colour background>>
tiddler-controls-foreground-hover: #888888
tiddler-controls-foreground-selected: #444444
tiddler-controls-foreground: #cccccc
tiddler-editor-background: #f8f8f8
tiddler-editor-border-image: #ffffff
tiddler-editor-border: #cccccc
tiddler-editor-fields-even: #e0e8e0
tiddler-editor-fields-odd: #f0f4f0
tiddler-info-background: #f8f8f8
tiddler-info-border: #dddddd
tiddler-info-tab-background: #f8f8f8
tiddler-link-background: <<colour background>>
tiddler-link-foreground: <<colour primary>>
tiddler-subtitle-foreground: #c0c0c0
tiddler-title-foreground: #182955
toolbar-new-button:
toolbar-options-button:
toolbar-save-button:
toolbar-info-button:
toolbar-edit-button:
toolbar-close-button:
toolbar-delete-button:
toolbar-cancel-button:
toolbar-done-button:
untagged-background: #999999
very-muted-foreground: #888888
alert-background: #ffe476
alert-border: #b99e2f
alert-highlight: #881122
alert-muted-foreground: #b99e2f
background: #ffffff
blockquote-bar: <<colour muted-foreground>>
button-background:
button-foreground:
button-border:
code-background: #f7f7f9
code-border: #e1e1e8
code-foreground: #dd1144
dirty-indicator: #ff0000
download-background: #34c734
download-foreground: <<colour background>>
dragger-background: <<colour foreground>>
dragger-foreground: <<colour background>>
dropdown-background: <<colour background>>
dropdown-border: <<colour muted-foreground>>
dropdown-tab-background-selected: #fff
dropdown-tab-background: #ececec
dropzone-background: rgba(0,200,0,0.7)
external-link-background-hover: inherit
external-link-background-visited: inherit
external-link-background: inherit
external-link-foreground-hover: inherit
external-link-foreground-visited: #0000aa
external-link-foreground: #0000ee
foreground: #333333
message-background: #ecf2ff
message-border: #cfd6e6
message-foreground: #547599
modal-backdrop: <<colour foreground>>
modal-background: <<colour background>>
modal-border: #999999
modal-footer-background: #f5f5f5
modal-footer-border: #dddddd
modal-header-border: #eeeeee
muted-foreground: #bbb
notification-background: #ffffdd
notification-border: #999999
page-background: #6f6f70
pre-background: #f5f5f5
pre-border: #cccccc
primary: #29a6ee
sidebar-button-foreground: <<colour foreground>>
sidebar-controls-foreground-hover: #000000
sidebar-controls-foreground: #c2c1c2
sidebar-foreground-shadow: rgba(255,255,255,0)
sidebar-foreground: #d3d2d4
sidebar-muted-foreground-hover: #444444
sidebar-muted-foreground: #c0c0c0
sidebar-tab-background-selected: #6f6f70
sidebar-tab-background: #666667
sidebar-tab-border-selected: #999
sidebar-tab-border: #515151
sidebar-tab-divider: #999
sidebar-tab-foreground-selected:
sidebar-tab-foreground: #999
sidebar-tiddler-link-foreground-hover: #444444
sidebar-tiddler-link-foreground: #d1d0d2
site-title-foreground: <<colour tiddler-title-foreground>>
static-alert-foreground: #aaaaaa
tab-background-selected: #ffffff
tab-background: #d8d8d8
tab-border-selected: #d8d8d8
tab-border: #cccccc
tab-divider: #d8d8d8
tab-foreground-selected: <<colour tab-foreground>>
tab-foreground: #666666
table-border: #dddddd
table-footer-background: #a8a8a8
table-header-background: #f0f0f0
tag-background: #d5ad34
tag-foreground: #ffffff
tiddler-background: <<colour background>>
tiddler-border: <<colour background>>
tiddler-controls-foreground-hover: #888888
tiddler-controls-foreground-selected: #444444
tiddler-controls-foreground: #cccccc
tiddler-editor-background: #f8f8f8
tiddler-editor-border-image: #ffffff
tiddler-editor-border: #cccccc
tiddler-editor-fields-even: #e0e8e0
tiddler-editor-fields-odd: #f0f4f0
tiddler-info-background: #f8f8f8
tiddler-info-border: #dddddd
tiddler-info-tab-background: #f8f8f8
tiddler-link-background: <<colour background>>
tiddler-link-foreground: <<colour primary>>
tiddler-subtitle-foreground: #c0c0c0
tiddler-title-foreground: #182955
toolbar-new-button:
toolbar-options-button:
toolbar-save-button:
toolbar-info-button:
toolbar-edit-button:
toolbar-close-button:
toolbar-delete-button:
toolbar-cancel-button:
toolbar-done-button:
untagged-background: #999999
very-muted-foreground: #888888
alert-background: #ffe476
alert-border: #b99e2f
alert-highlight: #881122
alert-muted-foreground: #b99e2f
background: #ffffff
blockquote-bar: <<colour muted-foreground>>
button-background:
button-foreground:
button-border:
code-background: #f7f7f9
code-border: #e1e1e8
code-foreground: #dd1144
dirty-indicator: #ff0000
download-background: #34c734
download-foreground: <<colour background>>
dragger-background: <<colour foreground>>
dragger-foreground: <<colour background>>
dropdown-background: <<colour background>>
dropdown-border: <<colour muted-foreground>>
dropdown-tab-background-selected: #fff
dropdown-tab-background: #ececec
dropzone-background: rgba(0,200,0,0.7)
external-link-background-hover: inherit
external-link-background-visited: inherit
external-link-background: inherit
external-link-foreground-hover: inherit
external-link-foreground-visited: #0000aa
external-link-foreground: #0000ee
foreground: #333333
message-background: #ecf2ff
message-border: #cfd6e6
message-foreground: #547599
modal-backdrop: <<colour foreground>>
modal-background: <<colour background>>
modal-border: #999999
modal-footer-background: #f5f5f5
modal-footer-border: #dddddd
modal-header-border: #eeeeee
muted-foreground: #999999
notification-background: #ffffdd
notification-border: #999999
page-background: #000
pre-background: #f5f5f5
pre-border: #cccccc
primary: #cc0000
sidebar-button-foreground: <<colour foreground>>
sidebar-controls-foreground-hover: #000000
sidebar-controls-foreground: #ffffff
sidebar-foreground-shadow: rgba(255,255,255, 0.0)
sidebar-foreground: #acacac
sidebar-muted-foreground-hover: #444444
sidebar-muted-foreground: #c0c0c0
sidebar-tab-background-selected: #000
sidebar-tab-background: <<colour tab-background>>
sidebar-tab-border-selected: <<colour tab-border-selected>>
sidebar-tab-border: <<colour tab-border>>
sidebar-tab-divider: <<colour tab-divider>>
sidebar-tab-foreground-selected:
sidebar-tab-foreground: <<colour tab-foreground>>
sidebar-tiddler-link-foreground-hover: #ffbb99
sidebar-tiddler-link-foreground: #cc0000
site-title-foreground: <<colour tiddler-title-foreground>>
static-alert-foreground: #aaaaaa
tab-background-selected: #ffffff
tab-background: #d8d8d8
tab-border-selected: #d8d8d8
tab-border: #cccccc
tab-divider: #d8d8d8
tab-foreground-selected: <<colour tab-foreground>>
tab-foreground: #666666
table-border: #dddddd
table-footer-background: #a8a8a8
table-header-background: #f0f0f0
tag-background: #ffbb99
tag-foreground: #000
tiddler-background: <<colour background>>
tiddler-border: <<colour background>>
tiddler-controls-foreground-hover: #888888
tiddler-controls-foreground-selected: #444444
tiddler-controls-foreground: #cccccc
tiddler-editor-background: #f8f8f8
tiddler-editor-border-image: #ffffff
tiddler-editor-border: #cccccc
tiddler-editor-fields-even: #e0e8e0
tiddler-editor-fields-odd: #f0f4f0
tiddler-info-background: #f8f8f8
tiddler-info-border: #dddddd
tiddler-info-tab-background: #f8f8f8
tiddler-link-background: <<colour background>>
tiddler-link-foreground: <<colour primary>>
tiddler-subtitle-foreground: #c0c0c0
tiddler-title-foreground: #cc0000
toolbar-new-button:
toolbar-options-button:
toolbar-save-button:
toolbar-info-button:
toolbar-edit-button:
toolbar-close-button:
toolbar-delete-button:
toolbar-cancel-button:
toolbar-done-button:
untagged-background: #999999
very-muted-foreground: #888888
: Background Tones
base03: #002b36
base02: #073642
: Content Tones
base01: #586e75
base00: #657b83
base0: #839496
base1: #93a1a1
: Background Tones
base2: #eee8d5
base3: #fdf6e3
: Accent Colors
yellow: #b58900
orange: #cb4b16
red: #dc322f
magenta: #d33682
violet: #6c71c4
blue: #268bd2
cyan: #2aa198
green: #859900
: Additional Tones (RA)
base10: #c0c4bb
violet-muted: #7c81b0
blue-muted: #4e7baa
yellow-hot: #ffcc44
orange-hot: #eb6d20
red-hot: #ff2222
blue-hot: #2298ee
green-hot: #98ee22
: Palette
: Do not use colour macro for background and foreground
background: #fdf6e3
download-foreground: <<colour background>>
dragger-foreground: <<colour background>>
dropdown-background: <<colour background>>
modal-background: <<colour background>>
sidebar-foreground-shadow: <<colour background>>
tiddler-background: <<colour background>>
tiddler-border: <<colour background>>
tiddler-link-background: <<colour background>>
tab-background-selected: <<colour background>>
dropdown-tab-background-selected: <<colour tab-background-selected>>
foreground: #657b83
dragger-background: <<colour foreground>>
tab-foreground: <<colour foreground>>
tab-foreground-selected: <<colour tab-foreground>>
sidebar-tab-foreground-selected: <<colour tab-foreground-selected>>
sidebar-tab-foreground: <<colour tab-foreground>>
sidebar-button-foreground: <<colour foreground>>
sidebar-controls-foreground: <<colour foreground>>
sidebar-foreground: <<colour foreground>>
: base03
: base02
: base01
alert-muted-foreground: <<colour base01>>
: base00
code-foreground: <<colour base00>>
message-foreground: <<colour base00>>
tag-foreground: <<colour base00>>
: base0
sidebar-tiddler-link-foreground: <<colour base0>>
: base1
muted-foreground: <<colour base1>>
blockquote-bar: <<colour muted-foreground>>
dropdown-border: <<colour muted-foreground>>
sidebar-muted-foreground: <<colour muted-foreground>>
tiddler-title-foreground: <<colour muted-foreground>>
site-title-foreground: <<colour tiddler-title-foreground>>
: base2
modal-footer-background: <<colour base2>>
page-background: <<colour base2>>
modal-backdrop: <<colour page-background>>
notification-background: <<colour page-background>>
code-background: <<colour page-background>>
code-border: <<colour code-background>>
pre-background: <<colour page-background>>
pre-border: <<colour pre-background>>
sidebar-tab-background-selected: <<colour page-background>>
table-header-background: <<colour base2>>
tag-background: <<colour base2>>
tiddler-editor-background: <<colour base2>>
tiddler-info-background: <<colour base2>>
tiddler-info-tab-background: <<colour base2>>
tab-background: <<colour base2>>
dropdown-tab-background: <<colour tab-background>>
: base3
alert-background: <<colour base3>>
message-background: <<colour base3>>
: yellow
: orange
: red
: magenta
alert-highlight: <<colour magenta>>
: violet
external-link-foreground: <<colour violet>>
: blue
: cyan
: green
: base10
tiddler-controls-foreground: <<colour base10>>
: violet-muted
external-link-foreground-visited: <<colour violet-muted>>
: blue-muted
primary: <<colour blue-muted>>
download-background: <<colour primary>>
tiddler-link-foreground: <<colour primary>>
alert-border: #b99e2f
dirty-indicator: #ff0000
dropzone-background: rgba(0,200,0,0.7)
external-link-background-hover: inherit
external-link-background-visited: inherit
external-link-background: inherit
external-link-foreground-hover: inherit
message-border: #cfd6e6
modal-border: #999999
sidebar-controls-foreground-hover:
sidebar-muted-foreground-hover:
sidebar-tab-background: #ded8c5
sidebar-tiddler-link-foreground-hover:
static-alert-foreground: #aaaaaa
tab-border: #cccccc
modal-footer-border: <<colour tab-border>>
modal-header-border: <<colour tab-border>>
notification-border: <<colour tab-border>>
sidebar-tab-border: <<colour tab-border>>
tab-border-selected: <<colour tab-border>>
sidebar-tab-border-selected: <<colour tab-border-selected>>
tab-divider: #d8d8d8
sidebar-tab-divider: <<colour tab-divider>>
table-border: #dddddd
table-footer-background: #a8a8a8
tiddler-controls-foreground-hover: #888888
tiddler-controls-foreground-selected: #444444
tiddler-editor-border-image: #ffffff
tiddler-editor-border: #cccccc
tiddler-editor-fields-even: #e0e8e0
tiddler-editor-fields-odd: #f0f4f0
tiddler-info-border: #dddddd
tiddler-subtitle-foreground: #c0c0c0
toolbar-new-button:
toolbar-options-button:
toolbar-save-button:
toolbar-info-button:
toolbar-edit-button:
toolbar-close-button:
toolbar-delete-button:
toolbar-cancel-button:
toolbar-done-button:
untagged-background: #999999
very-muted-foreground: #888888
alert-background: #ffe476
alert-border: #b99e2f
alert-highlight: #881122
alert-muted-foreground: #b99e2f
background: #ffffff
blockquote-bar: <<colour muted-foreground>>
button-background:
button-foreground:
button-border:
code-background: #f7f7f9
code-border: #e1e1e8
code-foreground: #dd1144
dirty-indicator: #ff0000
download-background: #34c734
download-foreground: <<colour background>>
dragger-background: <<colour foreground>>
dragger-foreground: <<colour background>>
dropdown-background: <<colour background>>
dropdown-border: <<colour muted-foreground>>
dropdown-tab-background-selected: #fff
dropdown-tab-background: #ececec
dropzone-background: rgba(0,200,0,0.7)
external-link-background-hover: inherit
external-link-background-visited: inherit
external-link-background: inherit
external-link-foreground-hover: inherit
external-link-foreground-visited: #0000aa
external-link-foreground: #0000ee
foreground: #333333
message-background: #ecf2ff
message-border: #cfd6e6
message-foreground: #547599
modal-backdrop: <<colour foreground>>
modal-background: <<colour background>>
modal-border: #999999
modal-footer-background: #f5f5f5
modal-footer-border: #dddddd
modal-header-border: #eeeeee
muted-foreground: #bbb
notification-background: #ffffdd
notification-border: #999999
page-background: #f4f4f4
pre-background: #f5f5f5
pre-border: #cccccc
primary: #5778d8
sidebar-button-foreground: <<colour foreground>>
sidebar-controls-foreground-hover: #000000
sidebar-controls-foreground: #aaaaaa
sidebar-foreground-shadow: rgba(255,255,255, 0.8)
sidebar-foreground: #acacac
sidebar-muted-foreground-hover: #444444
sidebar-muted-foreground: #c0c0c0
sidebar-tab-background-selected: #f4f4f4
sidebar-tab-background: #e0e0e0
sidebar-tab-border-selected: <<colour tab-border-selected>>
sidebar-tab-border: <<colour tab-border>>
sidebar-tab-divider: #e4e4e4
sidebar-tab-foreground-selected:
sidebar-tab-foreground: <<colour tab-foreground>>
sidebar-tiddler-link-foreground-hover: #444444
sidebar-tiddler-link-foreground: #999999
site-title-foreground: <<colour tiddler-title-foreground>>
static-alert-foreground: #aaaaaa
tab-background-selected: #ffffff
tab-background: #d8d8d8
tab-border-selected: #d8d8d8
tab-border: #cccccc
tab-divider: #d8d8d8
tab-foreground-selected: <<colour tab-foreground>>
tab-foreground: #666666
table-border: #dddddd
table-footer-background: #a8a8a8
table-header-background: #f0f0f0
tag-background: #ec6
tag-foreground: #ffffff
tiddler-background: <<colour background>>
tiddler-border: <<colour background>>
tiddler-controls-foreground-hover: #888888
tiddler-controls-foreground-selected: #444444
tiddler-controls-foreground: #cccccc
tiddler-editor-background: #f8f8f8
tiddler-editor-border-image: #ffffff
tiddler-editor-border: #cccccc
tiddler-editor-fields-even: #e0e8e0
tiddler-editor-fields-odd: #f0f4f0
tiddler-info-background: #f8f8f8
tiddler-info-border: #dddddd
tiddler-info-tab-background: #f8f8f8
tiddler-link-background: <<colour background>>
tiddler-link-foreground: <<colour primary>>
tiddler-subtitle-foreground: #c0c0c0
tiddler-title-foreground: #182955
toolbar-new-button:
toolbar-options-button:
toolbar-save-button:
toolbar-info-button:
toolbar-edit-button:
toolbar-close-button:
toolbar-delete-button:
toolbar-cancel-button:
toolbar-done-button:
untagged-background: #999999
very-muted-foreground: #888888
The MIT License (MIT)
Copyright (c) 2014 Jeffrey Wikinson aka buggyj
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Allows a user defined collection of tiddlywiki type parser rules to be associated with a (flexible) type. The flexible type has the form
'
text/vnd.twbase<htmlp
'
where:
vnd.twbase refers to the tiddlywiki5 parser stripped of its rules.
htmlp is an example of a user defined name of a json tiddler that contains options to define which rules will make up the new type.
In this example htmlp contains
`
{
"parserrules": {
"pragmaRuleList": [],
"blockRuleList": [
"html"
],
"inlineRuleList": [
"html",
"prettylink",
"transcludeinline",
"entity",
"wikilink"
]
},
"parseAsInline": true
}
`
"prettylink" etc are the tiddlywiki5 supplied 'parser rules'. Non-tiddlywiki defined rules may also be be used.
It is also possible to defined pre-parsers (not shown in this example).
Project home: http://bjtools.tiddlyspot.com
<div style="float:top;vertical-align: top;">
<$link><$view field=title/></$link>
<hr>
<style>
.edtithistemplate{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
float:top;
width: 100%;
max-height:300px;
resize: vertical;
vertical-align: top;
border: none;
}
</style>
<$edit-codemirror class=edtithistemplate tiddler=<<currentTiddler>>/>
</div>
\define jtinker(json project)
<table>
<$taglist targeTtag=$project$ htmltag=td>
<$link><<currentTiddler>></$link>
</$taglist>
</table>
<div style="float:left;width:50%;vertical-align: top;"><$mosaic prefix=$json$ wfixed=true index=1 rows=2 cols=1 >{{||$:/plugins/bj/jtinker/edittemplate}}</$mosaic></div><div style="float:left;width:50%;vertical-align: top;"><$mosaic prefix=$json$ index=2 rows=2 cols=1 >{{||$:/plugins/bj/jtinker/edittemplate}}</$mosaic></div>
<$mosaic prefix=$json$ wfixed=true index=0 rows=1 cols=9 >
<$link>
<<currentTiddler>>
</$link>
</$mosaic>
\end
<$link><$view field=title/></$link>
<hr>
<$transclude tiddler=<<currentTiddler>>/>
.mosaic {
width: 100%;
}
.mosaic tr {
vertical-align: top;
}
/*\
title: $:/plugins/bj/mosaic/mosaic.js
type: application/javascript
module-type: widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var MosaicWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
this.addEventListeners([
{type: "tw-close-tiddler", handler: "handleCloseTiddlerEvent"}
]);
};
/*
Inherit from the base widget class
*/
MosaicWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
MosaicWidget.prototype.render = function(parent,nextSibling) {
// Save the parent dom node
this.parentDomNode = parent;
// Compute our attributes
this.computeAttributes();
// Execute our logic
this.execute();
// Create a root domNode to contain our widget
var domNode = this.create(parent,nextSibling);
// Assign classes to our domNode
var classes = this["class"].split(" ") || [];
classes.push("tw-grid-frame");
domNode.className = classes.join(" ");
// Insert the root domNode for this widget
this.domNodes.push(domNode);
parent.insertBefore(domNode,nextSibling);
// Render the child widgets into the domNode
this.renderChildren(domNode,null);
};
MosaicWidget.prototype.create = function(parent,nextSibling) {
// Create a simple div element to contain the table
return this.document.createElement("div");
};
MosaicWidget.prototype.execute = function() {
// Get the widget attributes
this.whenEmpty = this.getAttribute("whenEmpty");
this.index=this.getAttribute("index","0");//reserve 0 for future use
this.template = this.getAttribute("template");
this.wfixed = this.getAttribute("wfixed");
this.variableName = this.getAttribute("variable","currentTiddler");
this.prefix = this.getAttribute("prefix","mosaic");
this.jsontid=this.getAttribute("json",this.prefix);
this.json=$tw.wiki.getTiddlerData(this.jsontid,{});
this.json[this.index] = this.json[this.index]||[];
this.rows = parseInt(this.getAttribute("rows","5"),10);
this.cols = parseInt(this.getAttribute("cols","5"),10);
this["class"] = this.getAttribute("class",""); //<col style="width:40%">
// Build the table widget tree
var table = {type: "element",tag: "table", children:[],
attributes: {class: {type: "string", value: "mosaic"}}};
if (this.wfixed){
for(var col=0; col<this.cols; col++) {
table.children.push({type: "element",tag: "col", children:[],
attributes: {style: {type: "string", value: "width:"+100/this.cols+"%;" }}});
}
}
var tbody = {type: "element",tag: "tbody", children:[]};
for(var row=0; row<this.rows; row++) {
var tr = {type: "element",tag: "tr", children:[]};
for(var col=0; col<this.cols; col++) {
var td = {type: "element",tag: "td", children:[]};
var item = this.makeItemTemplate(this.getTableCellTitle(col,row));
item.row = row;
item.col = col;
td.children.push(item);
tr.children.push(td);
}
tbody.children.push(tr);
}
table.children.push(tbody);
// Append the contents enclosed by the grid widget
var children = [table];
if (this.parseTreeNode && this.parseTreeNode.children) {
//children = children.concat(this.parseTreeNode.children);
}
// Make all of the child widgets
this.makeChildWidgets(children);
};
MosaicWidget.prototype.getTableCellTitle = function(col,row) {
var val;
try {
//this.json = (!!this.json)?this.json:$tw.wiki.getTiddlerData(this.jsontid);
if (this.json[this.index][col]) {
val=this.json[this.index][col][row];
}
return (!!val)?val:null;
} catch(e){
return null;
}
};
MosaicWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if(changedAttributes.tiddler || changedAttributes["class"]) {
this.refreshSelf();
return true;
} else {
if(changedTiddlers[this.jsontid]) {
this.refreshSelf();
return true;
}
else
return this.refreshChildren(changedTiddlers);
}
};
/*
Compose the template for a list item
*/
MosaicWidget.prototype.makeItemTemplate = function(title) {
var tiddler ,
hasTemplate ,
template ,
templateTree;
if (!title) {
if (this.whenEmpty){
templateTree = [{type: "transclude", attributes: {tiddler: {type: "string", value: this.whenEmpty}}}];
} else { //need to give the cell some invisable contain that takes up space, otherwise empty rows colapse
templateTree = [{type: "element", tag: "img", attributes: {style:
{type: "string", value: "float:left;min-height:50px;min-width:50px;visibility:hidden;"}}}];
}
} else {
// Check if the tiddler has a template
tiddler = this.wiki.getTiddler(title);
if( tiddler && tiddler.hasField("template")) {
template = tiddler.fields.template;
}
// Compose the transclusion of the template
if(template) {
templateTree = [{type: "transclude", attributes: {tiddler: {type: "string", value: template}}}];
} else {
if(this.parseTreeNode.children && this.parseTreeNode.children.length > 0) {
templateTree = this.parseTreeNode.children;
} else {
// Default template is a link to the title
templateTree = [{type: "element", tag: this.parseTreeNode.isBlock ? "div" : "span",
children: [{type: "link", attributes: {to: {type: "string", value: title}}, children: [
{type: "text", text: title}
]}]}];
}
}
}
// Return the list item
return {type: "cellitem", itemTitle: title, variableName: this.variableName, children: templateTree, listtag:this.listtag};
};
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
MosaicWidget.prototype.setTiddlerCell = function(what,col,row,del) {
var self = this;
var update = function(value) {
var tiddler = self.wiki.getTiddler(self.jsontid),updateFields;
if (tiddler){
updateFields = {};
} else {
updateFields = {title:self.jsontid,type:"application/json"}
}
//alert(JSON.stringify(tiddler))
updateFields["text"] = value;
self.wiki.addTiddler(new $tw.Tiddler(self.wiki.getCreationFields(),tiddler,updateFields,
self.wiki.getModificationFields()));
};
if (!del) {
try {
this.json[this.index][col][row]='Ꮬ'+what;//BJ should first check to see if any char of json is Ꮬ - if so use another char for marker
} catch(e) {
try {
this.json[this.index][col]=[];
this.json[this.index][col][row]='Ꮬ'+what;//BJ should first check to see if any char of json is Ꮬ - if so use another char for marker
} catch(e) {
this.json[this.index] =[];
this.json[this.index][col]=[];
this.json[this.index][col][row]='Ꮬ'+what;//BJ should first check to see if any char of json is Ꮬ - if so use another char for marker
}
}
}
var pattern=new RegExp('"(Ꮬ?)('+escapeRegExp(what)+')"',"mg");
var newval = JSON.stringify(this.json,null,2).replace(pattern,
function(m,key1,key2,offset,str){
if (key1=='Ꮬ') {// our new entry - remove special marker
return '"'+key2+'"';
}
return '""';//remove old entry
});
update(newval);
};
// Close a specified tiddler
MosaicWidget.prototype.handleCloseTiddlerEvent = function(event) {
var title = event.param || event.tiddlerTitle;
this.setTiddlerCell(title,0,0,true);
return false;
};
exports.mosaic = MosaicWidget;
/*
Inherit from the base widget class
*/
var ItemWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
ItemWidget.prototype = new Widget();
ItemWidget.prototype.handleDropEvent = function(event) {
var self = this,
dataTransfer = event.dataTransfer,
returned = this.nameandOnListTag(dataTransfer);
if (!!returned.name) { //only handle tiddler drops
var node = this;
while(node && node.parentWidget) {
if(!!node.setTiddlerCell) {
node.setTiddlerCell(returned.name,self.parseTreeNode.col,self.parseTreeNode.row);
break;
}
node = node.parentWidget;
}
//this.parentWidget.parentWidget.parentWidget.setTiddlerCell(returned.name,this.parseTreeNode.col,this.parseTreeNode.row);
//cancel normal action
this.cancelAction(event);
self.dispatchEvent({type: "tw-dropHandled", param: null});
}
//else let the event fall thru
};
ItemWidget.prototype.handleDragOverEvent = function(event) {
//alert("OVER")
// Tell the browser that we're still interested in the drop
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
};
ItemWidget.prototype.importDataTypes = [
{type: "text/vnd.tiddler", IECompatible: false, convertToFields: function(data) {
return JSON.parse(data);
}},
{type: "URL", IECompatible: true, convertToFields: function(data) {
// Check for tiddler data URI
var match = decodeURIComponent(data).match(/^data\:text\/vnd\.tiddler,(.*)/i);
if(match) {
return JSON.parse(match[1]);
} else {
return { // As URL string
text: data
};
}
}},
{type: "text/x-moz-url", IECompatible: false, convertToFields: function(data) {
// Check for tiddler data URI
var match = decodeURIComponent(data).match(/^data\:text\/vnd\.tiddler,(.*)/i);
if(match) {
return JSON.parse(match[1]);
} else {
return { // As URL string
text: data
};
}
}},
{type: "text/plain", IECompatible: false, convertToFields: function(data) {
return {
text: data
};
}},
{type: "Text", IECompatible: true, convertToFields: function(data) {
return {
text: data
};
}},
{type: "text/uri-list", IECompatible: false, convertToFields: function(data) {
return {
text: data
};
}}
];
ItemWidget.prototype.cancelAction =function(event) {
// Try each provided data type in turn
{
var self = this,
dataTransfer = event.dataTransfer;
event.preventDefault();
// Stop the drop ripple up to any parent handlers
event.stopPropagation();
};
};
ItemWidget.prototype.nameandOnListTag = function(dataTransfer) {
// Try each provided data type in turn
var self = this;
for(var t=0; t<this.importDataTypes.length; t++) {
if(!$tw.browser.isIE || this.importDataTypes[t].IECompatible) {
// Get the data
var dataType = this.importDataTypes[t];
var data = dataTransfer.getData(dataType.type);
// Import the tiddlers in the data
if(data !== "" && data !== null) {
var tiddlerFields = dataType.convertToFields(data);
if(!tiddlerFields.title) {
break;
}
return {name:tiddlerFields.title};
}
}
};
return {name:null, onList:false};
};
/*
Render this widget into the DOM
*/
ItemWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
var domNode = this.document.createElement("div");
// Add event handlers
$tw.utils.addEventListeners(this.parentDomNode,[
{name: "drop", handlerObject: this, handlerMethod: "handleDropEvent"},
{name: "dragover", handlerObject: this, handlerMethod: "handleDragOverEvent"},
]);
// Insert element
parent.insertBefore(domNode,nextSibling);
//if (!!this.parseTreeNode.itemTitle)
this.renderChildren(this.parentDomNode,null);//BJ may set this behavour as an option??
//else domNode.innerHTML='<img style="float:left;min-height:50px;min-width:50px;visibility:hidden;" />';
this.domNodes.push(domNode);
};
/*
Compute the internal state of the widget
*/
ItemWidget.prototype.execute = function() {
// Set the current list item title
if (!!this.parseTreeNode.itemTitle)
this.setVariable(this.parseTreeNode.variableName,this.parseTreeNode.itemTitle);
// Construct the child widgets
this.col =this.parseTreeNode.col;
this.row =this.parseTreeNode.row;
this.makeChildWidgets();
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ItemWidget.prototype.refresh = function(changedTiddlers) {
return this.refreshChildren(changedTiddlers);
};
exports.cellitem = ItemWidget;
})();
/*\
title: $:/plugins/bj/plugins/script/script.js
type: application/javascript
module-type: widget
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;
var ScriptWidget = function(parseTreeNode,options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
ScriptWidget.prototype = new Widget();
/*
Render this widget into the DOM
*/
ScriptWidget.prototype.render = function(parent,nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
// Create our element
var domNode = this.document.createElement("script");
if (this.id) domNode.setAttribute("id",this.id);
if (this.type) domNode.setAttribute("type",this.type);
var textNode = this.document.createTextNode(this.text);
domNode.insertBefore(textNode,nextSibling);
this.domNodes.push(textNode);
parent.insertBefore(domNode,null);
this.domNodes.push(domNode);
};
/*
Compute the internal state of the widget
*/
ScriptWidget.prototype.execute = function() {
// Get our parameters
var self = this;
this.source = this.getAttribute("source");
var tiddler = $tw.wiki.getTiddler(this.source);
if(tiddler) {
this.text = tiddler.fields.text;
this.id = tiddler.fields.id;
this.transcludeMode = tiddler.fields.transcludeMode;
this.type = tiddler.fields.type;
}
this.id = this.getAttribute("id")||this.id ;
this.transcludeMode = this.getAttribute("mode")||this.transcludeMode;
this.type = this.getAttribute("type")||this.type;
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ScriptWidget.prototype.refresh = function(changedTiddlers) {
var changedAttributes = this.computeAttributes();
if((Object.keys(changedAttributes).length) || changedTiddlers[this.source]) {
this.refreshSelf();
return true;
} else {
return false;
}
};
exports.script1 = ScriptWidget;
})();
/*\
title: $:/plugins/bj/plugins/script/scriptmacro.js
type: application/javascript
module-type: macro
*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "script";
exports.params = [
{name: "source"},{name: "esc"}
];
/*
Run the macro
*/
exports.run = function(source,esc) {
var text,id,transcludeMode,type,returns="<script ";
var tiddler = $tw.wiki.getTiddler(source);
if(tiddler) {
text = tiddler.fields.text;
id = tiddler.fields.id;
type = tiddler.fields.type;
}
returns += id ? 'id="'+id+'" ':'';
returns += type ? 'type="'+type+'" ' : "";
returns += '>';
returns += text ? text : "";
returns += '</script>';
if (esc) returns = "`"+returns+"`";
return returns;
};
})();
The MIT License (MIT)
Copyright (c) 2014 Jeffrey Wikinson aka buggyj
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\define openAllTaggedInner(state)
<$button set=<<qualify "$state$">> setTo="open">Open all tagged</$button>
<$edit-text tiddler="<<qualify $(usertagopen)$>>" tag="input" type="text"/>
<$list filter="""[!has[draft.of]tag{<<qualify $(usertagopen)$>>}sort[created]]""">
<$link><$click type="match" state=<<qualify "$state$">> text="open"/> </$link>
</$list>
\end
\define openAllTagged(userparam:"$:/temp/openall" state:"$:/state/opentagged" )
<$set name="usertagopen" value=<<qualify "$userparam$">>>
<<openAllTaggedInner $state$>>
\end
\define closeAllTaggedInner( state:"$:/state/closetagged" )
<$button set=<<qualify "$state$">> setTo="close">close all tagged</$button>
<$edit-text tiddler="<<qualify $(usertagclose)$>>" tag="input" type="text"/>
<$linkcatcher message=tm-close-tiddler>
<$list filter="""[!has[draft.of]tag{<<qualify $(usertagclose)$>>}sort[created]]""">
<$link><$click type="match" state=<<qualify "$state$">> text="close"/> </$link>
</$list>
</$linkcatcher>
\end
\define closeAllTagged(userparam:"$:/temp/closeeall" state:"$:/state/closetagged" )
<$set name="usertagclose" value=<<qualify "$userparam$">>>
<<closeAllTaggedInner $state$>>
\end
!!The Click Widget
watches for writes to tiddler specified in 'state' and clicks when the it sees the contents matches that specified by'text'
!!Usage
can be used to click all items on a list
!!Example open all tiddlers with the same tag:
`
<$button set=<<qualify "$:/state">> setTo="open">Open all tagged</$button>
<$edit-text tiddler="$:/temp/openall" tag="input" type="text"/>
<$list filter="[!has[draft.of]tag{$:/temp/openall}sort[created]]">
<$link><$click state=<<qualify "$:/state">> text="open"/> </$link>
</$list>
`
.CodeMirror-dialog {
position: absolute;
left: 0; right: 0;
background: white;
z-index: 15;
padding: .1em .8em;
overflow: hidden;
color: #333;
}
.CodeMirror-dialog-top {
border-bottom: 1px solid #eee;
top: 0;
}
.CodeMirror-dialog-bottom {
border-top: 1px solid #eee;
bottom: 0;
}
.CodeMirror-dialog input {
border: none;
outline: none;
background: transparent;
width: 20em;
color: inherit;
font-family: monospace;
}
.CodeMirror-dialog button {
font-size: 70%;
}
// Open simple dialogs on top of an editor. Relies on dialog.css.
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
function dialogDiv(cm, template, bottom) {
var wrap = cm.getWrapperElement();
var dialog;
dialog = wrap.appendChild(document.createElement("div"));
if (bottom) {
dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
} else {
dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
}
if (typeof template == "string") {
dialog.innerHTML = template;
} else { // Assuming it's a detached DOM element.
dialog.appendChild(template);
}
return dialog;
}
function closeNotification(cm, newVal) {
if (cm.state.currentNotificationClose)
cm.state.currentNotificationClose();
cm.state.currentNotificationClose = newVal;
}
CodeMirror.defineExtension("openDialog", function(template, callback, options) {
closeNotification(this, null);
var dialog = dialogDiv(this, template, options && options.bottom);
var closed = false, me = this;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
}
var inp = dialog.getElementsByTagName("input")[0], button;
if (inp) {
if (options && options.value) inp.value = options.value;
CodeMirror.on(inp, "keydown", function(e) {
if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
if (e.keyCode == 13 || e.keyCode == 27) {
inp.blur();
CodeMirror.e_stop(e);
close();
me.focus();
if (e.keyCode == 13) callback(inp.value);
}
});
if (options && options.onKeyUp) {
CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
}
if (options && options.value) inp.value = options.value;
inp.focus();
CodeMirror.on(inp, "blur", close);
} else if (button = dialog.getElementsByTagName("button")[0]) {
CodeMirror.on(button, "click", function() {
close();
me.focus();
});
button.focus();
CodeMirror.on(button, "blur", close);
}
return close;
});
CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
closeNotification(this, null);
var dialog = dialogDiv(this, template, options && options.bottom);
var buttons = dialog.getElementsByTagName("button");
var closed = false, me = this, blurring = 1;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
me.focus();
}
buttons[0].focus();
for (var i = 0; i < buttons.length; ++i) {
var b = buttons[i];
(function(callback) {
CodeMirror.on(b, "click", function(e) {
CodeMirror.e_preventDefault(e);
close();
if (callback) callback(me);
});
})(callbacks[i]);
CodeMirror.on(b, "blur", function() {
--blurring;
setTimeout(function() { if (blurring <= 0) close(); }, 200);
});
CodeMirror.on(b, "focus", function() { ++blurring; });
}
});
/*
* openNotification
* Opens a notification, that can be closed with an optional timer
* (default 5000ms timer) and always closes on click.
*
* If a notification is opened while another is opened, it will close the
* currently opened one and open the new one immediately.
*/
CodeMirror.defineExtension("openNotification", function(template, options) {
closeNotification(this, close);
var dialog = dialogDiv(this, template, options && options.bottom);
var duration = options && (options.duration === undefined ? 5000 : options.duration);
var closed = false, doneTimer;
function close() {
if (closed) return;
closed = true;
clearTimeout(doneTimer);
dialog.parentNode.removeChild(dialog);
}
CodeMirror.on(dialog, 'click', function(e) {
CodeMirror.e_preventDefault(e);
close();
});
if (duration)
doneTimer = setTimeout(close, options.duration);
});
});
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
(document.documentMode == null || document.documentMode < 8);
var Pos = CodeMirror.Pos;
var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
function findMatchingBracket(cm, where, strict, config) {
var line = cm.getLineHandle(where.line), pos = where.ch - 1;
var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
if (!match) return null;
var dir = match.charAt(1) == ">" ? 1 : -1;
if (strict && (dir > 0) != (pos == where.ch)) return null;
var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
if (found == null) return null;
return {from: Pos(where.line, pos), to: found && found.pos,
match: found && found.ch == match.charAt(0), forward: dir > 0};
}
// bracketRegex is used to specify which type of bracket to scan
// should be a regexp, e.g. /[[\]]/
//
// Note: If "where" is on an open bracket, then this bracket is ignored.
//
// Returns false when no bracket was found, null when it reached
// maxScanLines and gave up
function scanForBracket(cm, where, dir, style, config) {
var maxScanLen = (config && config.maxScanLineLength) || 10000;
var maxScanLines = (config && config.maxScanLines) || 1000;
var stack = [];
var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/;
var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
: Math.max(cm.firstLine() - 1, where.line - maxScanLines);
for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
var line = cm.getLine(lineNo);
if (!line) continue;
var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
if (line.length > maxScanLen) continue;
if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
for (; pos != end; pos += dir) {
var ch = line.charAt(pos);
if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
var match = matching[ch];
if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
else stack.pop();
}
}
}
return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
}
function matchBrackets(cm, autoclear, config) {
// Disable brace matching in long lines, since it'll cause hugely slow updates
var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
var marks = [], ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config);
if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
}
}
if (marks.length) {
// Kludge to work around the IE bug from issue #1193, where text
// input stops going to the textare whever this fires.
if (ie_lt8 && cm.state.focused) cm.display.input.focus();
var clear = function() {
cm.operation(function() {
for (var i = 0; i < marks.length; i++) marks[i].clear();
});
};
if (autoclear) setTimeout(clear, 800);
else return clear;
}
}
var currentlyHighlighted = null;
function doMatchBrackets(cm) {
cm.operation(function() {
if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
});
}
CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
if (old && old != CodeMirror.Init)
cm.off("cursorActivity", doMatchBrackets);
if (val) {
cm.state.matchBrackets = typeof val == "object" ? val : {};
cm.on("cursorActivity", doMatchBrackets);
}
});
CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){
return findMatchingBracket(this, pos, strict, config);
});
CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
return scanForBracket(this, pos, dir, style, config);
});
});
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var Pos = CodeMirror.Pos;
function SearchCursor(doc, query, pos, caseFold) {
this.atOccurrence = false; this.doc = doc;
if (caseFold == null && typeof query == "string") caseFold = false;
pos = pos ? doc.clipPos(pos) : Pos(0, 0);
this.pos = {from: pos, to: pos};
// The matches method is filled in based on the type of query.
// It takes a position and a direction, and returns an object
// describing the next occurrence of the query, or null if no
// more matches were found.
if (typeof query != "string") { // Regexp match
if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
this.matches = function(reverse, pos) {
if (reverse) {
query.lastIndex = 0;
var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
for (;;) {
query.lastIndex = cutOff;
var newMatch = query.exec(line);
if (!newMatch) break;
match = newMatch;
start = match.index;
cutOff = match.index + (match[0].length || 1);
if (cutOff == line.length) break;
}
var matchLen = (match && match[0].length) || 0;
if (!matchLen) {
if (start == 0 && line.length == 0) {match = undefined;}
else if (start != doc.getLine(pos.line).length) {
matchLen++;
}
}
} else {
query.lastIndex = pos.ch;
var line = doc.getLine(pos.line), match = query.exec(line);
var matchLen = (match && match[0].length) || 0;
var start = match && match.index;
if (start + matchLen != line.length && !matchLen) matchLen = 1;
}
if (match && matchLen)
return {from: Pos(pos.line, start),
to: Pos(pos.line, start + matchLen),
match: match};
};
} else { // String query
var origQuery = query;
if (caseFold) query = query.toLowerCase();
var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
var target = query.split("\n");
// Different methods for single-line and multi-line queries
if (target.length == 1) {
if (!query.length) {
// Empty string would match anything and never progress, so
// we define it to match nothing instead.
this.matches = function() {};
} else {
this.matches = function(reverse, pos) {
if (reverse) {
var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig);
var match = line.lastIndexOf(query);
if (match > -1) {
match = adjustPos(orig, line, match);
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
}
} else {
var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig);
var match = line.indexOf(query);
if (match > -1) {
match = adjustPos(orig, line, match) + pos.ch;
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
}
}
};
}
} else {
var origTarget = origQuery.split("\n");
this.matches = function(reverse, pos) {
var last = target.length - 1;
if (reverse) {
if (pos.line - (target.length - 1) < doc.firstLine()) return;
if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return;
var to = Pos(pos.line, origTarget[last].length);
for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln)
if (target[i] != fold(doc.getLine(ln))) return;
var line = doc.getLine(ln), cut = line.length - origTarget[0].length;
if (fold(line.slice(cut)) != target[0]) return;
return {from: Pos(ln, cut), to: to};
} else {
if (pos.line + (target.length - 1) > doc.lastLine()) return;
var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length;
if (fold(line.slice(cut)) != target[0]) return;
var from = Pos(pos.line, cut);
for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln)
if (target[i] != fold(doc.getLine(ln))) return;
if (doc.getLine(ln).slice(0, origTarget[last].length) != target[last]) return;
return {from: from, to: Pos(ln, origTarget[last].length)};
}
};
}
}
}
SearchCursor.prototype = {
findNext: function() {return this.find(false);},
findPrevious: function() {return this.find(true);},
find: function(reverse) {
var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
function savePosAndFail(line) {
var pos = Pos(line, 0);
self.pos = {from: pos, to: pos};
self.atOccurrence = false;
return false;
}
for (;;) {
if (this.pos = this.matches(reverse, pos)) {
this.atOccurrence = true;
return this.pos.match || true;
}
if (reverse) {
if (!pos.line) return savePosAndFail(0);
pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
}
else {
var maxLine = this.doc.lineCount();
if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
pos = Pos(pos.line + 1, 0);
}
}
},
from: function() {if (this.atOccurrence) return this.pos.from;},
to: function() {if (this.atOccurrence) return this.pos.to;},
replace: function(newText) {
if (!this.atOccurrence) return;
var lines = CodeMirror.splitLines(newText);
this.doc.replaceRange(lines, this.pos.from, this.pos.to);
this.pos.to = Pos(this.pos.from.line + lines.length - 1,
lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
}
};
// Maps a position in a case-folded line back to a position in the original line
// (compensating for codepoints increasing in number during folding)
function adjustPos(orig, folded, pos) {
if (orig.length == folded.length) return pos;
for (var pos1 = Math.min(pos, orig.length);;) {
var len1 = orig.slice(0, pos1).toLowerCase().length;
if (len1 < pos) ++pos1;
else if (len1 > pos) --pos1;
else return pos1;
}
}
CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this.doc, query, pos, caseFold);
});
CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this, query, pos, caseFold);
});
CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
var ranges = [], next;
var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold);
while (next = cur.findNext()) {
if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break;
ranges.push({anchor: cur.from(), head: cur.to()});
}
if (ranges.length)
this.setSelections(ranges, 0);
});
});
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var Pos = CodeMirror.Pos;
function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
// Kill 'ring'
var killRing = [];
function addToRing(str) {
killRing.push(str);
if (killRing.length > 50) killRing.shift();
}
function growRingTop(str) {
if (!killRing.length) return addToRing(str);
killRing[killRing.length - 1] += str;
}
function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; }
function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }
var lastKill = null;
function kill(cm, from, to, mayGrow, text) {
if (text == null) text = cm.getRange(from, to);
if (mayGrow && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen))
growRingTop(text);
else
addToRing(text);
cm.replaceRange("", from, to, "+delete");
if (mayGrow) lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()};
else lastKill = null;
}
// Boundaries of various units
function byChar(cm, pos, dir) {
return cm.findPosH(pos, dir, "char", true);
}
function byWord(cm, pos, dir) {
return cm.findPosH(pos, dir, "word", true);
}
function byLine(cm, pos, dir) {
return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn);
}
function byPage(cm, pos, dir) {
return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn);
}
function byParagraph(cm, pos, dir) {
var no = pos.line, line = cm.getLine(no);
var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch));
var fst = cm.firstLine(), lst = cm.lastLine();
for (;;) {
no += dir;
if (no < fst || no > lst)
return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null));
line = cm.getLine(no);
var hasText = /\S/.test(line);
if (hasText) sawText = true;
else if (sawText) return Pos(no, 0);
}
}
function bySentence(cm, pos, dir) {
var line = pos.line, ch = pos.ch;
var text = cm.getLine(pos.line), sawWord = false;
for (;;) {
var next = text.charAt(ch + (dir < 0 ? -1 : 0));
if (!next) { // End/beginning of line reached
if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
text = cm.getLine(line + dir);
if (!/\S/.test(text)) return Pos(line, ch);
line += dir;
ch = dir < 0 ? text.length : 0;
continue;
}
if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0));
if (!sawWord) sawWord = /\w/.test(next);
ch += dir;
}
}
function byExpr(cm, pos, dir) {
var wrap;
if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, true))
&& wrap.match && (wrap.forward ? 1 : -1) == dir)
return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to;
for (var first = true;; first = false) {
var token = cm.getTokenAt(pos);
var after = Pos(pos.line, dir < 0 ? token.start : token.end);
if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) {
var newPos = cm.findPosH(after, dir, "char");
if (posEq(after, newPos)) return pos;
else pos = newPos;
} else {
return after;
}
}
}
// Prefixes (only crudely supported)
function getPrefix(cm, precise) {
var digits = cm.state.emacsPrefix;
if (!digits) return precise ? null : 1;
clearPrefix(cm);
return digits == "-" ? -1 : Number(digits);
}
function repeated(cmd) {
var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd;
return function(cm) {
var prefix = getPrefix(cm);
f(cm);
for (var i = 1; i < prefix; ++i) f(cm);
};
}
function findEnd(cm, by, dir) {
var pos = cm.getCursor(), prefix = getPrefix(cm);
if (prefix < 0) { dir = -dir; prefix = -prefix; }
for (var i = 0; i < prefix; ++i) {
var newPos = by(cm, pos, dir);
if (posEq(newPos, pos)) break;
pos = newPos;
}
return pos;
}
function move(by, dir) {
var f = function(cm) {
cm.extendSelection(findEnd(cm, by, dir));
};
f.motion = true;
return f;
}
function killTo(cm, by, dir) {
kill(cm, cm.getCursor(), findEnd(cm, by, dir), true);
}
function addPrefix(cm, digit) {
if (cm.state.emacsPrefix) {
if (digit != "-") cm.state.emacsPrefix += digit;
return;
}
// Not active yet
cm.state.emacsPrefix = digit;
cm.on("keyHandled", maybeClearPrefix);
cm.on("inputRead", maybeDuplicateInput);
}
var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true};
function maybeClearPrefix(cm, arg) {
if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
clearPrefix(cm);
}
function clearPrefix(cm) {
cm.state.emacsPrefix = null;
cm.off("keyHandled", maybeClearPrefix);
cm.off("inputRead", maybeDuplicateInput);
}
function maybeDuplicateInput(cm, event) {
var dup = getPrefix(cm);
if (dup > 1 && event.origin == "+input") {
var one = event.text.join("\n"), txt = "";
for (var i = 1; i < dup; ++i) txt += one;
cm.replaceSelection(txt);
}
}
function addPrefixMap(cm) {
cm.state.emacsPrefixMap = true;
cm.addKeyMap(prefixMap);
cm.on("keyHandled", maybeRemovePrefixMap);
cm.on("inputRead", maybeRemovePrefixMap);
}
function maybeRemovePrefixMap(cm, arg) {
if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
cm.removeKeyMap(prefixMap);
cm.state.emacsPrefixMap = false;
cm.off("keyHandled", maybeRemovePrefixMap);
cm.off("inputRead", maybeRemovePrefixMap);
}
// Utilities
function setMark(cm) {
cm.setCursor(cm.getCursor());
cm.setExtending(!cm.getExtending());
cm.on("change", function() { cm.setExtending(false); });
}
function clearMark(cm) {
cm.setExtending(false);
cm.setCursor(cm.getCursor());
}
function getInput(cm, msg, f) {
if (cm.openDialog)
cm.openDialog(msg + ": <input type=\"text\" style=\"width: 10em\"/>", f, {bottom: true});
else
f(prompt(msg, ""));
}
function operateOnWord(cm, op) {
var start = cm.getCursor(), end = cm.findPosH(start, 1, "word");
cm.replaceRange(op(cm.getRange(start, end)), start, end);
cm.setCursor(end);
}
function toEnclosingExpr(cm) {
var pos = cm.getCursor(), line = pos.line, ch = pos.ch;
var stack = [];
while (line >= cm.firstLine()) {
var text = cm.getLine(line);
for (var i = ch == null ? text.length : ch; i > 0;) {
var ch = text.charAt(--i);
if (ch == ")")
stack.push("(");
else if (ch == "]")
stack.push("[");
else if (ch == "}")
stack.push("{");
else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch))
return cm.extendSelection(Pos(line, i));
}
--line; ch = null;
}
}
function quit(cm) {
cm.execCommand("clearSearch");
clearMark(cm);
}
// Actual keymap
var keyMap = CodeMirror.keyMap.emacs = {
"Ctrl-W": function(cm) {kill(cm, cm.getCursor("start"), cm.getCursor("end"));},
"Ctrl-K": repeated(function(cm) {
var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));
var text = cm.getRange(start, end);
if (!/\S/.test(text)) {
text += "\n";
end = Pos(start.line + 1, 0);
}
kill(cm, start, end, true, text);
}),
"Alt-W": function(cm) {
addToRing(cm.getSelection());
clearMark(cm);
},
"Ctrl-Y": function(cm) {
var start = cm.getCursor();
cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste");
cm.setSelection(start, cm.getCursor());
},
"Alt-Y": function(cm) {cm.replaceSelection(popFromRing(), "around", "paste");},
"Ctrl-Space": setMark, "Ctrl-Shift-2": setMark,
"Ctrl-F": move(byChar, 1), "Ctrl-B": move(byChar, -1),
"Right": move(byChar, 1), "Left": move(byChar, -1),
"Ctrl-D": function(cm) { killTo(cm, byChar, 1); },
"Delete": function(cm) { killTo(cm, byChar, 1); },
"Ctrl-H": function(cm) { killTo(cm, byChar, -1); },
"Backspace": function(cm) { killTo(cm, byChar, -1); },
"Alt-F": move(byWord, 1), "Alt-B": move(byWord, -1),
"Alt-D": function(cm) { killTo(cm, byWord, 1); },
"Alt-Backspace": function(cm) { killTo(cm, byWord, -1); },
"Ctrl-N": move(byLine, 1), "Ctrl-P": move(byLine, -1),
"Down": move(byLine, 1), "Up": move(byLine, -1),
"Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
"End": "goLineEnd", "Home": "goLineStart",
"Alt-V": move(byPage, -1), "Ctrl-V": move(byPage, 1),
"PageUp": move(byPage, -1), "PageDown": move(byPage, 1),
"Ctrl-Up": move(byParagraph, -1), "Ctrl-Down": move(byParagraph, 1),
"Alt-A": move(bySentence, -1), "Alt-E": move(bySentence, 1),
"Alt-K": function(cm) { killTo(cm, bySentence, 1); },
"Ctrl-Alt-K": function(cm) { killTo(cm, byExpr, 1); },
"Ctrl-Alt-Backspace": function(cm) { killTo(cm, byExpr, -1); },
"Ctrl-Alt-F": move(byExpr, 1), "Ctrl-Alt-B": move(byExpr, -1),
"Shift-Ctrl-Alt-2": function(cm) {
cm.setSelection(findEnd(cm, byExpr, 1), cm.getCursor());
},
"Ctrl-Alt-T": function(cm) {
var leftStart = byExpr(cm, cm.getCursor(), -1), leftEnd = byExpr(cm, leftStart, 1);
var rightEnd = byExpr(cm, leftEnd, 1), rightStart = byExpr(cm, rightEnd, -1);
cm.replaceRange(cm.getRange(rightStart, rightEnd) + cm.getRange(leftEnd, rightStart) +
cm.getRange(leftStart, leftEnd), leftStart, rightEnd);
},
"Ctrl-Alt-U": repeated(toEnclosingExpr),
"Alt-Space": function(cm) {
var pos = cm.getCursor(), from = pos.ch, to = pos.ch, text = cm.getLine(pos.line);
while (from && /\s/.test(text.charAt(from - 1))) --from;
while (to < text.length && /\s/.test(text.charAt(to))) ++to;
cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to));
},
"Ctrl-O": repeated(function(cm) { cm.replaceSelection("\n", "start"); }),
"Ctrl-T": repeated(function(cm) {
cm.execCommand("transposeChars");
}),
"Alt-C": repeated(function(cm) {
operateOnWord(cm, function(w) {
var letter = w.search(/\w/);
if (letter == -1) return w;
return w.slice(0, letter) + w.charAt(letter).toUpperCase() + w.slice(letter + 1).toLowerCase();
});
}),
"Alt-U": repeated(function(cm) {
operateOnWord(cm, function(w) { return w.toUpperCase(); });
}),
"Alt-L": repeated(function(cm) {
operateOnWord(cm, function(w) { return w.toLowerCase(); });
}),
"Alt-;": "toggleComment",
"Ctrl-/": repeated("undo"), "Shift-Ctrl--": repeated("undo"),
"Ctrl-Z": repeated("undo"), "Cmd-Z": repeated("undo"),
"Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd",
"Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": quit, "Shift-Alt-5": "replace",
"Alt-/": "autocomplete",
"Ctrl-J": "newlineAndIndent", "Enter": false, "Tab": "indentAuto",
"Alt-G": function(cm) {cm.setOption("keyMap", "emacs-Alt-G");},
"Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");},
"Ctrl-Q": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-Q");},
"Ctrl-U": addPrefixMap
};
CodeMirror.keyMap["emacs-Ctrl-X"] = {
"Tab": function(cm) {
cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
},
"Ctrl-X": function(cm) {
cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
},
"Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": repeated("undo"), "K": "close",
"Delete": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), true); },
auto: "emacs", nofallthrough: true, disableInput: true
};
CodeMirror.keyMap["emacs-Alt-G"] = {
"G": function(cm) {
var prefix = getPrefix(cm, true);
if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);
getInput(cm, "Goto line", function(str) {
var num;
if (str && !isNaN(num = Number(str)) && num == num|0 && num > 0)
cm.setCursor(num - 1);
});
},
auto: "emacs", nofallthrough: true, disableInput: true
};
CodeMirror.keyMap["emacs-Ctrl-Q"] = {
"Tab": repeated("insertTab"),
auto: "emacs", nofallthrough: true
};
var prefixMap = {"Ctrl-G": clearPrefix};
function regPrefix(d) {
prefixMap[d] = function(cm) { addPrefix(cm, d); };
keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); };
prefixPreservingKeys["Ctrl-" + d] = true;
}
for (var i = 0; i < 10; ++i) regPrefix(String(i));
regPrefix("-");
});
// A rough approximation of Sublime Text's keybindings
// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets"));
else if (typeof define == "function" && define.amd) // AMD
define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var map = CodeMirror.keyMap.sublime = {fallthrough: "default"};
var cmds = CodeMirror.commands;
var Pos = CodeMirror.Pos;
var ctrl = CodeMirror.keyMap["default"] == CodeMirror.keyMap.pcDefault ? "Ctrl-" : "Cmd-";
// This is not exactly Sublime's algorithm. I couldn't make heads or tails of that.
function findPosSubword(doc, start, dir) {
if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));
var line = doc.getLine(start.line);
if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));
var state = "start", type;
for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {
var next = line.charAt(dir < 0 ? pos - 1 : pos);
var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o";
if (cat == "w" && next.toUpperCase() == next) cat = "W";
if (state == "start") {
if (cat != "o") { state = "in"; type = cat; }
} else if (state == "in") {
if (type != cat) {
if (type == "w" && cat == "W" && dir < 0) pos--;
if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; }
break;
}
}
}
return Pos(start.line, pos);
}
function moveSubword(cm, dir) {
cm.extendSelectionsBy(function(range) {
if (cm.display.shift || cm.doc.extend || range.empty())
return findPosSubword(cm.doc, range.head, dir);
else
return dir < 0 ? range.from() : range.to();
});
}
cmds[map["Alt-Left"] = "goSubwordLeft"] = function(cm) { moveSubword(cm, -1); };
cmds[map["Alt-Right"] = "goSubwordRight"] = function(cm) { moveSubword(cm, 1); };
cmds[map[ctrl + "Up"] = "scrollLineUp"] = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local");
if (cm.getCursor().line >= visibleBottomLine)
cm.execCommand("goLineUp");
}
cm.scrollTo(null, info.top - cm.defaultTextHeight());
};
cmds[map[ctrl + "Down"] = "scrollLineDown"] = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleTopLine = cm.lineAtHeight(info.top, "local")+1;
if (cm.getCursor().line <= visibleTopLine)
cm.execCommand("goLineDown");
}
cm.scrollTo(null, info.top + cm.defaultTextHeight());
};
cmds[map["Shift-" + ctrl + "L"] = "splitSelectionByLine"] = function(cm) {
var ranges = cm.listSelections(), lineRanges = [];
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
for (var line = from.line; line <= to.line; ++line)
if (!(to.line > from.line && line == to.line && to.ch == 0))
lineRanges.push({anchor: line == from.line ? from : Pos(line, 0),
head: line == to.line ? to : Pos(line)});
}
cm.setSelections(lineRanges, 0);
};
map["Shift-Tab"] = "indentLess";
cmds[map["Esc"] = "singleSelectionTop"] = function(cm) {
var range = cm.listSelections()[0];
cm.setSelection(range.anchor, range.head, {scroll: false});
};
cmds[map[ctrl + "L"] = "selectLine"] = function(cm) {
var ranges = cm.listSelections(), extended = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
extended.push({anchor: Pos(range.from().line, 0),
head: Pos(range.to().line + 1, 0)});
}
cm.setSelections(extended);
};
map["Shift-" + ctrl + "K"] = "deleteLine";
function insertLine(cm, above) {
cm.operation(function() {
var len = cm.listSelections().length, newSelection = [], last = -1;
for (var i = 0; i < len; i++) {
var head = cm.listSelections()[i].head;
if (head.line <= last) continue;
var at = Pos(head.line + (above ? 0 : 1), 0);
cm.replaceRange("\n", at, null, "+insertLine");
cm.indentLine(at.line, null, true);
newSelection.push({head: at, anchor: at});
last = head.line + 1;
}
cm.setSelections(newSelection);
});
}
cmds[map[ctrl + "Enter"] = "insertLineAfter"] = function(cm) { insertLine(cm, false); };
cmds[map["Shift-" + ctrl + "Enter"] = "insertLineBefore"] = function(cm) { insertLine(cm, true); };
function wordAt(cm, pos) {
var start = pos.ch, end = start, line = cm.getLine(pos.line);
while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;
while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;
return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};
}
cmds[map[ctrl + "D"] = "selectNextOccurrence"] = function(cm) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel;
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
cm.setSelection(word.from, word.to);
fullWord = true;
} else {
var text = cm.getRange(from, to);
var query = fullWord ? new RegExp("\\b" + text + "\\b") : text;
var cur = cm.getSearchCursor(query, to);
if (cur.findNext()) {
cm.addSelection(cur.from(), cur.to());
} else {
cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0));
if (cur.findNext())
cm.addSelection(cur.from(), cur.to());
}
}
if (fullWord)
cm.state.sublimeFindFullWord = cm.doc.sel;
};
var mirror = "(){}[]";
function selectBetweenBrackets(cm) {
var pos = cm.getCursor(), opening = cm.scanForBracket(pos, -1);
if (!opening) return;
for (;;) {
var closing = cm.scanForBracket(pos, 1);
if (!closing) return;
if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
cm.setSelection(Pos(opening.pos.line, opening.pos.ch + 1), closing.pos, false);
return true;
}
pos = Pos(closing.pos.line, closing.pos.ch + 1);
}
}
cmds[map["Shift-" + ctrl + "Space"] = "selectScope"] = function(cm) {
selectBetweenBrackets(cm) || cm.execCommand("selectAll");
};
cmds[map["Shift-" + ctrl + "M"] = "selectBetweenBrackets"] = function(cm) {
if (!selectBetweenBrackets(cm)) return CodeMirror.Pass;
};
cmds[map[ctrl + "M"] = "goToBracket"] = function(cm) {
cm.extendSelectionsBy(function(range) {
var next = cm.scanForBracket(range.head, 1);
if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos;
var prev = cm.scanForBracket(range.head, -1);
return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head;
});
};
cmds[map["Shift-" + ctrl + "Up"] = "swapLineUp"] = function(cm) {
var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from().line - 1, to = range.to().line;
if (from > at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = 0; i < linesToMove.length; i += 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
if (to > cm.lastLine()) {
cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");
var sels = cm.listSelections(), last = sels[sels.length - 1];
var head = last.head.line == to ? Pos(to - 1) : last.head;
var anchor = last.anchor.line == to ? Pos(to - 1) : last.anchor;
cm.setSelections(sels.slice(0, sels.length - 1).concat([{head: head, anchor: anchor}]));
} else {
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
}
cm.scrollIntoView();
});
};
cmds[map["Shift-" + ctrl + "Down"] = "swapLineDown"] = function(cm) {
var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1;
for (var i = ranges.length - 1; i >= 0; i--) {
var range = ranges[i], from = range.to().line + 1, to = range.from().line;
if (from < at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = linesToMove.length - 2; i >= 0; i -= 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
if (from == cm.lastLine())
cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine");
else
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
cm.scrollIntoView();
});
};
map[ctrl + "/"] = "toggleComment";
cmds[map[ctrl + "J"] = "joinLines"] = function(cm) {
var ranges = cm.listSelections(), joined = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from();
var start = from.line, end = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == end)
end = ranges[++i].to().line;
joined.push({start: start, end: end, anchor: !range.empty() && from});
}
cm.operation(function() {
var offset = 0, ranges = [];
for (var i = 0; i < joined.length; i++) {
var obj = joined[i];
var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head;
for (var line = obj.start; line <= obj.end; line++) {
var actual = line - offset;
if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1);
if (actual < cm.lastLine()) {
cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length));
++offset;
}
}
ranges.push({anchor: anchor || head, head: head});
}
cm.setSelections(ranges, 0);
});
};
cmds[map["Shift-" + ctrl + "D"] = "duplicateLine"] = function(cm) {
cm.operation(function() {
var rangeCount = cm.listSelections().length;
for (var i = 0; i < rangeCount; i++) {
var range = cm.listSelections()[i];
if (range.empty())
cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));
else
cm.replaceRange(cm.getRange(range.from(), range.to()), range.from());
}
cm.scrollIntoView();
});
};
map[ctrl + "T"] = "transposeChars";
function sortLines(cm, caseSensitive) {
var ranges = cm.listSelections(), toSort = [], selected;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) continue;
var from = range.from().line, to = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == to)
to = range[++i].to().line;
toSort.push(from, to);
}
if (toSort.length) selected = true;
else toSort.push(cm.firstLine(), cm.lastLine());
cm.operation(function() {
var ranges = [];
for (var i = 0; i < toSort.length; i += 2) {
var from = toSort[i], to = toSort[i + 1];
var start = Pos(from, 0), end = Pos(to);
var lines = cm.getRange(start, end, false);
if (caseSensitive)
lines.sort();
else
lines.sort(function(a, b) {
var au = a.toUpperCase(), bu = b.toUpperCase();
if (au != bu) { a = au; b = bu; }
return a < b ? -1 : a == b ? 0 : 1;
});
cm.replaceRange(lines, start, end);
if (selected) ranges.push({anchor: start, head: end});
}
if (selected) cm.setSelections(ranges, 0);
});
}
cmds[map["F9"] = "sortLines"] = function(cm) { sortLines(cm, true); };
cmds[map[ctrl + "F9"] = "sortLinesInsensitive"] = function(cm) { sortLines(cm, false); };
cmds[map["F2"] = "nextBookmark"] = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
var current = marks.shift();
var found = current.find();
if (found) {
marks.push(current);
return cm.setSelection(found.from, found.to);
}
}
};
cmds[map["Shift-F2"] = "prevBookmark"] = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
marks.unshift(marks.pop());
var found = marks[marks.length - 1].find();
if (!found)
marks.pop();
else
return cm.setSelection(found.from, found.to);
}
};
cmds[map[ctrl + "F2"] = "toggleBookmark"] = function(cm) {
var ranges = cm.listSelections();
var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []);
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
var found = cm.findMarks(from, to);
for (var j = 0; j < found.length; j++) {
if (found[j].sublimeBookmark) {
found[j].clear();
for (var k = 0; k < marks.length; k++)
if (marks[k] == found[j])
marks.splice(k--, 1);
break;
}
}
if (j == found.length)
marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false}));
}
};
cmds[map["Shift-" + ctrl + "F2"] = "clearBookmarks"] = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();
marks.length = 0;
};
cmds[map["Alt-F2"] = "selectBookmarks"] = function(cm) {
var marks = cm.state.sublimeBookmarks, ranges = [];
if (marks) for (var i = 0; i < marks.length; i++) {
var found = marks[i].find();
if (!found)
marks.splice(i--, 0);
else
ranges.push({anchor: found.from, head: found.to});
}
if (ranges.length)
cm.setSelections(ranges, 0);
};
map["Alt-Q"] = "wrapLines";
var mapK = CodeMirror.keyMap["sublime-Ctrl-K"] = {auto: "sublime", nofallthrough: true};
map[ctrl + "K"] = function(cm) {cm.setOption("keyMap", "sublime-Ctrl-K");};
function modifyWordOrSelection(cm, mod) {
cm.operation(function() {
var ranges = cm.listSelections(), indices = [], replacements = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) { indices.push(i); replacements.push(""); }
else replacements.push(mod(cm.getRange(range.from(), range.to())));
}
cm.replaceSelections(replacements, "around", "case");
for (var i = indices.length - 1, at; i >= 0; i--) {
var range = ranges[indices[i]];
if (at && CodeMirror.cmpPos(range.head, at) > 0) continue;
var word = wordAt(cm, range.head);
at = word.from;
cm.replaceRange(mod(word.word), word.from, word.to);
}
});
}
mapK[ctrl + "Backspace"] = "delLineLeft";
cmds[mapK[ctrl + "K"] = "delLineRight"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = ranges.length - 1; i >= 0; i--)
cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete");
cm.scrollIntoView();
});
};
cmds[mapK[ctrl + "U"] = "upcaseAtCursor"] = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });
};
cmds[mapK[ctrl + "L"] = "downcaseAtCursor"] = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });
};
cmds[mapK[ctrl + "Space"] = "setSublimeMark"] = function(cm) {
if (cm.state.sublimeMark) cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
};
cmds[mapK[ctrl + "A"] = "selectToSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) cm.setSelection(cm.getCursor(), found);
};
cmds[mapK[ctrl + "W"] = "deleteToSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
var from = cm.getCursor(), to = found;
if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; }
cm.state.sublimeKilled = cm.getRange(from, to);
cm.replaceRange("", from, to);
}
};
cmds[mapK[ctrl + "X"] = "swapWithSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
cm.setCursor(found);
}
};
cmds[mapK[ctrl + "Y"] = "sublimeYank"] = function(cm) {
if (cm.state.sublimeKilled != null)
cm.replaceSelection(cm.state.sublimeKilled, null, "paste");
};
mapK[ctrl + "G"] = "clearBookmarks";
cmds[mapK[ctrl + "C"] = "showInCenter"] = function(cm) {
var pos = cm.cursorCoords(null, "local");
cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);
};
cmds[map["Shift-Alt-Up"] = "selectLinesUpward"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.head.line > cm.firstLine())
cm.addSelection(Pos(range.head.line - 1, range.head.ch));
}
});
};
cmds[map["Shift-Alt-Down"] = "selectLinesDownward"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.head.line < cm.lastLine())
cm.addSelection(Pos(range.head.line + 1, range.head.ch));
}
});
};
function findAndGoTo(cm, forward) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
from = word.from;
to = word.to;
}
var query = cm.getRange(from, to);
var cur = cm.getSearchCursor(query, forward ? to : from);
if (forward ? cur.findNext() : cur.findPrevious()) {
cm.setSelection(cur.from(), cur.to());
} else {
cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0)
: cm.clipPos(Pos(cm.lastLine())));
if (forward ? cur.findNext() : cur.findPrevious())
cm.setSelection(cur.from(), cur.to());
else if (word)
cm.setSelection(from, to);
}
};
cmds[map[ctrl + "F3"] = "findUnder"] = function(cm) { findAndGoTo(cm, true); };
cmds[map["Shift-" + ctrl + "F3"] = "findUnderPrevious"] = function(cm) { findAndGoTo(cm,false); };
map["Shift-" + ctrl + "["] = "fold";
map["Shift-" + ctrl + "]"] = "unfold";
mapK[ctrl + "0"] = mapK[ctrl + "j"] = "unfoldAll";
map[ctrl + "I"] = "findIncremental";
map["Shift-" + ctrl + "I"] = "findIncrementalReverse";
map[ctrl + "H"] = "replace";
map["F3"] = "findNext";
map["Shift-F3"] = "findPrev";
});
/**
* Supported keybindings:
*
* Motion:
* h, j, k, l
* gj, gk
* e, E, w, W, b, B, ge, gE
* f<character>, F<character>, t<character>, T<character>
* $, ^, 0, -, +, _
* gg, G
* %
* '<character>, `<character>
*
* Operator:
* d, y, c
* dd, yy, cc
* g~, g~g~
* >, <, >>, <<
*
* Operator-Motion:
* x, X, D, Y, C, ~
*
* Action:
* a, i, s, A, I, S, o, O
* zz, z., z<CR>, zt, zb, z-
* J
* u, Ctrl-r
* m<character>
* r<character>
*
* Modes:
* ESC - leave insert mode, visual mode, and clear input state.
* Ctrl-[, Ctrl-c - same as ESC.
*
* Registers: unnamed, -, a-z, A-Z, 0-9
* (Does not respect the special case for number registers when delete
* operator is made with these commands: %, (, ), , /, ?, n, N, {, } )
* TODO: Implement the remaining registers.
* Marks: a-z, A-Z, and 0-9
* TODO: Implement the remaining special marks. They have more complex
* behavior.
*
* Events:
* 'vim-mode-change' - raised on the editor anytime the current mode changes,
* Event object: {mode: "visual", subMode: "linewise"}
*
* Code structure:
* 1. Default keymap
* 2. Variable declarations and short basic helpers
* 3. Instance (External API) implementation
* 4. Internal state tracking objects (input state, counter) implementation
* and instanstiation
* 5. Key handler (the main command dispatcher) implementation
* 6. Motion, operator, and action implementations
* 7. Helper functions for the key handler, motions, operators, and actions
* 8. Set up Vim to work as a keymap for CodeMirror.
*/
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/dialog/dialog"), require("../addon/edit/matchbrackets.js"));
else if (typeof define == "function" && define.amd) // AMD
define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
'use strict';
var defaultKeymap = [
// Key to key mapping. This goes first to make it possible to override
// existing mappings.
{ keys: ['<Left>'], type: 'keyToKey', toKeys: ['h'] },
{ keys: ['<Right>'], type: 'keyToKey', toKeys: ['l'] },
{ keys: ['<Up>'], type: 'keyToKey', toKeys: ['k'] },
{ keys: ['<Down>'], type: 'keyToKey', toKeys: ['j'] },
{ keys: ['<Space>'], type: 'keyToKey', toKeys: ['l'] },
{ keys: ['<BS>'], type: 'keyToKey', toKeys: ['h'] },
{ keys: ['<C-Space>'], type: 'keyToKey', toKeys: ['W'] },
{ keys: ['<C-BS>'], type: 'keyToKey', toKeys: ['B'] },
{ keys: ['<S-Space>'], type: 'keyToKey', toKeys: ['w'] },
{ keys: ['<S-BS>'], type: 'keyToKey', toKeys: ['b'] },
{ keys: ['<C-n>'], type: 'keyToKey', toKeys: ['j'] },
{ keys: ['<C-p>'], type: 'keyToKey', toKeys: ['k'] },
{ keys: ['<C-[>'], type: 'keyToKey', toKeys: ['<Esc>'] },
{ keys: ['<C-c>'], type: 'keyToKey', toKeys: ['<Esc>'] },
{ keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'], context: 'normal' },
{ keys: ['s'], type: 'keyToKey', toKeys: ['x', 'i'], context: 'visual'},
{ keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'], context: 'normal' },
{ keys: ['S'], type: 'keyToKey', toKeys: ['d', 'c', 'c'], context: 'visual' },
{ keys: ['<Home>'], type: 'keyToKey', toKeys: ['0'] },
{ keys: ['<End>'], type: 'keyToKey', toKeys: ['$'] },
{ keys: ['<PageUp>'], type: 'keyToKey', toKeys: ['<C-b>'] },
{ keys: ['<PageDown>'], type: 'keyToKey', toKeys: ['<C-f>'] },
{ keys: ['<CR>'], type: 'keyToKey', toKeys: ['j', '^'], context: 'normal' },
// Motions
{ keys: ['H'], type: 'motion',
motion: 'moveToTopLine',
motionArgs: { linewise: true, toJumplist: true }},
{ keys: ['M'], type: 'motion',
motion: 'moveToMiddleLine',
motionArgs: { linewise: true, toJumplist: true }},
{ keys: ['L'], type: 'motion',
motion: 'moveToBottomLine',
motionArgs: { linewise: true, toJumplist: true }},
{ keys: ['h'], type: 'motion',
motion: 'moveByCharacters',
motionArgs: { forward: false }},
{ keys: ['l'], type: 'motion',
motion: 'moveByCharacters',
motionArgs: { forward: true }},
{ keys: ['j'], type: 'motion',
motion: 'moveByLines',
motionArgs: { forward: true, linewise: true }},
{ keys: ['k'], type: 'motion',
motion: 'moveByLines',
motionArgs: { forward: false, linewise: true }},
{ keys: ['g','j'], type: 'motion',
motion: 'moveByDisplayLines',
motionArgs: { forward: true }},
{ keys: ['g','k'], type: 'motion',
motion: 'moveByDisplayLines',
motionArgs: { forward: false }},
{ keys: ['w'], type: 'motion',
motion: 'moveByWords',
motionArgs: { forward: true, wordEnd: false }},
{ keys: ['W'], type: 'motion',
motion: 'moveByWords',
motionArgs: { forward: true, wordEnd: false, bigWord: true }},
{ keys: ['e'], type: 'motion',
motion: 'moveByWords',
motionArgs: { forward: true, wordEnd: true, inclusive: true }},
{ keys: ['E'], type: 'motion',
motion: 'moveByWords',
motionArgs: { forward: true, wordEnd: true, bigWord: true,
inclusive: true }},
{ keys: ['b'], type: 'motion',
motion: 'moveByWords',
motionArgs: { forward: false, wordEnd: false }},
{ keys: ['B'], type: 'motion',
motion: 'moveByWords',
motionArgs: { forward: false, wordEnd: false, bigWord: true }},
{ keys: ['g', 'e'], type: 'motion',
motion: 'moveByWords',
motionArgs: { forward: false, wordEnd: true, inclusive: true }},
{ keys: ['g', 'E'], type: 'motion',
motion: 'moveByWords',
motionArgs: { forward: false, wordEnd: true, bigWord: true,
inclusive: true }},
{ keys: ['{'], type: 'motion', motion: 'moveByParagraph',
motionArgs: { forward: false, toJumplist: true }},
{ keys: ['}'], type: 'motion', motion: 'moveByParagraph',
motionArgs: { forward: true, toJumplist: true }},
{ keys: ['<C-f>'], type: 'motion',
motion: 'moveByPage', motionArgs: { forward: true }},
{ keys: ['<C-b>'], type: 'motion',
motion: 'moveByPage', motionArgs: { forward: false }},
{ keys: ['<C-d>'], type: 'motion',
motion: 'moveByScroll',
motionArgs: { forward: true, explicitRepeat: true }},
{ keys: ['<C-u>'], type: 'motion',
motion: 'moveByScroll',
motionArgs: { forward: false, explicitRepeat: true }},
{ keys: ['g', 'g'], type: 'motion',
motion: 'moveToLineOrEdgeOfDocument',
motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
{ keys: ['G'], type: 'motion',
motion: 'moveToLineOrEdgeOfDocument',
motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
{ keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' },
{ keys: ['^'], type: 'motion',
motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: ['+'], type: 'motion',
motion: 'moveByLines',
motionArgs: { forward: true, toFirstChar:true }},
{ keys: ['-'], type: 'motion',
motion: 'moveByLines',
motionArgs: { forward: false, toFirstChar:true }},
{ keys: ['_'], type: 'motion',
motion: 'moveByLines',
motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
{ keys: ['$'], type: 'motion',
motion: 'moveToEol',
motionArgs: { inclusive: true }},
{ keys: ['%'], type: 'motion',
motion: 'moveToMatchedSymbol',
motionArgs: { inclusive: true, toJumplist: true }},
{ keys: ['f', 'character'], type: 'motion',
motion: 'moveToCharacter',
motionArgs: { forward: true , inclusive: true }},
{ keys: ['F', 'character'], type: 'motion',
motion: 'moveToCharacter',
motionArgs: { forward: false }},
{ keys: ['t', 'character'], type: 'motion',
motion: 'moveTillCharacter',
motionArgs: { forward: true, inclusive: true }},
{ keys: ['T', 'character'], type: 'motion',
motion: 'moveTillCharacter',
motionArgs: { forward: false }},
{ keys: [';'], type: 'motion', motion: 'repeatLastCharacterSearch',
motionArgs: { forward: true }},
{ keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch',
motionArgs: { forward: false }},
{ keys: ['\'', 'character'], type: 'motion', motion: 'goToMark',
motionArgs: {toJumplist: true, linewise: true}},
{ keys: ['`', 'character'], type: 'motion', motion: 'goToMark',
motionArgs: {toJumplist: true}},
{ keys: [']', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
{ keys: ['[', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
{ keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
{ keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
// the next two aren't motions but must come before more general motion declarations
{ keys: [']', 'p'], type: 'action', action: 'paste', isEdit: true,
actionArgs: { after: true, isEdit: true, matchIndent: true}},
{ keys: ['[', 'p'], type: 'action', action: 'paste', isEdit: true,
actionArgs: { after: false, isEdit: true, matchIndent: true}},
{ keys: [']', 'character'], type: 'motion',
motion: 'moveToSymbol',
motionArgs: { forward: true, toJumplist: true}},
{ keys: ['[', 'character'], type: 'motion',
motion: 'moveToSymbol',
motionArgs: { forward: false, toJumplist: true}},
{ keys: ['|'], type: 'motion',
motion: 'moveToColumn',
motionArgs: { }},
{ keys: ['o'], type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: { },context:'visual'},
// Operators
{ keys: ['d'], type: 'operator', operator: 'delete' },
{ keys: ['y'], type: 'operator', operator: 'yank' },
{ keys: ['c'], type: 'operator', operator: 'change' },
{ keys: ['>'], type: 'operator', operator: 'indent',
operatorArgs: { indentRight: true }},
{ keys: ['<'], type: 'operator', operator: 'indent',
operatorArgs: { indentRight: false }},
{ keys: ['g', '~'], type: 'operator', operator: 'swapcase' },
{ keys: ['n'], type: 'motion', motion: 'findNext',
motionArgs: { forward: true, toJumplist: true }},
{ keys: ['N'], type: 'motion', motion: 'findNext',
motionArgs: { forward: false, toJumplist: true }},
// Operator-Motion dual commands
{ keys: ['x'], type: 'operatorMotion', operator: 'delete',
motion: 'moveByCharacters', motionArgs: { forward: true },
operatorMotionArgs: { visualLine: false }},
{ keys: ['X'], type: 'operatorMotion', operator: 'delete',
motion: 'moveByCharacters', motionArgs: { forward: false },
operatorMotionArgs: { visualLine: true }},
{ keys: ['D'], type: 'operatorMotion', operator: 'delete',
motion: 'moveToEol', motionArgs: { inclusive: true },
operatorMotionArgs: { visualLine: true }},
{ keys: ['Y'], type: 'operatorMotion', operator: 'yank',
motion: 'moveToEol', motionArgs: { inclusive: true },
operatorMotionArgs: { visualLine: true }},
{ keys: ['C'], type: 'operatorMotion',
operator: 'change',
motion: 'moveToEol', motionArgs: { inclusive: true },
operatorMotionArgs: { visualLine: true }},
{ keys: ['~'], type: 'operatorMotion',
operator: 'swapcase', operatorArgs: { shouldMoveCursor: true },
motion: 'moveByCharacters', motionArgs: { forward: true }},
// Actions
{ keys: ['<C-i>'], type: 'action', action: 'jumpListWalk',
actionArgs: { forward: true }},
{ keys: ['<C-o>'], type: 'action', action: 'jumpListWalk',
actionArgs: { forward: false }},
{ keys: ['<C-e>'], type: 'action',
action: 'scroll',
actionArgs: { forward: true, linewise: true }},
{ keys: ['<C-y>'], type: 'action',
action: 'scroll',
actionArgs: { forward: false, linewise: true }},
{ keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true,
actionArgs: { insertAt: 'charAfter' }},
{ keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true,
actionArgs: { insertAt: 'eol' }},
{ keys: ['i'], type: 'action', action: 'enterInsertMode', isEdit: true,
actionArgs: { insertAt: 'inplace' }},
{ keys: ['I'], type: 'action', action: 'enterInsertMode', isEdit: true,
actionArgs: { insertAt: 'firstNonBlank' }},
{ keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode',
isEdit: true, interlaceInsertRepeat: true,
actionArgs: { after: true }},
{ keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode',
isEdit: true, interlaceInsertRepeat: true,
actionArgs: { after: false }},
{ keys: ['v'], type: 'action', action: 'toggleVisualMode' },
{ keys: ['V'], type: 'action', action: 'toggleVisualMode',
actionArgs: { linewise: true }},
{ keys: ['g', 'v'], type: 'action', action: 'reselectLastSelection' },
{ keys: ['J'], type: 'action', action: 'joinLines', isEdit: true },
{ keys: ['p'], type: 'action', action: 'paste', isEdit: true,
actionArgs: { after: true, isEdit: true }},
{ keys: ['P'], type: 'action', action: 'paste', isEdit: true,
actionArgs: { after: false, isEdit: true }},
{ keys: ['r', 'character'], type: 'action', action: 'replace', isEdit: true },
{ keys: ['@', 'character'], type: 'action', action: 'replayMacro' },
{ keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' },
// Handle Replace-mode as a special case of insert mode.
{ keys: ['R'], type: 'action', action: 'enterInsertMode', isEdit: true,
actionArgs: { replace: true }},
{ keys: ['u'], type: 'action', action: 'undo' },
{ keys: ['u'], type: 'action', action: 'changeCase', actionArgs: {toLower: true}, context: 'visual', isEdit: true },
{ keys: ['U'],type: 'action', action: 'changeCase', actionArgs: {toLower: false}, context: 'visual', isEdit: true },
{ keys: ['<C-r>'], type: 'action', action: 'redo' },
{ keys: ['m', 'character'], type: 'action', action: 'setMark' },
{ keys: ['"', 'character'], type: 'action', action: 'setRegister' },
{ keys: ['z', 'z'], type: 'action', action: 'scrollToCursor',
actionArgs: { position: 'center' }},
{ keys: ['z', '.'], type: 'action', action: 'scrollToCursor',
actionArgs: { position: 'center' },
motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: ['z', 't'], type: 'action', action: 'scrollToCursor',
actionArgs: { position: 'top' }},
{ keys: ['z', '<CR>'], type: 'action', action: 'scrollToCursor',
actionArgs: { position: 'top' },
motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: ['z', '-'], type: 'action', action: 'scrollToCursor',
actionArgs: { position: 'bottom' }},
{ keys: ['z', 'b'], type: 'action', action: 'scrollToCursor',
actionArgs: { position: 'bottom' },
motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: ['.'], type: 'action', action: 'repeatLastEdit' },
{ keys: ['<C-a>'], type: 'action', action: 'incrementNumberToken',
isEdit: true,
actionArgs: {increase: true, backtrack: false}},
{ keys: ['<C-x>'], type: 'action', action: 'incrementNumberToken',
isEdit: true,
actionArgs: {increase: false, backtrack: false}},
// Text object motions
{ keys: ['a', 'character'], type: 'motion',
motion: 'textObjectManipulation' },
{ keys: ['i', 'character'], type: 'motion',
motion: 'textObjectManipulation',
motionArgs: { textObjectInner: true }},
// Search
{ keys: ['/'], type: 'search',
searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
{ keys: ['?'], type: 'search',
searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
{ keys: ['*'], type: 'search',
searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
{ keys: ['#'], type: 'search',
searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
{ keys: ['g', '*'], type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
{ keys: ['g', '#'], type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
// Ex command
{ keys: [':'], type: 'ex' }
];
var Pos = CodeMirror.Pos;
var Vim = function() {
CodeMirror.defineOption('vimMode', false, function(cm, val) {
if (val) {
cm.setOption('keyMap', 'vim');
cm.setOption('disableInput', true);
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
cm.on('beforeSelectionChange', beforeSelectionChange);
cm.on('cursorActivity', onCursorActivity);
maybeInitVimState(cm);
CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
} else if (cm.state.vim) {
cm.setOption('keyMap', 'default');
cm.setOption('disableInput', false);
cm.off('beforeSelectionChange', beforeSelectionChange);
cm.off('cursorActivity', onCursorActivity);
CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
cm.state.vim = null;
}
});
function beforeSelectionChange(cm, obj) {
var vim = cm.state.vim;
if (vim.insertMode || vim.exMode) return;
var head = obj.ranges[0].head;
var anchor = obj.ranges[0].anchor;
if (head.ch && head.ch == cm.doc.getLine(head.line).length) {
var pos = Pos(head.line, head.ch - 1);
obj.update([{anchor: cursorEqual(head, anchor) ? pos : anchor,
head: pos}]);
}
}
function getOnPasteFn(cm) {
var vim = cm.state.vim;
if (!vim.onPasteFn) {
vim.onPasteFn = function() {
if (!vim.insertMode) {
cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
actions.enterInsertMode(cm, {}, vim);
}
};
}
return vim.onPasteFn;
}
var numberRegex = /[\d]/;
var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
function makeKeyRange(start, size) {
var keys = [];
for (var i = start; i < start + size; i++) {
keys.push(String.fromCharCode(i));
}
return keys;
}
var upperCaseAlphabet = makeKeyRange(65, 26);
var lowerCaseAlphabet = makeKeyRange(97, 26);
var numbers = makeKeyRange(48, 10);
var specialSymbols = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;"\''.split('');
var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace',
'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter'];
var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':']);
function isLine(cm, line) {
return line >= cm.firstLine() && line <= cm.lastLine();
}
function isLowerCase(k) {
return (/^[a-z]$/).test(k);
}
function isMatchableSymbol(k) {
return '()[]{}'.indexOf(k) != -1;
}
function isNumber(k) {
return numberRegex.test(k);
}
function isUpperCase(k) {
return (/^[A-Z]$/).test(k);
}
function isWhiteSpaceString(k) {
return (/^\s*$/).test(k);
}
function inArray(val, arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == val) {
return true;
}
}
return false;
}
var options = {};
function defineOption(name, defaultValue, type) {
if (defaultValue === undefined) { throw Error('defaultValue is required'); }
if (!type) { type = 'string'; }
options[name] = {
type: type,
defaultValue: defaultValue
};
setOption(name, defaultValue);
}
function setOption(name, value) {
var option = options[name];
if (!option) {
throw Error('Unknown option: ' + name);
}
if (option.type == 'boolean') {
if (value && value !== true) {
throw Error('Invalid argument: ' + name + '=' + value);
} else if (value !== false) {
// Boolean options are set to true if value is not defined.
value = true;
}
}
option.value = option.type == 'boolean' ? !!value : value;
}
function getOption(name) {
var option = options[name];
if (!option) {
throw Error('Unknown option: ' + name);
}
return option.value;
}
var createCircularJumpList = function() {
var size = 100;
var pointer = -1;
var head = 0;
var tail = 0;
var buffer = new Array(size);
function add(cm, oldCur, newCur) {
var current = pointer % size;
var curMark = buffer[current];
function useNextSlot(cursor) {
var next = ++pointer % size;
var trashMark = buffer[next];
if (trashMark) {
trashMark.clear();
}
buffer[next] = cm.setBookmark(cursor);
}
if (curMark) {
var markPos = curMark.find();
// avoid recording redundant cursor position
if (markPos && !cursorEqual(markPos, oldCur)) {
useNextSlot(oldCur);
}
} else {
useNextSlot(oldCur);
}
useNextSlot(newCur);
head = pointer;
tail = pointer - size + 1;
if (tail < 0) {
tail = 0;
}
}
function move(cm, offset) {
pointer += offset;
if (pointer > head) {
pointer = head;
} else if (pointer < tail) {
pointer = tail;
}
var mark = buffer[(size + pointer) % size];
// skip marks that are temporarily removed from text buffer
if (mark && !mark.find()) {
var inc = offset > 0 ? 1 : -1;
var newCur;
var oldCur = cm.getCursor();
do {
pointer += inc;
mark = buffer[(size + pointer) % size];
// skip marks that are the same as current position
if (mark &&
(newCur = mark.find()) &&
!cursorEqual(oldCur, newCur)) {
break;
}
} while (pointer < head && pointer > tail);
}
return mark;
}
return {
cachedCursor: undefined, //used for # and * jumps
add: add,
move: move
};
};
// Returns an object to track the changes associated insert mode. It
// clones the object that is passed in, or creates an empty object one if
// none is provided.
var createInsertModeChanges = function(c) {
if (c) {
// Copy construction
return {
changes: c.changes,
expectCursorActivityForChange: c.expectCursorActivityForChange
};
}
return {
// Change list
changes: [],
// Set to true on change, false on cursorActivity.
expectCursorActivityForChange: false
};
};
function MacroModeState() {
this.latestRegister = undefined;
this.isPlaying = false;
this.isRecording = false;
this.replaySearchQueries = [];
this.onRecordingDone = undefined;
this.lastInsertModeChanges = createInsertModeChanges();
}
MacroModeState.prototype = {
exitMacroRecordMode: function() {
var macroModeState = vimGlobalState.macroModeState;
macroModeState.onRecordingDone(); // close dialog
macroModeState.onRecordingDone = undefined;
macroModeState.isRecording = false;
},
enterMacroRecordMode: function(cm, registerName) {
var register =
vimGlobalState.registerController.getRegister(registerName);
if (register) {
register.clear();
this.latestRegister = registerName;
this.onRecordingDone = cm.openDialog(
'(recording)['+registerName+']', null, {bottom:true});
this.isRecording = true;
}
}
};
function maybeInitVimState(cm) {
if (!cm.state.vim) {
// Store instance state in the CodeMirror object.
cm.state.vim = {
inputState: new InputState(),
// Vim's input state that triggered the last edit, used to repeat
// motions and operators with '.'.
lastEditInputState: undefined,
// Vim's action command before the last edit, used to repeat actions
// with '.' and insert mode repeat.
lastEditActionCommand: undefined,
// When using jk for navigation, if you move from a longer line to a
// shorter line, the cursor may clip to the end of the shorter line.
// If j is pressed again and cursor goes to the next line, the
// cursor should go back to its horizontal position on the longer
// line if it can. This is to keep track of the horizontal position.
lastHPos: -1,
// Doing the same with screen-position for gj/gk
lastHSPos: -1,
// The last motion command run. Cleared if a non-motion command gets
// executed in between.
lastMotion: null,
marks: {},
insertMode: false,
// Repeat count for changes made in insert mode, triggered by key
// sequences like 3,i. Only exists when insertMode is true.
insertModeRepeat: undefined,
visualMode: false,
// If we are in visual line mode. No effect if visualMode is false.
visualLine: false,
lastSelection: null
};
}
return cm.state.vim;
}
var vimGlobalState;
function resetVimGlobalState() {
vimGlobalState = {
// The current search query.
searchQuery: null,
// Whether we are searching backwards.
searchIsReversed: false,
// Replace part of the last substituted pattern
lastSubstituteReplacePart: undefined,
jumpList: createCircularJumpList(),
macroModeState: new MacroModeState,
// Recording latest f, t, F or T motion command.
lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
registerController: new RegisterController({})
};
for (var optionName in options) {
var option = options[optionName];
option.value = option.defaultValue;
}
}
var vimApi= {
buildKeyMap: function() {
// TODO: Convert keymap into dictionary format for fast lookup.
},
// Testing hook, though it might be useful to expose the register
// controller anyways.
getRegisterController: function() {
return vimGlobalState.registerController;
},
// Testing hook.
resetVimGlobalState_: resetVimGlobalState,
// Testing hook.
getVimGlobalState_: function() {
return vimGlobalState;
},
// Testing hook.
maybeInitVimState_: maybeInitVimState,
InsertModeKey: InsertModeKey,
map: function(lhs, rhs, ctx) {
// Add user defined key bindings.
exCommandDispatcher.map(lhs, rhs, ctx);
},
setOption: setOption,
getOption: getOption,
defineOption: defineOption,
defineEx: function(name, prefix, func){
if (name.indexOf(prefix) !== 0) {
throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
}
exCommands[name]=func;
exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
},
// This is the outermost function called by CodeMirror, after keys have
// been mapped to their Vim equivalents.
handleKey: function(cm, key) {
var command;
var vim = maybeInitVimState(cm);
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isRecording) {
if (key == 'q') {
macroModeState.exitMacroRecordMode();
vim.inputState = new InputState();
return;
}
}
if (key == '<Esc>') {
// Clear input state and get back to normal mode.
vim.inputState = new InputState();
if (vim.visualMode) {
exitVisualMode(cm);
}
return;
}
// Enter visual mode when the mouse selects text.
if (!vim.visualMode &&
!cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
vim.visualMode = true;
vim.visualLine = false;
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
cm.on('mousedown', exitVisualMode);
}
if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
// Have to special case 0 since it's both a motion and a number.
command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
}
if (!command) {
if (isNumber(key)) {
// Increment count unless count is 0 and key is 0.
vim.inputState.pushRepeatDigit(key);
}
if (macroModeState.isRecording) {
logKey(macroModeState, key);
}
return;
}
if (command.type == 'keyToKey') {
// TODO: prevent infinite recursion.
for (var i = 0; i < command.toKeys.length; i++) {
this.handleKey(cm, command.toKeys[i]);
}
} else {
if (macroModeState.isRecording) {
logKey(macroModeState, key);
}
commandDispatcher.processCommand(cm, vim, command);
}
},
handleEx: function(cm, input) {
exCommandDispatcher.processCommand(cm, input);
}
};
// Represents the current input state.
function InputState() {
this.prefixRepeat = [];
this.motionRepeat = [];
this.operator = null;
this.operatorArgs = null;
this.motion = null;
this.motionArgs = null;
this.keyBuffer = []; // For matching multi-key commands.
this.registerName = null; // Defaults to the unnamed register.
}
InputState.prototype.pushRepeatDigit = function(n) {
if (!this.operator) {
this.prefixRepeat = this.prefixRepeat.concat(n);
} else {
this.motionRepeat = this.motionRepeat.concat(n);
}
};
InputState.prototype.getRepeat = function() {
var repeat = 0;
if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
repeat = 1;
if (this.prefixRepeat.length > 0) {
repeat *= parseInt(this.prefixRepeat.join(''), 10);
}
if (this.motionRepeat.length > 0) {
repeat *= parseInt(this.motionRepeat.join(''), 10);
}
}
return repeat;
};
/*
* Register stores information about copy and paste registers. Besides
* text, a register must store whether it is linewise (i.e., when it is
* pasted, should it insert itself into a new line, or should the text be
* inserted at the cursor position.)
*/
function Register(text, linewise) {
this.clear();
this.keyBuffer = [text || ''];
this.insertModeChanges = [];
this.searchQueries = [];
this.linewise = !!linewise;
}
Register.prototype = {
setText: function(text, linewise) {
this.keyBuffer = [text || ''];
this.linewise = !!linewise;
},
pushText: function(text, linewise) {
// if this register has ever been set to linewise, use linewise.
if (linewise) {
if (!this.linewise) {
this.keyBuffer.push('\n');
}
this.linewise = true;
}
this.keyBuffer.push(text);
},
pushInsertModeChanges: function(changes) {
this.insertModeChanges.push(createInsertModeChanges(changes));
},
pushSearchQuery: function(query) {
this.searchQueries.push(query);
},
clear: function() {
this.keyBuffer = [];
this.insertModeChanges = [];
this.searchQueries = [];
this.linewise = false;
},
toString: function() {
return this.keyBuffer.join('');
}
};
/*
* vim registers allow you to keep many independent copy and paste buffers.
* See http://usevim.com/2012/04/13/registers/ for an introduction.
*
* RegisterController keeps the state of all the registers. An initial
* state may be passed in. The unnamed register '"' will always be
* overridden.
*/
function RegisterController(registers) {
this.registers = registers;
this.unnamedRegister = registers['"'] = new Register();
registers['.'] = new Register();
registers[':'] = new Register();
}
RegisterController.prototype = {
pushText: function(registerName, operator, text, linewise) {
if (linewise && text.charAt(0) == '\n') {
text = text.slice(1) + '\n';
}
if (linewise && text.charAt(text.length - 1) !== '\n'){
text += '\n';
}
// Lowercase and uppercase registers refer to the same register.
// Uppercase just means append.
var register = this.isValidRegister(registerName) ?
this.getRegister(registerName) : null;
// if no register/an invalid register was specified, things go to the
// default registers
if (!register) {
switch (operator) {
case 'yank':
// The 0 register contains the text from the most recent yank.
this.registers['0'] = new Register(text, linewise);
break;
case 'delete':
case 'change':
if (text.indexOf('\n') == -1) {
// Delete less than 1 line. Update the small delete register.
this.registers['-'] = new Register(text, linewise);
} else {
// Shift down the contents of the numbered registers and put the
// deleted text into register 1.
this.shiftNumericRegisters_();
this.registers['1'] = new Register(text, linewise);
}
break;
}
// Make sure the unnamed register is set to what just happened
this.unnamedRegister.setText(text, linewise);
return;
}
// If we've gotten to this point, we've actually specified a register
var append = isUpperCase(registerName);
if (append) {
register.pushText(text, linewise);
} else {
register.setText(text, linewise);
}
// The unnamed register always has the same value as the last used
// register.
this.unnamedRegister.setText(register.toString(), linewise);
},
// Gets the register named @name. If one of @name doesn't already exist,
// create it. If @name is invalid, return the unnamedRegister.
getRegister: function(name) {
if (!this.isValidRegister(name)) {
return this.unnamedRegister;
}
name = name.toLowerCase();
if (!this.registers[name]) {
this.registers[name] = new Register();
}
return this.registers[name];
},
isValidRegister: function(name) {
return name && inArray(name, validRegisters);
},
shiftNumericRegisters_: function() {
for (var i = 9; i >= 2; i--) {
this.registers[i] = this.getRegister('' + (i - 1));
}
}
};
var commandDispatcher = {
matchCommand: function(key, keyMap, vim) {
var inputState = vim.inputState;
var keys = inputState.keyBuffer.concat(key);
var matchedCommands = [];
var selectedCharacter;
for (var i = 0; i < keyMap.length; i++) {
var command = keyMap[i];
if (matchKeysPartial(keys, command.keys)) {
if (inputState.operator && command.type == 'action') {
// Ignore matched action commands after an operator. Operators
// only operate on motions. This check is really for text
// objects since aW, a[ etcs conflicts with a.
continue;
}
// Match commands that take <character> as an argument.
if (command.keys[keys.length - 1] == 'character') {
selectedCharacter = keys[keys.length - 1];
if (selectedCharacter.length>1){
switch(selectedCharacter){
case '<CR>':
selectedCharacter='\n';
break;
case '<Space>':
selectedCharacter=' ';
break;
default:
continue;
}
}
}
// Add the command to the list of matched commands. Choose the best
// command later.
matchedCommands.push(command);
}
}
// Returns the command if it is a full match, or null if not.
function getFullyMatchedCommandOrNull(command) {
if (keys.length < command.keys.length) {
// Matches part of a multi-key command. Buffer and wait for next
// stroke.
inputState.keyBuffer.push(key);
return null;
} else {
if (command.keys[keys.length - 1] == 'character') {
inputState.selectedCharacter = selectedCharacter;
}
// Clear the buffer since a full match was found.
inputState.keyBuffer = [];
return command;
}
}
if (!matchedCommands.length) {
// Clear the buffer since there were no matches.
inputState.keyBuffer = [];
return null;
} else if (matchedCommands.length == 1) {
return getFullyMatchedCommandOrNull(matchedCommands[0]);
} else {
// Find the best match in the list of matchedCommands.
var context = vim.visualMode ? 'visual' : 'normal';
var bestMatch; // Default to first in the list.
for (var i = 0; i < matchedCommands.length; i++) {
var current = matchedCommands[i];
if (current.context == context) {
bestMatch = current;
break;
} else if (!bestMatch && !current.context) {
// Only set an imperfect match to best match if no best match is
// set and the imperfect match is not restricted to another
// context.
bestMatch = current;
}
}
return getFullyMatchedCommandOrNull(bestMatch);
}
},
processCommand: function(cm, vim, command) {
vim.inputState.repeatOverride = command.repeatOverride;
switch (command.type) {
case 'motion':
this.processMotion(cm, vim, command);
break;
case 'operator':
this.processOperator(cm, vim, command);
break;
case 'operatorMotion':
this.processOperatorMotion(cm, vim, command);
break;
case 'action':
this.processAction(cm, vim, command);
break;
case 'search':
this.processSearch(cm, vim, command);
break;
case 'ex':
case 'keyToEx':
this.processEx(cm, vim, command);
break;
default:
break;
}
},
processMotion: function(cm, vim, command) {
vim.inputState.motion = command.motion;
vim.inputState.motionArgs = copyArgs(command.motionArgs);
this.evalInput(cm, vim);
},
processOperator: function(cm, vim, command) {
var inputState = vim.inputState;
if (inputState.operator) {
if (inputState.operator == command.operator) {
// Typing an operator twice like 'dd' makes the operator operate
// linewise
inputState.motion = 'expandToLine';
inputState.motionArgs = { linewise: true };
this.evalInput(cm, vim);
return;
} else {
// 2 different operators in a row doesn't make sense.
vim.inputState = new InputState();
}
}
inputState.operator = command.operator;
inputState.operatorArgs = copyArgs(command.operatorArgs);
if (vim.visualMode) {
// Operating on a selection in visual mode. We don't need a motion.
this.evalInput(cm, vim);
}
},
processOperatorMotion: function(cm, vim, command) {
var visualMode = vim.visualMode;
var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
if (operatorMotionArgs) {
// Operator motions may have special behavior in visual mode.
if (visualMode && operatorMotionArgs.visualLine) {
vim.visualLine = true;
}
}
this.processOperator(cm, vim, command);
if (!visualMode) {
this.processMotion(cm, vim, command);
}
},
processAction: function(cm, vim, command) {
var inputState = vim.inputState;
var repeat = inputState.getRepeat();
var repeatIsExplicit = !!repeat;
var actionArgs = copyArgs(command.actionArgs) || {};
if (inputState.selectedCharacter) {
actionArgs.selectedCharacter = inputState.selectedCharacter;
}
// Actions may or may not have motions and operators. Do these first.
if (command.operator) {
this.processOperator(cm, vim, command);
}
if (command.motion) {
this.processMotion(cm, vim, command);
}
if (command.motion || command.operator) {
this.evalInput(cm, vim);
}
actionArgs.repeat = repeat || 1;
actionArgs.repeatIsExplicit = repeatIsExplicit;
actionArgs.registerName = inputState.registerName;
vim.inputState = new InputState();
vim.lastMotion = null;
if (command.isEdit) {
this.recordLastEdit(vim, inputState, command);
}
actions[command.action](cm, actionArgs, vim);
},
processSearch: function(cm, vim, command) {
if (!cm.getSearchCursor) {
// Search depends on SearchCursor.
return;
}
var forward = command.searchArgs.forward;
var wholeWordOnly = command.searchArgs.wholeWordOnly;
getSearchState(cm).setReversed(!forward);
var promptPrefix = (forward) ? '/' : '?';
var originalQuery = getSearchState(cm).getQuery();
var originalScrollPos = cm.getScrollInfo();
function handleQuery(query, ignoreCase, smartCase) {
try {
updateSearchQuery(cm, query, ignoreCase, smartCase);
} catch (e) {
showConfirm(cm, 'Invalid regex: ' + query);
return;
}
commandDispatcher.processMotion(cm, vim, {
type: 'motion',
motion: 'findNext',
motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
});
}
function onPromptClose(query) {
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
handleQuery(query, true /** ignoreCase */, true /** smartCase */);
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isRecording) {
logSearchQuery(macroModeState, query);
}
}
function onPromptKeyUp(_e, query) {
var parsedQuery;
try {
parsedQuery = updateSearchQuery(cm, query,
true /** ignoreCase */, true /** smartCase */);
} catch (e) {
// Swallow bad regexes for incremental search.
}
if (parsedQuery) {
cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
} else {
clearSearchHighlight(cm);
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
}
}
function onPromptKeyDown(e, _query, close) {
var keyName = CodeMirror.keyName(e);
if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
updateSearchQuery(cm, originalQuery);
clearSearchHighlight(cm);
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
CodeMirror.e_stop(e);
close();
cm.focus();
}
}
switch (command.searchArgs.querySrc) {
case 'prompt':
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isPlaying) {
var query = macroModeState.replaySearchQueries.shift();
handleQuery(query, true /** ignoreCase */, false /** smartCase */);
} else {
showPrompt(cm, {
onClose: onPromptClose,
prefix: promptPrefix,
desc: searchPromptDesc,
onKeyUp: onPromptKeyUp,
onKeyDown: onPromptKeyDown
});
}
break;
case 'wordUnderCursor':
var word = expandWordUnderCursor(cm, false /** inclusive */,
true /** forward */, false /** bigWord */,
true /** noSymbol */);
var isKeyword = true;
if (!word) {
word = expandWordUnderCursor(cm, false /** inclusive */,
true /** forward */, false /** bigWord */,
false /** noSymbol */);
isKeyword = false;
}
if (!word) {
return;
}
var query = cm.getLine(word.start.line).substring(word.start.ch,
word.end.ch);
if (isKeyword && wholeWordOnly) {
query = '\\b' + query + '\\b';
} else {
query = escapeRegex(query);
}
// cachedCursor is used to save the old position of the cursor
// when * or # causes vim to seek for the nearest word and shift
// the cursor before entering the motion.
vimGlobalState.jumpList.cachedCursor = cm.getCursor();
cm.setCursor(word.start);
handleQuery(query, true /** ignoreCase */, false /** smartCase */);
break;
}
},
processEx: function(cm, vim, command) {
function onPromptClose(input) {
// Give the prompt some time to close so that if processCommand shows
// an error, the elements don't overlap.
exCommandDispatcher.processCommand(cm, input);
}
function onPromptKeyDown(e, _input, close) {
var keyName = CodeMirror.keyName(e);
if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
CodeMirror.e_stop(e);
close();
cm.focus();
}
}
if (command.type == 'keyToEx') {
// Handle user defined Ex to Ex mappings
exCommandDispatcher.processCommand(cm, command.exArgs.input);
} else {
if (vim.visualMode) {
showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
onKeyDown: onPromptKeyDown});
} else {
showPrompt(cm, { onClose: onPromptClose, prefix: ':',
onKeyDown: onPromptKeyDown});
}
}
},
evalInput: function(cm, vim) {
// If the motion comand is set, execute both the operator and motion.
// Otherwise return.
var inputState = vim.inputState;
var motion = inputState.motion;
var motionArgs = inputState.motionArgs || {};
var operator = inputState.operator;
var operatorArgs = inputState.operatorArgs || {};
var registerName = inputState.registerName;
var selectionEnd = copyCursor(cm.getCursor('head'));
var selectionStart = copyCursor(cm.getCursor('anchor'));
// The difference between cur and selection cursors are that cur is
// being operated on and ignores that there is a selection.
var curStart = copyCursor(selectionEnd);
var curOriginal = copyCursor(curStart);
var curEnd;
var repeat;
if (operator) {
this.recordLastEdit(vim, inputState);
}
if (inputState.repeatOverride !== undefined) {
// If repeatOverride is specified, that takes precedence over the
// input state's repeat. Used by Ex mode and can be user defined.
repeat = inputState.repeatOverride;
} else {
repeat = inputState.getRepeat();
}
if (repeat > 0 && motionArgs.explicitRepeat) {
motionArgs.repeatIsExplicit = true;
} else if (motionArgs.noRepeat ||
(!motionArgs.explicitRepeat && repeat === 0)) {
repeat = 1;
motionArgs.repeatIsExplicit = false;
}
if (inputState.selectedCharacter) {
// If there is a character input, stick it in all of the arg arrays.
motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
inputState.selectedCharacter;
}
motionArgs.repeat = repeat;
vim.inputState = new InputState();
if (motion) {
var motionResult = motions[motion](cm, motionArgs, vim);
vim.lastMotion = motions[motion];
if (!motionResult) {
return;
}
if (motionArgs.toJumplist) {
var jumpList = vimGlobalState.jumpList;
// if the current motion is # or *, use cachedCursor
var cachedCursor = jumpList.cachedCursor;
if (cachedCursor) {
recordJumpPosition(cm, cachedCursor, motionResult);
delete jumpList.cachedCursor;
} else {
recordJumpPosition(cm, curOriginal, motionResult);
}
}
if (motionResult instanceof Array) {
curStart = motionResult[0];
curEnd = motionResult[1];
} else {
curEnd = motionResult;
}
// TODO: Handle null returns from motion commands better.
if (!curEnd) {
curEnd = Pos(curStart.line, curStart.ch);
}
if (vim.visualMode) {
// Check if the selection crossed over itself. Will need to shift
// the start point if that happened.
if (cursorIsBefore(selectionStart, selectionEnd) &&
(cursorEqual(selectionStart, curEnd) ||
cursorIsBefore(curEnd, selectionStart))) {
// The end of the selection has moved from after the start to
// before the start. We will shift the start right by 1.
selectionStart.ch += 1;
} else if (cursorIsBefore(selectionEnd, selectionStart) &&
(cursorEqual(selectionStart, curEnd) ||
cursorIsBefore(selectionStart, curEnd))) {
// The opposite happened. We will shift the start left by 1.
selectionStart.ch -= 1;
}
selectionEnd = curEnd;
selectionStart = (motionResult instanceof Array) ? curStart : selectionStart;
if (vim.visualLine) {
if (cursorIsBefore(selectionStart, selectionEnd)) {
selectionStart.ch = 0;
var lastLine = cm.lastLine();
if (selectionEnd.line > lastLine) {
selectionEnd.line = lastLine;
}
selectionEnd.ch = lineLength(cm, selectionEnd.line);
} else {
selectionEnd.ch = 0;
selectionStart.ch = lineLength(cm, selectionStart.line);
}
}
cm.setSelection(selectionStart, selectionEnd);
updateMark(cm, vim, '<',
cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
: selectionEnd);
updateMark(cm, vim, '>',
cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
: selectionStart);
} else if (!operator) {
curEnd = clipCursorToContent(cm, curEnd);
cm.setCursor(curEnd.line, curEnd.ch);
}
}
if (operator) {
var inverted = false;
vim.lastMotion = null;
operatorArgs.repeat = repeat; // Indent in visual mode needs this.
if (vim.visualMode) {
curStart = selectionStart;
curEnd = selectionEnd;
motionArgs.inclusive = true;
}
// Swap start and end if motion was backward.
if (curEnd && cursorIsBefore(curEnd, curStart)) {
var tmp = curStart;
curStart = curEnd;
curEnd = tmp;
inverted = true;
} else if (!curEnd) {
curEnd = copyCursor(curStart);
}
if (motionArgs.inclusive && !(vim.visualMode && inverted)) {
// Move the selection end one to the right to include the last
// character.
curEnd.ch++;
}
if (operatorArgs.selOffset) {
// Replaying a visual mode operation
curEnd.line = curStart.line + operatorArgs.selOffset.line;
if (operatorArgs.selOffset.line) {curEnd.ch = operatorArgs.selOffset.ch; }
else { curEnd.ch = curStart.ch + operatorArgs.selOffset.ch; }
} else if (vim.visualMode) {
var selOffset = Pos();
selOffset.line = curEnd.line - curStart.line;
if (selOffset.line) { selOffset.ch = curEnd.ch; }
else { selOffset.ch = curEnd.ch - curStart.ch; }
operatorArgs.selOffset = selOffset;
}
var linewise = motionArgs.linewise ||
(vim.visualMode && vim.visualLine) ||
operatorArgs.linewise;
if (linewise) {
// Expand selection to entire line.
expandSelectionToLine(cm, curStart, curEnd);
} else if (motionArgs.forward) {
// Clip to trailing newlines only if the motion goes forward.
clipToLine(cm, curStart, curEnd);
}
operatorArgs.registerName = registerName;
// Keep track of linewise as it affects how paste and change behave.
operatorArgs.linewise = linewise;
operators[operator](cm, operatorArgs, vim, curStart,
curEnd, curOriginal);
if (vim.visualMode) {
exitVisualMode(cm);
}
}
},
recordLastEdit: function(vim, inputState, actionCommand) {
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isPlaying) { return; }
vim.lastEditInputState = inputState;
vim.lastEditActionCommand = actionCommand;
macroModeState.lastInsertModeChanges.changes = [];
macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
}
};
/**
* typedef {Object{line:number,ch:number}} Cursor An object containing the
* position of the cursor.
*/
// All of the functions below return Cursor objects.
var motions = {
moveToTopLine: function(cm, motionArgs) {
var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
moveToMiddleLine: function(cm) {
var range = getUserVisibleLines(cm);
var line = Math.floor((range.top + range.bottom) * 0.5);
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
moveToBottomLine: function(cm, motionArgs) {
var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
expandToLine: function(cm, motionArgs) {
// Expands forward to end of line, and then to next line if repeat is
// >1. Does not handle backward motion!
var cur = cm.getCursor();
return Pos(cur.line + motionArgs.repeat - 1, Infinity);
},
findNext: function(cm, motionArgs) {
var state = getSearchState(cm);
var query = state.getQuery();
if (!query) {
return;
}
var prev = !motionArgs.forward;
// If search is initiated with ? instead of /, negate direction.
prev = (state.isReversed()) ? !prev : prev;
highlightSearchMatches(cm, query);
return findNext(cm, prev/** prev */, query, motionArgs.repeat);
},
goToMark: function(cm, motionArgs, vim) {
var mark = vim.marks[motionArgs.selectedCharacter];
if (mark) {
var pos = mark.find();
return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
}
return null;
},
moveToOtherHighlightedEnd: function(cm) {
var curEnd = copyCursor(cm.getCursor('head'));
var curStart = copyCursor(cm.getCursor('anchor'));
if (cursorIsBefore(curStart, curEnd)) {
curEnd.ch += 1;
} else if (cursorIsBefore(curEnd, curStart)) {
curStart.ch -= 1;
}
return ([curEnd,curStart]);
},
jumpToMark: function(cm, motionArgs, vim) {
var best = cm.getCursor();
for (var i = 0; i < motionArgs.repeat; i++) {
var cursor = best;
for (var key in vim.marks) {
if (!isLowerCase(key)) {
continue;
}
var mark = vim.marks[key].find();
var isWrongDirection = (motionArgs.forward) ?
cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
if (isWrongDirection) {
continue;
}
if (motionArgs.linewise && (mark.line == cursor.line)) {
continue;
}
var equal = cursorEqual(cursor, best);
var between = (motionArgs.forward) ?
cusrorIsBetween(cursor, mark, best) :
cusrorIsBetween(best, mark, cursor);
if (equal || between) {
best = mark;
}
}
}
if (motionArgs.linewise) {
// Vim places the cursor on the first non-whitespace character of
// the line if there is one, else it places the cursor at the end
// of the line, regardless of whether a mark was found.
best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
}
return best;
},
moveByCharacters: function(cm, motionArgs) {
var cur = cm.getCursor();
var repeat = motionArgs.repeat;
var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
return Pos(cur.line, ch);
},
moveByLines: function(cm, motionArgs, vim) {
var cur = cm.getCursor();
var endCh = cur.ch;
// Depending what our last motion was, we may want to do different
// things. If our last motion was moving vertically, we want to
// preserve the HPos from our last horizontal move. If our last motion
// was going to the end of a line, moving vertically we should go to
// the end of the line, etc.
switch (vim.lastMotion) {
case this.moveByLines:
case this.moveByDisplayLines:
case this.moveByScroll:
case this.moveToColumn:
case this.moveToEol:
endCh = vim.lastHPos;
break;
default:
vim.lastHPos = endCh;
}
var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
var first = cm.firstLine();
var last = cm.lastLine();
// Vim cancels linewise motions that start on an edge and move beyond
// that edge. It does not cancel motions that do not start on an edge.
if ((line < first && cur.line == first) ||
(line > last && cur.line == last)) {
return;
}
if (motionArgs.toFirstChar){
endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
vim.lastHPos = endCh;
}
vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
return Pos(line, endCh);
},
moveByDisplayLines: function(cm, motionArgs, vim) {
var cur = cm.getCursor();
switch (vim.lastMotion) {
case this.moveByDisplayLines:
case this.moveByScroll:
case this.moveByLines:
case this.moveToColumn:
case this.moveToEol:
break;
default:
vim.lastHSPos = cm.charCoords(cur,'div').left;
}
var repeat = motionArgs.repeat;
var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
if (res.hitSide) {
if (motionArgs.forward) {
var lastCharCoords = cm.charCoords(res, 'div');
var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
var res = cm.coordsChar(goalCoords, 'div');
} else {
var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');
resCoords.left = vim.lastHSPos;
res = cm.coordsChar(resCoords, 'div');
}
}
vim.lastHPos = res.ch;
return res;
},
moveByPage: function(cm, motionArgs) {
// CodeMirror only exposes functions that move the cursor page down, so
// doing this bad hack to move the cursor and move it back. evalInput
// will move the cursor to where it should be in the end.
var curStart = cm.getCursor();
var repeat = motionArgs.repeat;
return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
},
moveByParagraph: function(cm, motionArgs) {
var line = cm.getCursor().line;
var repeat = motionArgs.repeat;
var inc = motionArgs.forward ? 1 : -1;
for (var i = 0; i < repeat; i++) {
if ((!motionArgs.forward && line === cm.firstLine() ) ||
(motionArgs.forward && line == cm.lastLine())) {
break;
}
line += inc;
while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) {
line += inc;
}
}
return Pos(line, 0);
},
moveByScroll: function(cm, motionArgs, vim) {
var scrollbox = cm.getScrollInfo();
var curEnd = null;
var repeat = motionArgs.repeat;
if (!repeat) {
repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
}
var orig = cm.charCoords(cm.getCursor(), 'local');
motionArgs.repeat = repeat;
var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
if (!curEnd) {
return null;
}
var dest = cm.charCoords(curEnd, 'local');
cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
return curEnd;
},
moveByWords: function(cm, motionArgs) {
return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
!!motionArgs.wordEnd, !!motionArgs.bigWord);
},
moveTillCharacter: function(cm, motionArgs) {
var repeat = motionArgs.repeat;
var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter);
var increment = motionArgs.forward ? -1 : 1;
recordLastCharacterSearch(increment, motionArgs);
if (!curEnd) return null;
curEnd.ch += increment;
return curEnd;
},
moveToCharacter: function(cm, motionArgs) {
var repeat = motionArgs.repeat;
recordLastCharacterSearch(0, motionArgs);
return moveToCharacter(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter) || cm.getCursor();
},
moveToSymbol: function(cm, motionArgs) {
var repeat = motionArgs.repeat;
return findSymbol(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter) || cm.getCursor();
},
moveToColumn: function(cm, motionArgs, vim) {
var repeat = motionArgs.repeat;
// repeat is equivalent to which column we want to move to!
vim.lastHPos = repeat - 1;
vim.lastHSPos = cm.charCoords(cm.getCursor(),'div').left;
return moveToColumn(cm, repeat);
},
moveToEol: function(cm, motionArgs, vim) {
var cur = cm.getCursor();
vim.lastHPos = Infinity;
var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
var end=cm.clipPos(retval);
end.ch--;
vim.lastHSPos = cm.charCoords(end,'div').left;
return retval;
},
moveToFirstNonWhiteSpaceCharacter: function(cm) {
// Go to the start of the line where the text begins, or the end for
// whitespace-only lines
var cursor = cm.getCursor();
return Pos(cursor.line,
findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
},
moveToMatchedSymbol: function(cm) {
var cursor = cm.getCursor();
var line = cursor.line;
var ch = cursor.ch;
var lineText = cm.getLine(line);
var symbol;
do {
symbol = lineText.charAt(ch++);
if (symbol && isMatchableSymbol(symbol)) {
var style = cm.getTokenTypeAt(Pos(line, ch));
if (style !== "string" && style !== "comment") {
break;
}
}
} while (symbol);
if (symbol) {
var matched = cm.findMatchingBracket(Pos(line, ch));
return matched.to;
} else {
return cursor;
}
},
moveToStartOfLine: function(cm) {
var cursor = cm.getCursor();
return Pos(cursor.line, 0);
},
moveToLineOrEdgeOfDocument: function(cm, motionArgs) {
var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
if (motionArgs.repeatIsExplicit) {
lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
}
return Pos(lineNum,
findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
},
textObjectManipulation: function(cm, motionArgs) {
// TODO: lots of possible exceptions that can be thrown here. Try da(
// outside of a () block.
// TODO: adding <> >< to this map doesn't work, presumably because
// they're operators
var mirroredPairs = {'(': ')', ')': '(',
'{': '}', '}': '{',
'[': ']', ']': '['};
var selfPaired = {'\'': true, '"': true};
var character = motionArgs.selectedCharacter;
// 'b' refers to '()' block.
// 'B' refers to '{}' block.
if (character == 'b') {
character = '(';
} else if (character == 'B') {
character = '{';
}
// Inclusive is the difference between a and i
// TODO: Instead of using the additional text object map to perform text
// object operations, merge the map into the defaultKeyMap and use
// motionArgs to define behavior. Define separate entries for 'aw',
// 'iw', 'a[', 'i[', etc.
var inclusive = !motionArgs.textObjectInner;
var tmp;
if (mirroredPairs[character]) {
tmp = selectCompanionObject(cm, character, inclusive);
} else if (selfPaired[character]) {
tmp = findBeginningAndEnd(cm, character, inclusive);
} else if (character === 'W') {
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
true /** bigWord */);
} else if (character === 'w') {
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
false /** bigWord */);
} else {
// No text object defined for this, don't move.
return null;
}
return [tmp.start, tmp.end];
},
repeatLastCharacterSearch: function(cm, motionArgs) {
var lastSearch = vimGlobalState.lastChararacterSearch;
var repeat = motionArgs.repeat;
var forward = motionArgs.forward === lastSearch.forward;
var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
cm.moveH(-increment, 'char');
motionArgs.inclusive = forward ? true : false;
var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
if (!curEnd) {
cm.moveH(increment, 'char');
return cm.getCursor();
}
curEnd.ch += increment;
return curEnd;
}
};
var operators = {
change: function(cm, operatorArgs, _vim, curStart, curEnd) {
vimGlobalState.registerController.pushText(
operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd),
operatorArgs.linewise);
if (operatorArgs.linewise) {
// Push the next line back down, if there is a next line.
var replacement = curEnd.line > cm.lastLine() ? '' : '\n';
cm.replaceRange(replacement, curStart, curEnd);
cm.indentLine(curStart.line, 'smart');
// null ch so setCursor moves to end of line.
curStart.ch = null;
} else {
// Exclude trailing whitespace if the range is not all whitespace.
var text = cm.getRange(curStart, curEnd);
if (!isWhiteSpaceString(text)) {
var match = (/\s+$/).exec(text);
if (match) {
curEnd = offsetCursor(curEnd, 0, - match[0].length);
}
}
cm.replaceRange('', curStart, curEnd);
}
actions.enterInsertMode(cm, {}, cm.state.vim);
cm.setCursor(curStart);
},
// delete is a javascript keyword.
'delete': function(cm, operatorArgs, _vim, curStart, curEnd) {
// If the ending line is past the last line, inclusive, instead of
// including the trailing \n, include the \n before the starting line
if (operatorArgs.linewise &&
curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) {
curStart.line--;
curStart.ch = lineLength(cm, curStart.line);
}
vimGlobalState.registerController.pushText(
operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd),
operatorArgs.linewise);
cm.replaceRange('', curStart, curEnd);
if (operatorArgs.linewise) {
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
} else {
cm.setCursor(curStart);
}
},
indent: function(cm, operatorArgs, vim, curStart, curEnd) {
var startLine = curStart.line;
var endLine = curEnd.line;
// In visual mode, n> shifts the selection right n times, instead of
// shifting n lines right once.
var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
if (operatorArgs.linewise) {
// The only way to delete a newline is to delete until the start of
// the next line, so in linewise mode evalInput will include the next
// line. We don't want this in indent, so we go back a line.
endLine--;
}
for (var i = startLine; i <= endLine; i++) {
for (var j = 0; j < repeat; j++) {
cm.indentLine(i, operatorArgs.indentRight);
}
}
cm.setCursor(curStart);
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
},
swapcase: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
var toSwap = cm.getRange(curStart, curEnd);
var swapped = '';
for (var i = 0; i < toSwap.length; i++) {
var character = toSwap.charAt(i);
swapped += isUpperCase(character) ? character.toLowerCase() :
character.toUpperCase();
}
cm.replaceRange(swapped, curStart, curEnd);
if (!operatorArgs.shouldMoveCursor) {
cm.setCursor(curOriginal);
}
},
yank: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
vimGlobalState.registerController.pushText(
operatorArgs.registerName, 'yank',
cm.getRange(curStart, curEnd), operatorArgs.linewise);
cm.setCursor(curOriginal);
}
};
var actions = {
jumpListWalk: function(cm, actionArgs, vim) {
if (vim.visualMode) {
return;
}
var repeat = actionArgs.repeat;
var forward = actionArgs.forward;
var jumpList = vimGlobalState.jumpList;
var mark = jumpList.move(cm, forward ? repeat : -repeat);
var markPos = mark ? mark.find() : undefined;
markPos = markPos ? markPos : cm.getCursor();
cm.setCursor(markPos);
},
scroll: function(cm, actionArgs, vim) {
if (vim.visualMode) {
return;
}
var repeat = actionArgs.repeat || 1;
var lineHeight = cm.defaultTextHeight();
var top = cm.getScrollInfo().top;
var delta = lineHeight * repeat;
var newPos = actionArgs.forward ? top + delta : top - delta;
var cursor = copyCursor(cm.getCursor());
var cursorCoords = cm.charCoords(cursor, 'local');
if (actionArgs.forward) {
if (newPos > cursorCoords.top) {
cursor.line += (newPos - cursorCoords.top) / lineHeight;
cursor.line = Math.ceil(cursor.line);
cm.setCursor(cursor);
cursorCoords = cm.charCoords(cursor, 'local');
cm.scrollTo(null, cursorCoords.top);
} else {
// Cursor stays within bounds. Just reposition the scroll window.
cm.scrollTo(null, newPos);
}
} else {
var newBottom = newPos + cm.getScrollInfo().clientHeight;
if (newBottom < cursorCoords.bottom) {
cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
cursor.line = Math.floor(cursor.line);
cm.setCursor(cursor);
cursorCoords = cm.charCoords(cursor, 'local');
cm.scrollTo(
null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
} else {
// Cursor stays within bounds. Just reposition the scroll window.
cm.scrollTo(null, newPos);
}
}
},
scrollToCursor: function(cm, actionArgs) {
var lineNum = cm.getCursor().line;
var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');
var height = cm.getScrollInfo().clientHeight;
var y = charCoords.top;
var lineHeight = charCoords.bottom - y;
switch (actionArgs.position) {
case 'center': y = y - (height / 2) + lineHeight;
break;
case 'bottom': y = y - height + lineHeight*1.4;
break;
case 'top': y = y + lineHeight*0.4;
break;
}
cm.scrollTo(null, y);
},
replayMacro: function(cm, actionArgs, vim) {
var registerName = actionArgs.selectedCharacter;
var repeat = actionArgs.repeat;
var macroModeState = vimGlobalState.macroModeState;
if (registerName == '@') {
registerName = macroModeState.latestRegister;
}
while(repeat--){
executeMacroRegister(cm, vim, macroModeState, registerName);
}
},
enterMacroRecordMode: function(cm, actionArgs) {
var macroModeState = vimGlobalState.macroModeState;
var registerName = actionArgs.selectedCharacter;
macroModeState.enterMacroRecordMode(cm, registerName);
},
enterInsertMode: function(cm, actionArgs, vim) {
if (cm.getOption('readOnly')) { return; }
vim.insertMode = true;
vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
var insertAt = (actionArgs) ? actionArgs.insertAt : null;
if (insertAt == 'eol') {
var cursor = cm.getCursor();
cursor = Pos(cursor.line, lineLength(cm, cursor.line));
cm.setCursor(cursor);
} else if (insertAt == 'charAfter') {
cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
} else if (insertAt == 'firstNonBlank') {
cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
}
cm.setOption('keyMap', 'vim-insert');
cm.setOption('disableInput', false);
if (actionArgs && actionArgs.replace) {
// Handle Replace-mode as a special case of insert mode.
cm.toggleOverwrite(true);
cm.setOption('keyMap', 'vim-replace');
CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
} else {
cm.setOption('keyMap', 'vim-insert');
CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
}
if (!vimGlobalState.macroModeState.isPlaying) {
// Only record if not replaying.
cm.on('change', onChange);
CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
}
},
toggleVisualMode: function(cm, actionArgs, vim) {
var repeat = actionArgs.repeat;
var curStart = cm.getCursor();
var curEnd;
// TODO: The repeat should actually select number of characters/lines
// equal to the repeat times the size of the previous visual
// operation.
if (!vim.visualMode) {
cm.on('mousedown', exitVisualMode);
vim.visualMode = true;
vim.visualLine = !!actionArgs.linewise;
if (vim.visualLine) {
curStart.ch = 0;
curEnd = clipCursorToContent(
cm, Pos(curStart.line + repeat - 1, lineLength(cm, curStart.line)),
true /** includeLineBreak */);
} else {
curEnd = clipCursorToContent(
cm, Pos(curStart.line, curStart.ch + repeat),
true /** includeLineBreak */);
}
// Make the initial selection.
if (!actionArgs.repeatIsExplicit && !vim.visualLine) {
// This is a strange case. Here the implicit repeat is 1. The
// following commands lets the cursor hover over the 1 character
// selection.
cm.setCursor(curEnd);
cm.setSelection(curEnd, curStart);
} else {
cm.setSelection(curStart, curEnd);
}
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
} else {
curStart = cm.getCursor('anchor');
curEnd = cm.getCursor('head');
if (!vim.visualLine && actionArgs.linewise) {
// Shift-V pressed in characterwise visual mode. Switch to linewise
// visual mode instead of exiting visual mode.
vim.visualLine = true;
curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
lineLength(cm, curStart.line);
curEnd.ch = cursorIsBefore(curStart, curEnd) ?
lineLength(cm, curEnd.line) : 0;
cm.setSelection(curStart, curEnd);
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: "linewise"});
} else if (vim.visualLine && !actionArgs.linewise) {
// v pressed in linewise visual mode. Switch to characterwise visual
// mode instead of exiting visual mode.
vim.visualLine = false;
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
} else {
exitVisualMode(cm);
}
}
updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
: curEnd);
updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
: curStart);
},
reselectLastSelection: function(cm, _actionArgs, vim) {
if (vim.lastSelection) {
var lastSelection = vim.lastSelection;
cm.setSelection(lastSelection.curStart, lastSelection.curEnd);
if (lastSelection.visualLine) {
vim.visualMode = true;
vim.visualLine = true;
}
else {
vim.visualMode = true;
vim.visualLine = false;
}
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
}
},
joinLines: function(cm, actionArgs, vim) {
var curStart, curEnd;
if (vim.visualMode) {
curStart = cm.getCursor('anchor');
curEnd = cm.getCursor('head');
curEnd.ch = lineLength(cm, curEnd.line) - 1;
} else {
// Repeat is the number of lines to join. Minimum 2 lines.
var repeat = Math.max(actionArgs.repeat, 2);
curStart = cm.getCursor();
curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,
Infinity));
}
var finalCh = 0;
cm.operation(function() {
for (var i = curStart.line; i < curEnd.line; i++) {
finalCh = lineLength(cm, curStart.line);
var tmp = Pos(curStart.line + 1,
lineLength(cm, curStart.line + 1));
var text = cm.getRange(curStart, tmp);
text = text.replace(/\n\s*/g, ' ');
cm.replaceRange(text, curStart, tmp);
}
var curFinalPos = Pos(curStart.line, finalCh);
cm.setCursor(curFinalPos);
});
},
newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
vim.insertMode = true;
var insertAt = copyCursor(cm.getCursor());
if (insertAt.line === cm.firstLine() && !actionArgs.after) {
// Special case for inserting newline before start of document.
cm.replaceRange('\n', Pos(cm.firstLine(), 0));
cm.setCursor(cm.firstLine(), 0);
} else {
insertAt.line = (actionArgs.after) ? insertAt.line :
insertAt.line - 1;
insertAt.ch = lineLength(cm, insertAt.line);
cm.setCursor(insertAt);
var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
CodeMirror.commands.newlineAndIndent;
newlineFn(cm);
}
this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
},
paste: function(cm, actionArgs) {
var cur = copyCursor(cm.getCursor());
var register = vimGlobalState.registerController.getRegister(
actionArgs.registerName);
var text = register.toString();
if (!text) {
return;
}
if (actionArgs.matchIndent) {
// length that considers tabs and cm.options.tabSize
var whitespaceLength = function(str) {
var tabs = (str.split("\t").length - 1);
var spaces = (str.split(" ").length - 1);
return tabs * cm.options.tabSize + spaces * 1;
};
var currentLine = cm.getLine(cm.getCursor().line);
var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
// chomp last newline b/c don't want it to match /^\s*/gm
var chompedText = text.replace(/\n$/, '');
var wasChomped = text !== chompedText;
var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
var text = chompedText.replace(/^\s*/gm, function(wspace) {
var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
if (newIndent < 0) {
return "";
}
else if (cm.options.indentWithTabs) {
var quotient = Math.floor(newIndent / cm.options.tabSize);
return Array(quotient + 1).join('\t');
}
else {
return Array(newIndent + 1).join(' ');
}
});
text += wasChomped ? "\n" : "";
}
if (actionArgs.repeat > 1) {
var text = Array(actionArgs.repeat + 1).join(text);
}
var linewise = register.linewise;
if (linewise) {
if (actionArgs.after) {
// Move the newline at the end to the start instead, and paste just
// before the newline character of the line we are on right now.
text = '\n' + text.slice(0, text.length - 1);
cur.ch = lineLength(cm, cur.line);
} else {
cur.ch = 0;
}
} else {
cur.ch += actionArgs.after ? 1 : 0;
}
cm.replaceRange(text, cur);
// Now fine tune the cursor to where we want it.
var curPosFinal;
var idx;
if (linewise && actionArgs.after) {
curPosFinal = Pos(
cur.line + 1,
findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
} else if (linewise && !actionArgs.after) {
curPosFinal = Pos(
cur.line,
findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
} else if (!linewise && actionArgs.after) {
idx = cm.indexFromPos(cur);
curPosFinal = cm.posFromIndex(idx + text.length - 1);
} else {
idx = cm.indexFromPos(cur);
curPosFinal = cm.posFromIndex(idx + text.length);
}
cm.setCursor(curPosFinal);
},
undo: function(cm, actionArgs) {
cm.operation(function() {
repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
cm.setCursor(cm.getCursor('anchor'));
});
},
redo: function(cm, actionArgs) {
repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
},
setRegister: function(_cm, actionArgs, vim) {
vim.inputState.registerName = actionArgs.selectedCharacter;
},
setMark: function(cm, actionArgs, vim) {
var markName = actionArgs.selectedCharacter;
updateMark(cm, vim, markName, cm.getCursor());
},
replace: function(cm, actionArgs, vim) {
var replaceWith = actionArgs.selectedCharacter;
var curStart = cm.getCursor();
var replaceTo;
var curEnd;
if (vim.visualMode){
curStart=cm.getCursor('start');
curEnd=cm.getCursor('end');
// workaround to catch the character under the cursor
// existing workaround doesn't cover actions
curEnd=cm.clipPos(Pos(curEnd.line, curEnd.ch+1));
}else{
var line = cm.getLine(curStart.line);
replaceTo = curStart.ch + actionArgs.repeat;
if (replaceTo > line.length) {
replaceTo=line.length;
}
curEnd = Pos(curStart.line, replaceTo);
}
if (replaceWith=='\n'){
if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
// special case, where vim help says to replace by just one line-break
(CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
}else {
var replaceWithStr=cm.getRange(curStart, curEnd);
//replace all characters in range by selected, but keep linebreaks
replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);
cm.replaceRange(replaceWithStr, curStart, curEnd);
if (vim.visualMode){
cm.setCursor(curStart);
exitVisualMode(cm);
}else{
cm.setCursor(offsetCursor(curEnd, 0, -1));
}
}
},
incrementNumberToken: function(cm, actionArgs) {
var cur = cm.getCursor();
var lineStr = cm.getLine(cur.line);
var re = /-?\d+/g;
var match;
var start;
var end;
var numberStr;
var token;
while ((match = re.exec(lineStr)) !== null) {
token = match[0];
start = match.index;
end = start + token.length;
if (cur.ch < end)break;
}
if (!actionArgs.backtrack && (end <= cur.ch))return;
if (token) {
var increment = actionArgs.increase ? 1 : -1;
var number = parseInt(token) + (increment * actionArgs.repeat);
var from = Pos(cur.line, start);
var to = Pos(cur.line, end);
numberStr = number.toString();
cm.replaceRange(numberStr, from, to);
} else {
return;
}
cm.setCursor(Pos(cur.line, start + numberStr.length - 1));
},
repeatLastEdit: function(cm, actionArgs, vim) {
var lastEditInputState = vim.lastEditInputState;
if (!lastEditInputState) { return; }
var repeat = actionArgs.repeat;
if (repeat && actionArgs.repeatIsExplicit) {
vim.lastEditInputState.repeatOverride = repeat;
} else {
repeat = vim.lastEditInputState.repeatOverride || repeat;
}
repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
},
changeCase: function(cm, actionArgs, vim) {
var selectedAreaRange = getSelectedAreaRange(cm, vim);
var selectionStart = selectedAreaRange[0];
var selectionEnd = selectedAreaRange[1];
var toLower = actionArgs.toLower;
if (cursorIsBefore(selectionEnd, selectionStart)) {
var tmp = selectionStart;
selectionStart = selectionEnd;
selectionEnd = tmp;
} else {
selectionEnd = cm.clipPos(Pos(selectionEnd.line, selectionEnd.ch+1));
}
var text = cm.getRange(selectionStart, selectionEnd);
cm.replaceRange(toLower ? text.toLowerCase() : text.toUpperCase(), selectionStart, selectionEnd);
cm.setCursor(selectionStart);
}
};
/*
* Below are miscellaneous utility functions used by vim.js
*/
/**
* Clips cursor to ensure that line is within the buffer's range
* If includeLineBreak is true, then allow cur.ch == lineLength.
*/
function clipCursorToContent(cm, cur, includeLineBreak) {
var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
var maxCh = lineLength(cm, line) - 1;
maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
var ch = Math.min(Math.max(0, cur.ch), maxCh);
return Pos(line, ch);
}
function copyArgs(args) {
var ret = {};
for (var prop in args) {
if (args.hasOwnProperty(prop)) {
ret[prop] = args[prop];
}
}
return ret;
}
function offsetCursor(cur, offsetLine, offsetCh) {
return Pos(cur.line + offsetLine, cur.ch + offsetCh);
}
function matchKeysPartial(pressed, mapped) {
for (var i = 0; i < pressed.length; i++) {
// 'character' means any character. For mark, register commads, etc.
if (pressed[i] != mapped[i] && mapped[i] != 'character') {
return false;
}
}
return true;
}
function repeatFn(cm, fn, repeat) {
return function() {
for (var i = 0; i < repeat; i++) {
fn(cm);
}
};
}
function copyCursor(cur) {
return Pos(cur.line, cur.ch);
}
function cursorEqual(cur1, cur2) {
return cur1.ch == cur2.ch && cur1.line == cur2.line;
}
function cursorIsBefore(cur1, cur2) {
if (cur1.line < cur2.line) {
return true;
}
if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
return true;
}
return false;
}
function cusrorIsBetween(cur1, cur2, cur3) {
// returns true if cur2 is between cur1 and cur3.
var cur1before2 = cursorIsBefore(cur1, cur2);
var cur2before3 = cursorIsBefore(cur2, cur3);
return cur1before2 && cur2before3;
}
function lineLength(cm, lineNum) {
return cm.getLine(lineNum).length;
}
function reverse(s){
return s.split('').reverse().join('');
}
function trim(s) {
if (s.trim) {
return s.trim();
}
return s.replace(/^\s+|\s+$/g, '');
}
function escapeRegex(s) {
return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
}
function getSelectedAreaRange(cm, vim) {
var selectionStart = cm.getCursor('anchor');
var selectionEnd = cm.getCursor('head');
var lastSelection = vim.lastSelection;
if (!vim.visualMode) {
var line = lastSelection.curEnd.line - lastSelection.curStart.line;
var ch = line ? lastSelection.curEnd.ch : lastSelection.curEnd.ch - lastSelection.curStart.ch;
selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
if (lastSelection.visualLine) {
return [{line: selectionStart.line, ch: 0}, {line: selectionEnd.line, ch: lineLength(cm, selectionEnd.line)}];
}
} else {
exitVisualMode(cm);
}
return [selectionStart, selectionEnd];
}
function exitVisualMode(cm) {
cm.off('mousedown', exitVisualMode);
var vim = cm.state.vim;
// can't use selection state here because yank has already reset its cursor
vim.lastSelection = {'curStart': vim.marks['<'].find(),
'curEnd': vim.marks['>'].find(), 'visualMode': vim.visualMode,
'visualLine': vim.visualLine};
vim.visualMode = false;
vim.visualLine = false;
var selectionStart = cm.getCursor('anchor');
var selectionEnd = cm.getCursor('head');
if (!cursorEqual(selectionStart, selectionEnd)) {
// Clear the selection and set the cursor only if the selection has not
// already been cleared. Otherwise we risk moving the cursor somewhere
// it's not supposed to be.
cm.setCursor(clipCursorToContent(cm, selectionEnd));
}
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
}
// Remove any trailing newlines from the selection. For
// example, with the caret at the start of the last word on the line,
// 'dw' should word, but not the newline, while 'w' should advance the
// caret to the first character of the next line.
function clipToLine(cm, curStart, curEnd) {
var selection = cm.getRange(curStart, curEnd);
// Only clip if the selection ends with trailing newline + whitespace
if (/\n\s*$/.test(selection)) {
var lines = selection.split('\n');
// We know this is all whitepsace.
lines.pop();
// Cases:
// 1. Last word is an empty line - do not clip the trailing '\n'
// 2. Last word is not an empty line - clip the trailing '\n'
var line;
// Find the line containing the last word, and clip all whitespace up
// to it.
for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
curEnd.line--;
curEnd.ch = 0;
}
// If the last word is not an empty line, clip an additional newline
if (line) {
curEnd.line--;
curEnd.ch = lineLength(cm, curEnd.line);
} else {
curEnd.ch = 0;
}
}
}
// Expand the selection to line ends.
function expandSelectionToLine(_cm, curStart, curEnd) {
curStart.ch = 0;
curEnd.ch = 0;
curEnd.line++;
}
function findFirstNonWhiteSpaceCharacter(text) {
if (!text) {
return 0;
}
var firstNonWS = text.search(/\S/);
return firstNonWS == -1 ? text.length : firstNonWS;
}
function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
var cur = cm.getCursor();
var line = cm.getLine(cur.line);
var idx = cur.ch;
// Seek to first word or non-whitespace character, depending on if
// noSymbol is true.
var textAfterIdx = line.substring(idx);
var firstMatchedChar;
if (noSymbol) {
firstMatchedChar = textAfterIdx.search(/\w/);
} else {
firstMatchedChar = textAfterIdx.search(/\S/);
}
if (firstMatchedChar == -1) {
return null;
}
idx += firstMatchedChar;
textAfterIdx = line.substring(idx);
var textBeforeIdx = line.substring(0, idx);
var matchRegex;
// Greedy matchers for the "word" we are trying to expand.
if (bigWord) {
matchRegex = /^\S+/;
} else {
if ((/\w/).test(line.charAt(idx))) {
matchRegex = /^\w+/;
} else {
matchRegex = /^[^\w\s]+/;
}
}
var wordAfterRegex = matchRegex.exec(textAfterIdx);
var wordStart = idx;
var wordEnd = idx + wordAfterRegex[0].length;
// TODO: Find a better way to do this. It will be slow on very long lines.
var revTextBeforeIdx = reverse(textBeforeIdx);
var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx);
if (wordBeforeRegex) {
wordStart -= wordBeforeRegex[0].length;
}
if (inclusive) {
// If present, trim all whitespace after word.
// Otherwise, trim all whitespace before word.
var textAfterWordEnd = line.substring(wordEnd);
var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length;
if (whitespacesAfterWord > 0) {
wordEnd += whitespacesAfterWord;
} else {
var revTrim = revTextBeforeIdx.length - wordStart;
var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
wordStart -= whitespacesBeforeWord;
}
}
return { start: Pos(cur.line, wordStart),
end: Pos(cur.line, wordEnd) };
}
function recordJumpPosition(cm, oldCur, newCur) {
if (!cursorEqual(oldCur, newCur)) {
vimGlobalState.jumpList.add(cm, oldCur, newCur);
}
}
function recordLastCharacterSearch(increment, args) {
vimGlobalState.lastChararacterSearch.increment = increment;
vimGlobalState.lastChararacterSearch.forward = args.forward;
vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
}
var symbolToMode = {
'(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
'[': 'section', ']': 'section',
'*': 'comment', '/': 'comment',
'm': 'method', 'M': 'method',
'#': 'preprocess'
};
var findSymbolModes = {
bracket: {
isComplete: function(state) {
if (state.nextCh === state.symb) {
state.depth++;
if (state.depth >= 1)return true;
} else if (state.nextCh === state.reverseSymb) {
state.depth--;
}
return false;
}
},
section: {
init: function(state) {
state.curMoveThrough = true;
state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
},
isComplete: function(state) {
return state.index === 0 && state.nextCh === state.symb;
}
},
comment: {
isComplete: function(state) {
var found = state.lastCh === '*' && state.nextCh === '/';
state.lastCh = state.nextCh;
return found;
}
},
// TODO: The original Vim implementation only operates on level 1 and 2.
// The current implementation doesn't check for code block level and
// therefore it operates on any levels.
method: {
init: function(state) {
state.symb = (state.symb === 'm' ? '{' : '}');
state.reverseSymb = state.symb === '{' ? '}' : '{';
},
isComplete: function(state) {
if (state.nextCh === state.symb)return true;
return false;
}
},
preprocess: {
init: function(state) {
state.index = 0;
},
isComplete: function(state) {
if (state.nextCh === '#') {
var token = state.lineText.match(/#(\w+)/)[1];
if (token === 'endif') {
if (state.forward && state.depth === 0) {
return true;
}
state.depth++;
} else if (token === 'if') {
if (!state.forward && state.depth === 0) {
return true;
}
state.depth--;
}
if (token === 'else' && state.depth === 0)return true;
}
return false;
}
}
};
function findSymbol(cm, repeat, forward, symb) {
var cur = copyCursor(cm.getCursor());
var increment = forward ? 1 : -1;
var endLine = forward ? cm.lineCount() : -1;
var curCh = cur.ch;
var line = cur.line;
var lineText = cm.getLine(line);
var state = {
lineText: lineText,
nextCh: lineText.charAt(curCh),
lastCh: null,
index: curCh,
symb: symb,
reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
forward: forward,
depth: 0,
curMoveThrough: false
};
var mode = symbolToMode[symb];
if (!mode)return cur;
var init = findSymbolModes[mode].init;
var isComplete = findSymbolModes[mode].isComplete;
if (init) { init(state); }
while (line !== endLine && repeat) {
state.index += increment;
state.nextCh = state.lineText.charAt(state.index);
if (!state.nextCh) {
line += increment;
state.lineText = cm.getLine(line) || '';
if (increment > 0) {
state.index = 0;
} else {
var lineLen = state.lineText.length;
state.index = (lineLen > 0) ? (lineLen-1) : 0;
}
state.nextCh = state.lineText.charAt(state.index);
}
if (isComplete(state)) {
cur.line = line;
cur.ch = state.index;
repeat--;
}
}
if (state.nextCh || state.curMoveThrough) {
return Pos(line, state.index);
}
return cur;
}
/*
* Returns the boundaries of the next word. If the cursor in the middle of
* the word, then returns the boundaries of the current word, starting at
* the cursor. If the cursor is at the start/end of a word, and we are going
* forward/backward, respectively, find the boundaries of the next word.
*
* @param {CodeMirror} cm CodeMirror object.
* @param {Cursor} cur The cursor position.
* @param {boolean} forward True to search forward. False to search
* backward.
* @param {boolean} bigWord True if punctuation count as part of the word.
* False if only [a-zA-Z0-9] characters count as part of the word.
* @param {boolean} emptyLineIsWord True if empty lines should be treated
* as words.
* @return {Object{from:number, to:number, line: number}} The boundaries of
* the word, or null if there are no more words.
*/
function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
var lineNum = cur.line;
var pos = cur.ch;
var line = cm.getLine(lineNum);
var dir = forward ? 1 : -1;
var regexps = bigWord ? bigWordRegexp : wordRegexp;
if (emptyLineIsWord && line == '') {
lineNum += dir;
line = cm.getLine(lineNum);
if (!isLine(cm, lineNum)) {
return null;
}
pos = (forward) ? 0 : line.length;
}
while (true) {
if (emptyLineIsWord && line == '') {
return { from: 0, to: 0, line: lineNum };
}
var stop = (dir > 0) ? line.length : -1;
var wordStart = stop, wordEnd = stop;
// Find bounds of next word.
while (pos != stop) {
var foundWord = false;
for (var i = 0; i < regexps.length && !foundWord; ++i) {
if (regexps[i].test(line.charAt(pos))) {
wordStart = pos;
// Advance to end of word.
while (pos != stop && regexps[i].test(line.charAt(pos))) {
pos += dir;
}
wordEnd = pos;
foundWord = wordStart != wordEnd;
if (wordStart == cur.ch && lineNum == cur.line &&
wordEnd == wordStart + dir) {
// We started at the end of a word. Find the next one.
continue;
} else {
return {
from: Math.min(wordStart, wordEnd + 1),
to: Math.max(wordStart, wordEnd),
line: lineNum };
}
}
}
if (!foundWord) {
pos += dir;
}
}
// Advance to next/prev line.
lineNum += dir;
if (!isLine(cm, lineNum)) {
return null;
}
line = cm.getLine(lineNum);
pos = (dir > 0) ? 0 : line.length;
}
// Should never get here.
throw new Error('The impossible happened.');
}
/**
* @param {CodeMirror} cm CodeMirror object.
* @param {int} repeat Number of words to move past.
* @param {boolean} forward True to search forward. False to search
* backward.
* @param {boolean} wordEnd True to move to end of word. False to move to
* beginning of word.
* @param {boolean} bigWord True if punctuation count as part of the word.
* False if only alphabet characters count as part of the word.
* @return {Cursor} The position the cursor should move to.
*/
function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
var cur = cm.getCursor();
var curStart = copyCursor(cur);
var words = [];
if (forward && !wordEnd || !forward && wordEnd) {
repeat++;
}
// For 'e', empty lines are not considered words, go figure.
var emptyLineIsWord = !(forward && wordEnd);
for (var i = 0; i < repeat; i++) {
var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
if (!word) {
var eodCh = lineLength(cm, cm.lastLine());
words.push(forward
? {line: cm.lastLine(), from: eodCh, to: eodCh}
: {line: 0, from: 0, to: 0});
break;
}
words.push(word);
cur = Pos(word.line, forward ? (word.to - 1) : word.from);
}
var shortCircuit = words.length != repeat;
var firstWord = words[0];
var lastWord = words.pop();
if (forward && !wordEnd) {
// w
if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
// We did not start in the middle of a word. Discard the extra word at the end.
lastWord = words.pop();
}
return Pos(lastWord.line, lastWord.from);
} else if (forward && wordEnd) {
return Pos(lastWord.line, lastWord.to - 1);
} else if (!forward && wordEnd) {
// ge
if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
// We did not start in the middle of a word. Discard the extra word at the end.
lastWord = words.pop();
}
return Pos(lastWord.line, lastWord.to);
} else {
// b
return Pos(lastWord.line, lastWord.from);
}
}
function moveToCharacter(cm, repeat, forward, character) {
var cur = cm.getCursor();
var start = cur.ch;
var idx;
for (var i = 0; i < repeat; i ++) {
var line = cm.getLine(cur.line);
idx = charIdxInLine(start, line, character, forward, true);
if (idx == -1) {
return null;
}
start = idx;
}
return Pos(cm.getCursor().line, idx);
}
function moveToColumn(cm, repeat) {
// repeat is always >= 1, so repeat - 1 always corresponds
// to the column we want to go to.
var line = cm.getCursor().line;
return clipCursorToContent(cm, Pos(line, repeat - 1));
}
function updateMark(cm, vim, markName, pos) {
if (!inArray(markName, validMarks)) {
return;
}
if (vim.marks[markName]) {
vim.marks[markName].clear();
}
vim.marks[markName] = cm.setBookmark(pos);
}
function charIdxInLine(start, line, character, forward, includeChar) {
// Search for char in line.
// motion_options: {forward, includeChar}
// If includeChar = true, include it too.
// If forward = true, search forward, else search backwards.
// If char is not found on this line, do nothing
var idx;
if (forward) {
idx = line.indexOf(character, start + 1);
if (idx != -1 && !includeChar) {
idx -= 1;
}
} else {
idx = line.lastIndexOf(character, start - 1);
if (idx != -1 && !includeChar) {
idx += 1;
}
}
return idx;
}
// TODO: perhaps this finagling of start and end positions belonds
// in codmirror/replaceRange?
function selectCompanionObject(cm, symb, inclusive) {
var cur = cm.getCursor(), start, end;
var bracketRegexp = ({
'(': /[()]/, ')': /[()]/,
'[': /[[\]]/, ']': /[[\]]/,
'{': /[{}]/, '}': /[{}]/})[symb];
var openSym = ({
'(': '(', ')': '(',
'[': '[', ']': '[',
'{': '{', '}': '{'})[symb];
var curChar = cm.getLine(cur.line).charAt(cur.ch);
// Due to the behavior of scanForBracket, we need to add an offset if the
// cursor is on a matching open bracket.
var offset = curChar === openSym ? 1 : 0;
start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp});
end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp});
if (!start || !end) {
return { start: cur, end: cur };
}
start = start.pos;
end = end.pos;
if ((start.line == end.line && start.ch > end.ch)
|| (start.line > end.line)) {
var tmp = start;
start = end;
end = tmp;
}
if (inclusive) {
end.ch += 1;
} else {
start.ch += 1;
}
return { start: start, end: end };
}
// Takes in a symbol and a cursor and tries to simulate text objects that
// have identical opening and closing symbols
// TODO support across multiple lines
function findBeginningAndEnd(cm, symb, inclusive) {
var cur = copyCursor(cm.getCursor());
var line = cm.getLine(cur.line);
var chars = line.split('');
var start, end, i, len;
var firstIndex = chars.indexOf(symb);
// the decision tree is to always look backwards for the beginning first,
// but if the cursor is in front of the first instance of the symb,
// then move the cursor forward
if (cur.ch < firstIndex) {
cur.ch = firstIndex;
// Why is this line even here???
// cm.setCursor(cur.line, firstIndex+1);
}
// otherwise if the cursor is currently on the closing symbol
else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
end = cur.ch; // assign end to the current cursor
--cur.ch; // make sure to look backwards
}
// if we're currently on the symbol, we've got a start
if (chars[cur.ch] == symb && !end) {
start = cur.ch + 1; // assign start to ahead of the cursor
} else {
// go backwards to find the start
for (i = cur.ch; i > -1 && !start; i--) {
if (chars[i] == symb) {
start = i + 1;
}
}
}
// look forwards for the end symbol
if (start && !end) {
for (i = start, len = chars.length; i < len && !end; i++) {
if (chars[i] == symb) {
end = i;
}
}
}
// nothing found
if (!start || !end) {
return { start: cur, end: cur };
}
// include the symbols
if (inclusive) {
--start; ++end;
}
return {
start: Pos(cur.line, start),
end: Pos(cur.line, end)
};
}
// Search functions
defineOption('pcre', true, 'boolean');
function SearchState() {}
SearchState.prototype = {
getQuery: function() {
return vimGlobalState.query;
},
setQuery: function(query) {
vimGlobalState.query = query;
},
getOverlay: function() {
return this.searchOverlay;
},
setOverlay: function(overlay) {
this.searchOverlay = overlay;
},
isReversed: function() {
return vimGlobalState.isReversed;
},
setReversed: function(reversed) {
vimGlobalState.isReversed = reversed;
}
};
function getSearchState(cm) {
var vim = cm.state.vim;
return vim.searchState_ || (vim.searchState_ = new SearchState());
}
function dialog(cm, template, shortText, onClose, options) {
if (cm.openDialog) {
cm.openDialog(template, onClose, { bottom: true, value: options.value,
onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp });
}
else {
onClose(prompt(shortText, ''));
}
}
function findUnescapedSlashes(str) {
var escapeNextChar = false;
var slashes = [];
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (!escapeNextChar && c == '/') {
slashes.push(i);
}
escapeNextChar = !escapeNextChar && (c == '\\');
}
return slashes;
}
// Translates a search string from ex (vim) syntax into javascript form.
function translateRegex(str) {
// When these match, add a '\' if unescaped or remove one if escaped.
var specials = '|(){';
// Remove, but never add, a '\' for these.
var unescape = '}';
var escapeNextChar = false;
var out = [];
for (var i = -1; i < str.length; i++) {
var c = str.charAt(i) || '';
var n = str.charAt(i+1) || '';
var specialComesNext = (n && specials.indexOf(n) != -1);
if (escapeNextChar) {
if (c !== '\\' || !specialComesNext) {
out.push(c);
}
escapeNextChar = false;
} else {
if (c === '\\') {
escapeNextChar = true;
// Treat the unescape list as special for removing, but not adding '\'.
if (n && unescape.indexOf(n) != -1) {
specialComesNext = true;
}
// Not passing this test means removing a '\'.
if (!specialComesNext || n === '\\') {
out.push(c);
}
} else {
out.push(c);
if (specialComesNext && n !== '\\') {
out.push('\\');
}
}
}
}
return out.join('');
}
// Translates the replace part of a search and replace from ex (vim) syntax into
// javascript form. Similar to translateRegex, but additionally fixes back references
// (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
function translateRegexReplace(str) {
var escapeNextChar = false;
var out = [];
for (var i = -1; i < str.length; i++) {
var c = str.charAt(i) || '';
var n = str.charAt(i+1) || '';
if (escapeNextChar) {
// At any point in the loop, escapeNextChar is true if the previous
// character was a '\' and was not escaped.
out.push(c);
escapeNextChar = false;
} else {
if (c === '\\') {
escapeNextChar = true;
if ((isNumber(n) || n === '$')) {
out.push('$');
} else if (n !== '/' && n !== '\\') {
out.push('\\');
}
} else {
if (c === '$') {
out.push('$');
}
out.push(c);
if (n === '/') {
out.push('\\');
}
}
}
}
return out.join('');
}
// Unescape \ and / in the replace part, for PCRE mode.
function unescapeRegexReplace(str) {
var stream = new CodeMirror.StringStream(str);
var output = [];
while (!stream.eol()) {
// Search for \.
while (stream.peek() && stream.peek() != '\\') {
output.push(stream.next());
}
if (stream.match('\\/', true)) {
// \/ => /
output.push('/');
} else if (stream.match('\\\\', true)) {
// \\ => \
output.push('\\');
} else {
// Don't change anything
output.push(stream.next());
}
}
return output.join('');
}
/**
* Extract the regular expression from the query and return a Regexp object.
* Returns null if the query is blank.
* If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
* If smartCase is passed in, and the query contains upper case letters,
* then ignoreCase is overridden, and the 'i' flag will not be set.
* If the query contains the /i in the flag part of the regular expression,
* then both ignoreCase and smartCase are ignored, and 'i' will be passed
* through to the Regex object.
*/
function parseQuery(query, ignoreCase, smartCase) {
// Check if the query is already a regex.
if (query instanceof RegExp) { return query; }
// First try to extract regex + flags from the input. If no flags found,
// extract just the regex. IE does not accept flags directly defined in
// the regex string in the form /regex/flags
var slashes = findUnescapedSlashes(query);
var regexPart;
var forceIgnoreCase;
if (!slashes.length) {
// Query looks like 'regexp'
regexPart = query;
} else {
// Query looks like 'regexp/...'
regexPart = query.substring(0, slashes[0]);
var flagsPart = query.substring(slashes[0]);
forceIgnoreCase = (flagsPart.indexOf('i') != -1);
}
if (!regexPart) {
return null;
}
if (!getOption('pcre')) {
regexPart = translateRegex(regexPart);
}
if (smartCase) {
ignoreCase = (/^[^A-Z]*$/).test(regexPart);
}
var regexp = new RegExp(regexPart,
(ignoreCase || forceIgnoreCase) ? 'i' : undefined);
return regexp;
}
function showConfirm(cm, text) {
if (cm.openNotification) {
cm.openNotification('<span style="color: red">' + text + '</span>',
{bottom: true, duration: 5000});
} else {
alert(text);
}
}
function makePrompt(prefix, desc) {
var raw = '';
if (prefix) {
raw += '<span style="font-family: monospace">' + prefix + '</span>';
}
raw += '<input type="text"/> ' +
'<span style="color: #888">';
if (desc) {
raw += '<span style="color: #888">';
raw += desc;
raw += '</span>';
}
return raw;
}
var searchPromptDesc = '(Javascript regexp)';
function showPrompt(cm, options) {
var shortText = (options.prefix || '') + ' ' + (options.desc || '');
var prompt = makePrompt(options.prefix, options.desc);
dialog(cm, prompt, shortText, options.onClose, options);
}
function regexEqual(r1, r2) {
if (r1 instanceof RegExp && r2 instanceof RegExp) {
var props = ['global', 'multiline', 'ignoreCase', 'source'];
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (r1[prop] !== r2[prop]) {
return false;
}
}
return true;
}
return false;
}
// Returns true if the query is valid.
function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
if (!rawQuery) {
return;
}
var state = getSearchState(cm);
var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
if (!query) {
return;
}
highlightSearchMatches(cm, query);
if (regexEqual(query, state.getQuery())) {
return query;
}
state.setQuery(query);
return query;
}
function searchOverlay(query) {
if (query.source.charAt(0) == '^') {
var matchSol = true;
}
return {
token: function(stream) {
if (matchSol && !stream.sol()) {
stream.skipToEnd();
return;
}
var match = stream.match(query, false);
if (match) {
if (match[0].length == 0) {
// Matched empty string, skip to next.
stream.next();
return 'searching';
}
if (!stream.sol()) {
// Backtrack 1 to match \b
stream.backUp(1);
if (!query.exec(stream.next() + match[0])) {
stream.next();
return null;
}
}
stream.match(query);
return 'searching';
}
while (!stream.eol()) {
stream.next();
if (stream.match(query, false)) break;
}
},
query: query
};
}
function highlightSearchMatches(cm, query) {
var overlay = getSearchState(cm).getOverlay();
if (!overlay || query != overlay.query) {
if (overlay) {
cm.removeOverlay(overlay);
}
overlay = searchOverlay(query);
cm.addOverlay(overlay);
getSearchState(cm).setOverlay(overlay);
}
}
function findNext(cm, prev, query, repeat) {
if (repeat === undefined) { repeat = 1; }
return cm.operation(function() {
var pos = cm.getCursor();
var cursor = cm.getSearchCursor(query, pos);
for (var i = 0; i < repeat; i++) {
var found = cursor.find(prev);
if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
if (!found) {
// SearchCursor may have returned null because it hit EOF, wrap
// around and try again.
cursor = cm.getSearchCursor(query,
(prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );
if (!cursor.find(prev)) {
return;
}
}
}
return cursor.from();
});
}
function clearSearchHighlight(cm) {
cm.removeOverlay(getSearchState(cm).getOverlay());
getSearchState(cm).setOverlay(null);
}
/**
* Check if pos is in the specified range, INCLUSIVE.
* Range can be specified with 1 or 2 arguments.
* If the first range argument is an array, treat it as an array of line
* numbers. Match pos against any of the lines.
* If the first range argument is a number,
* if there is only 1 range argument, check if pos has the same line
* number
* if there are 2 range arguments, then check if pos is in between the two
* range arguments.
*/
function isInRange(pos, start, end) {
if (typeof pos != 'number') {
// Assume it is a cursor position. Get the line number.
pos = pos.line;
}
if (start instanceof Array) {
return inArray(pos, start);
} else {
if (end) {
return (pos >= start && pos <= end);
} else {
return pos == start;
}
}
}
function getUserVisibleLines(cm) {
var scrollInfo = cm.getScrollInfo();
var occludeToleranceTop = 6;
var occludeToleranceBottom = 10;
var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
var to = cm.coordsChar({left:0, top: bottomY}, 'local');
return {top: from.line, bottom: to.line};
}
// Ex command handling
// Care must be taken when adding to the default Ex command map. For any
// pair of commands that have a shared prefix, at least one of their
// shortNames must not match the prefix of the other command.
var defaultExCommandMap = [
{ name: 'map' },
{ name: 'nmap', shortName: 'nm' },
{ name: 'vmap', shortName: 'vm' },
{ name: 'unmap' },
{ name: 'write', shortName: 'w' },
{ name: 'undo', shortName: 'u' },
{ name: 'redo', shortName: 'red' },
{ name: 'set', shortName: 'set' },
{ name: 'sort', shortName: 'sor' },
{ name: 'substitute', shortName: 's' },
{ name: 'nohlsearch', shortName: 'noh' },
{ name: 'delmarks', shortName: 'delm' },
{ name: 'registers', shortName: 'reg', excludeFromCommandHistory: true }
];
Vim.ExCommandDispatcher = function() {
this.buildCommandMap_();
};
Vim.ExCommandDispatcher.prototype = {
processCommand: function(cm, input) {
var vim = cm.state.vim;
var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
var previousCommand = commandHistoryRegister.toString();
if (vim.visualMode) {
exitVisualMode(cm);
}
var inputStream = new CodeMirror.StringStream(input);
// update ": with the latest command whether valid or invalid
commandHistoryRegister.setText(input);
var params = {};
params.input = input;
try {
this.parseInput_(cm, inputStream, params);
} catch(e) {
showConfirm(cm, e);
throw e;
}
var commandName;
if (!params.commandName) {
// If only a line range is defined, move to the line.
if (params.line !== undefined) {
commandName = 'move';
}
} else {
var command = this.matchCommand_(params.commandName);
if (command) {
commandName = command.name;
if (command.excludeFromCommandHistory) {
commandHistoryRegister.setText(previousCommand);
}
this.parseCommandArgs_(inputStream, params, command);
if (command.type == 'exToKey') {
// Handle Ex to Key mapping.
for (var i = 0; i < command.toKeys.length; i++) {
CodeMirror.Vim.handleKey(cm, command.toKeys[i]);
}
return;
} else if (command.type == 'exToEx') {
// Handle Ex to Ex mapping.
this.processCommand(cm, command.toInput);
return;
}
}
}
if (!commandName) {
showConfirm(cm, 'Not an editor command ":' + input + '"');
return;
}
try {
exCommands[commandName](cm, params);
} catch(e) {
showConfirm(cm, e);
throw e;
}
},
parseInput_: function(cm, inputStream, result) {
inputStream.eatWhile(':');
// Parse range.
if (inputStream.eat('%')) {
result.line = cm.firstLine();
result.lineEnd = cm.lastLine();
} else {
result.line = this.parseLineSpec_(cm, inputStream);
if (result.line !== undefined && inputStream.eat(',')) {
result.lineEnd = this.parseLineSpec_(cm, inputStream);
}
}
// Parse command name.
var commandMatch = inputStream.match(/^(\w+)/);
if (commandMatch) {
result.commandName = commandMatch[1];
} else {
result.commandName = inputStream.match(/.*/)[0];
}
return result;
},
parseLineSpec_: function(cm, inputStream) {
var numberMatch = inputStream.match(/^(\d+)/);
if (numberMatch) {
return parseInt(numberMatch[1], 10) - 1;
}
switch (inputStream.next()) {
case '.':
return cm.getCursor().line;
case '$':
return cm.lastLine();
case '\'':
var mark = cm.state.vim.marks[inputStream.next()];
if (mark && mark.find()) {
return mark.find().line;
}
throw new Error('Mark not set');
default:
inputStream.backUp(1);
return undefined;
}
},
parseCommandArgs_: function(inputStream, params, command) {
if (inputStream.eol()) {
return;
}
params.argString = inputStream.match(/.*/)[0];
// Parse command-line arguments
var delim = command.argDelimiter || /\s+/;
var args = trim(params.argString).split(delim);
if (args.length && args[0]) {
params.args = args;
}
},
matchCommand_: function(commandName) {
// Return the command in the command map that matches the shortest
// prefix of the passed in command name. The match is guaranteed to be
// unambiguous if the defaultExCommandMap's shortNames are set up
// correctly. (see @code{defaultExCommandMap}).
for (var i = commandName.length; i > 0; i--) {
var prefix = commandName.substring(0, i);
if (this.commandMap_[prefix]) {
var command = this.commandMap_[prefix];
if (command.name.indexOf(commandName) === 0) {
return command;
}
}
}
return null;
},
buildCommandMap_: function() {
this.commandMap_ = {};
for (var i = 0; i < defaultExCommandMap.length; i++) {
var command = defaultExCommandMap[i];
var key = command.shortName || command.name;
this.commandMap_[key] = command;
}
},
map: function(lhs, rhs, ctx) {
if (lhs != ':' && lhs.charAt(0) == ':') {
if (ctx) { throw Error('Mode not supported for ex mappings'); }
var commandName = lhs.substring(1);
if (rhs != ':' && rhs.charAt(0) == ':') {
// Ex to Ex mapping
this.commandMap_[commandName] = {
name: commandName,
type: 'exToEx',
toInput: rhs.substring(1),
user: true
};
} else {
// Ex to key mapping
this.commandMap_[commandName] = {
name: commandName,
type: 'exToKey',
toKeys: parseKeyString(rhs),
user: true
};
}
} else {
if (rhs != ':' && rhs.charAt(0) == ':') {
// Key to Ex mapping.
var mapping = {
keys: parseKeyString(lhs),
type: 'keyToEx',
exArgs: { input: rhs.substring(1) },
user: true};
if (ctx) { mapping.context = ctx; }
defaultKeymap.unshift(mapping);
} else {
// Key to key mapping
var mapping = {
keys: parseKeyString(lhs),
type: 'keyToKey',
toKeys: parseKeyString(rhs),
user: true
};
if (ctx) { mapping.context = ctx; }
defaultKeymap.unshift(mapping);
}
}
},
unmap: function(lhs, ctx) {
var arrayEquals = function(a, b) {
if (a === b) return true;
if (a == null || b == null) return true;
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
};
if (lhs != ':' && lhs.charAt(0) == ':') {
// Ex to Ex or Ex to key mapping
if (ctx) { throw Error('Mode not supported for ex mappings'); }
var commandName = lhs.substring(1);
if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
delete this.commandMap_[commandName];
return;
}
} else {
// Key to Ex or key to key mapping
var keys = parseKeyString(lhs);
for (var i = 0; i < defaultKeymap.length; i++) {
if (arrayEquals(keys, defaultKeymap[i].keys)
&& defaultKeymap[i].context === ctx
&& defaultKeymap[i].user) {
defaultKeymap.splice(i, 1);
return;
}
}
}
throw Error('No such mapping.');
}
};
// Converts a key string sequence of the form a<C-w>bd<Left> into Vim's
// keymap representation.
function parseKeyString(str) {
var key, match;
var keys = [];
while (str) {
match = (/<\w+-.+?>|<\w+>|./).exec(str);
if (match === null)break;
key = match[0];
str = str.substring(match.index + key.length);
keys.push(key);
}
return keys;
}
var exCommands = {
map: function(cm, params, ctx) {
var mapArgs = params.args;
if (!mapArgs || mapArgs.length < 2) {
if (cm) {
showConfirm(cm, 'Invalid mapping: ' + params.input);
}
return;
}
exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
},
nmap: function(cm, params) { this.map(cm, params, 'normal'); },
vmap: function(cm, params) { this.map(cm, params, 'visual'); },
unmap: function(cm, params, ctx) {
var mapArgs = params.args;
if (!mapArgs || mapArgs.length < 1) {
if (cm) {
showConfirm(cm, 'No such mapping: ' + params.input);
}
return;
}
exCommandDispatcher.unmap(mapArgs[0], ctx);
},
move: function(cm, params) {
commandDispatcher.processCommand(cm, cm.state.vim, {
type: 'motion',
motion: 'moveToLineOrEdgeOfDocument',
motionArgs: { forward: false, explicitRepeat: true,
linewise: true },
repeatOverride: params.line+1});
},
set: function(cm, params) {
var setArgs = params.args;
if (!setArgs || setArgs.length < 1) {
if (cm) {
showConfirm(cm, 'Invalid mapping: ' + params.input);
}
return;
}
var expr = setArgs[0].split('=');
var optionName = expr[0];
var value = expr[1];
var forceGet = false;
if (optionName.charAt(optionName.length - 1) == '?') {
// If post-fixed with ?, then the set is actually a get.
if (value) { throw Error('Trailing characters: ' + params.argString); }
optionName = optionName.substring(0, optionName.length - 1);
forceGet = true;
}
if (value === undefined && optionName.substring(0, 2) == 'no') {
// To set boolean options to false, the option name is prefixed with
// 'no'.
optionName = optionName.substring(2);
value = false;
}
var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
if (optionIsBoolean && value == undefined) {
// Calling set with a boolean option sets it to true.
value = true;
}
if (!optionIsBoolean && !value || forceGet) {
var oldValue = getOption(optionName);
// If no value is provided, then we assume this is a get.
if (oldValue === true || oldValue === false) {
showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
} else {
showConfirm(cm, ' ' + optionName + '=' + oldValue);
}
} else {
setOption(optionName, value);
}
},
registers: function(cm,params) {
var regArgs = params.args;
var registers = vimGlobalState.registerController.registers;
var regInfo = '----------Registers----------<br><br>';
if (!regArgs) {
for (var registerName in registers) {
var text = registers[registerName].toString();
if (text.length) {
regInfo += '"' + registerName + ' ' + text + '<br>';
}
}
} else {
var registerName;
regArgs = regArgs.join('');
for (var i = 0; i < regArgs.length; i++) {
registerName = regArgs.charAt(i);
if (!vimGlobalState.registerController.isValidRegister(registerName)) {
continue;
}
var register = registers[registerName] || new Register();
regInfo += '"' + registerName + ' ' + register.toString() + '<br>';
}
}
showConfirm(cm, regInfo);
},
sort: function(cm, params) {
var reverse, ignoreCase, unique, number;
function parseArgs() {
if (params.argString) {
var args = new CodeMirror.StringStream(params.argString);
if (args.eat('!')) { reverse = true; }
if (args.eol()) { return; }
if (!args.eatSpace()) { return 'Invalid arguments'; }
var opts = args.match(/[a-z]+/);
if (opts) {
opts = opts[0];
ignoreCase = opts.indexOf('i') != -1;
unique = opts.indexOf('u') != -1;
var decimal = opts.indexOf('d') != -1 && 1;
var hex = opts.indexOf('x') != -1 && 1;
var octal = opts.indexOf('o') != -1 && 1;
if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
}
if (args.eatSpace() && args.match(/\/.*\//)) { 'patterns not supported'; }
}
}
var err = parseArgs();
if (err) {
showConfirm(cm, err + ': ' + params.argString);
return;
}
var lineStart = params.line || cm.firstLine();
var lineEnd = params.lineEnd || params.line || cm.lastLine();
if (lineStart == lineEnd) { return; }
var curStart = Pos(lineStart, 0);
var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));
var text = cm.getRange(curStart, curEnd).split('\n');
var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
(number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
(number == 'octal') ? /([0-7]+)/ : null;
var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
var numPart = [], textPart = [];
if (number) {
for (var i = 0; i < text.length; i++) {
if (numberRegex.exec(text[i])) {
numPart.push(text[i]);
} else {
textPart.push(text[i]);
}
}
} else {
textPart = text;
}
function compareFn(a, b) {
if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
var anum = number && numberRegex.exec(a);
var bnum = number && numberRegex.exec(b);
if (!anum) { return a < b ? -1 : 1; }
anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
return anum - bnum;
}
numPart.sort(compareFn);
textPart.sort(compareFn);
text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
if (unique) { // Remove duplicate lines
var textOld = text;
var lastLine;
text = [];
for (var i = 0; i < textOld.length; i++) {
if (textOld[i] != lastLine) {
text.push(textOld[i]);
}
lastLine = textOld[i];
}
}
cm.replaceRange(text.join('\n'), curStart, curEnd);
},
substitute: function(cm, params) {
if (!cm.getSearchCursor) {
throw new Error('Search feature not available. Requires searchcursor.js or ' +
'any other getSearchCursor implementation.');
}
var argString = params.argString;
var slashes = argString ? findUnescapedSlashes(argString) : [];
var replacePart = '';
if (slashes.length) {
if (slashes[0] !== 0) {
showConfirm(cm, 'Substitutions should be of the form ' +
':s/pattern/replace/');
return;
}
var regexPart = argString.substring(slashes[0] + 1, slashes[1]);
var flagsPart;
var count;
var confirm = false; // Whether to confirm each replace.
if (slashes[1]) {
replacePart = argString.substring(slashes[1] + 1, slashes[2]);
if (getOption('pcre')) {
replacePart = unescapeRegexReplace(replacePart);
} else {
replacePart = translateRegexReplace(replacePart);
}
vimGlobalState.lastSubstituteReplacePart = replacePart;
}
if (slashes[2]) {
// After the 3rd slash, we can have flags followed by a space followed
// by count.
var trailing = argString.substring(slashes[2] + 1).split(' ');
flagsPart = trailing[0];
count = parseInt(trailing[1]);
}
if (flagsPart) {
if (flagsPart.indexOf('c') != -1) {
confirm = true;
flagsPart.replace('c', '');
}
regexPart = regexPart + '/' + flagsPart;
}
}
if (regexPart) {
// If regex part is empty, then use the previous query. Otherwise use
// the regex part as the new query.
try {
updateSearchQuery(cm, regexPart, true /** ignoreCase */,
true /** smartCase */);
} catch (e) {
showConfirm(cm, 'Invalid regex: ' + regexPart);
return;
}
}
replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
if (replacePart === undefined) {
showConfirm(cm, 'No previous substitute regular expression');
return;
}
var state = getSearchState(cm);
var query = state.getQuery();
var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
var lineEnd = params.lineEnd || lineStart;
if (count) {
lineStart = lineEnd;
lineEnd = lineStart + count - 1;
}
var startPos = clipCursorToContent(cm, Pos(lineStart, 0));
var cursor = cm.getSearchCursor(query, startPos);
doReplace(cm, confirm, lineStart, lineEnd, cursor, query, replacePart);
},
redo: CodeMirror.commands.redo,
undo: CodeMirror.commands.undo,
write: function(cm) {
if (CodeMirror.commands.save) {
// If a save command is defined, call it.
CodeMirror.commands.save(cm);
} else {
// Saves to text area if no save command is defined.
cm.save();
}
},
nohlsearch: function(cm) {
clearSearchHighlight(cm);
},
delmarks: function(cm, params) {
if (!params.argString || !trim(params.argString)) {
showConfirm(cm, 'Argument required');
return;
}
var state = cm.state.vim;
var stream = new CodeMirror.StringStream(trim(params.argString));
while (!stream.eol()) {
stream.eatSpace();
// Record the streams position at the beginning of the loop for use
// in error messages.
var count = stream.pos;
if (!stream.match(/[a-zA-Z]/, false)) {
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
return;
}
var sym = stream.next();
// Check if this symbol is part of a range
if (stream.match('-', true)) {
// This symbol is part of a range.
// The range must terminate at an alphabetic character.
if (!stream.match(/[a-zA-Z]/, false)) {
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
return;
}
var startMark = sym;
var finishMark = stream.next();
// The range must terminate at an alphabetic character which
// shares the same case as the start of the range.
if (isLowerCase(startMark) && isLowerCase(finishMark) ||
isUpperCase(startMark) && isUpperCase(finishMark)) {
var start = startMark.charCodeAt(0);
var finish = finishMark.charCodeAt(0);
if (start >= finish) {
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
return;
}
// Because marks are always ASCII values, and we have
// determined that they are the same case, we can use
// their char codes to iterate through the defined range.
for (var j = 0; j <= finish - start; j++) {
var mark = String.fromCharCode(start + j);
delete state.marks[mark];
}
} else {
showConfirm(cm, 'Invalid argument: ' + startMark + '-');
return;
}
} else {
// This symbol is a valid mark, and is not part of a range.
delete state.marks[sym];
}
}
}
};
var exCommandDispatcher = new Vim.ExCommandDispatcher();
/**
* @param {CodeMirror} cm CodeMirror instance we are in.
* @param {boolean} confirm Whether to confirm each replace.
* @param {Cursor} lineStart Line to start replacing from.
* @param {Cursor} lineEnd Line to stop replacing at.
* @param {RegExp} query Query for performing matches with.
* @param {string} replaceWith Text to replace matches with. May contain $1,
* $2, etc for replacing captured groups using Javascript replace.
*/
function doReplace(cm, confirm, lineStart, lineEnd, searchCursor, query,
replaceWith) {
// Set up all the functions.
cm.state.vim.exMode = true;
var done = false;
var lastPos = searchCursor.from();
function replaceAll() {
cm.operation(function() {
while (!done) {
replace();
next();
}
stop();
});
}
function replace() {
var text = cm.getRange(searchCursor.from(), searchCursor.to());
var newText = text.replace(query, replaceWith);
searchCursor.replace(newText);
}
function next() {
var found = searchCursor.findNext();
if (!found) {
done = true;
} else if (isInRange(searchCursor.from(), lineStart, lineEnd)) {
cm.scrollIntoView(searchCursor.from(), 30);
cm.setSelection(searchCursor.from(), searchCursor.to());
lastPos = searchCursor.from();
done = false;
} else {
done = true;
}
}
function stop(close) {
if (close) { close(); }
cm.focus();
if (lastPos) {
cm.setCursor(lastPos);
var vim = cm.state.vim;
vim.exMode = false;
vim.lastHPos = vim.lastHSPos = lastPos.ch;
}
}
function onPromptKeyDown(e, _value, close) {
// Swallow all keys.
CodeMirror.e_stop(e);
var keyName = CodeMirror.keyName(e);
switch (keyName) {
case 'Y':
replace(); next(); break;
case 'N':
next(); break;
case 'A':
cm.operation(replaceAll); break;
case 'L':
replace();
// fall through and exit.
case 'Q':
case 'Esc':
case 'Ctrl-C':
case 'Ctrl-[':
stop(close);
break;
}
if (done) { stop(close); }
}
// Actually do replace.
next();
if (done) {
showConfirm(cm, 'No matches for ' + query.source);
return;
}
if (!confirm) {
replaceAll();
return;
}
showPrompt(cm, {
prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
onKeyDown: onPromptKeyDown
});
}
// Register Vim with CodeMirror
function buildVimKeyMap() {
/**
* Handle the raw key event from CodeMirror. Translate the
* Shift + key modifier to the resulting letter, while preserving other
* modifers.
*/
function cmKeyToVimKey(key, modifier) {
var vimKey = key;
if (isUpperCase(vimKey) && modifier == 'Ctrl') {
vimKey = vimKey.toLowerCase();
}
if (modifier) {
// Vim will parse modifier+key combination as a single key.
vimKey = modifier.charAt(0) + '-' + vimKey;
}
var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
vimKey = specialKey ? specialKey : vimKey;
vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
return vimKey;
}
// Closure to bind CodeMirror, key, modifier.
function keyMapper(vimKey) {
return function(cm) {
CodeMirror.Vim.handleKey(cm, vimKey);
};
}
var cmToVimKeymap = {
'nofallthrough': true,
'style': 'fat-cursor'
};
function bindKeys(keys, modifier) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!modifier && key.length == 1) {
// Wrap all keys without modifiers with '' to identify them by their
// key characters instead of key identifiers.
key = "'" + key + "'";
}
var vimKey = cmKeyToVimKey(keys[i], modifier);
var cmKey = modifier ? modifier + '-' + key : key;
cmToVimKeymap[cmKey] = keyMapper(vimKey);
}
}
bindKeys(upperCaseAlphabet);
bindKeys(lowerCaseAlphabet);
bindKeys(upperCaseAlphabet, 'Ctrl');
bindKeys(specialSymbols);
bindKeys(specialSymbols, 'Ctrl');
bindKeys(numbers);
bindKeys(numbers, 'Ctrl');
bindKeys(specialKeys);
bindKeys(specialKeys, 'Ctrl');
return cmToVimKeymap;
}
CodeMirror.keyMap.vim = buildVimKeyMap();
function exitInsertMode(cm) {
var vim = cm.state.vim;
var macroModeState = vimGlobalState.macroModeState;
var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
var isPlaying = macroModeState.isPlaying;
if (!isPlaying) {
cm.off('change', onChange);
CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
}
if (!isPlaying && vim.insertModeRepeat > 1) {
// Perform insert mode repeat for commands like 3,a and 3,o.
repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
true /** repeatForInsert */);
vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
}
delete vim.insertModeRepeat;
vim.insertMode = false;
cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
cm.setOption('keyMap', 'vim');
cm.setOption('disableInput', true);
cm.toggleOverwrite(false); // exit replace mode if we were in it.
// update the ". register before exiting insert mode
insertModeChangeRegister.setText(macroModeState.lastInsertModeChanges.changes.join(''));
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
if (macroModeState.isRecording) {
logInsertModeChange(macroModeState);
}
}
CodeMirror.keyMap['vim-insert'] = {
// TODO: override navigation keys so that Esc will cancel automatic
// indentation from o, O, i_<CR>
'Esc': exitInsertMode,
'Ctrl-[': exitInsertMode,
'Ctrl-C': exitInsertMode,
'Ctrl-N': 'autocomplete',
'Ctrl-P': 'autocomplete',
'Enter': function(cm) {
var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
CodeMirror.commands.newlineAndIndent;
fn(cm);
},
fallthrough: ['default']
};
CodeMirror.keyMap['vim-replace'] = {
'Backspace': 'goCharLeft',
fallthrough: ['vim-insert']
};
function executeMacroRegister(cm, vim, macroModeState, registerName) {
var register = vimGlobalState.registerController.getRegister(registerName);
var keyBuffer = register.keyBuffer;
var imc = 0;
macroModeState.isPlaying = true;
macroModeState.replaySearchQueries = register.searchQueries.slice(0);
for (var i = 0; i < keyBuffer.length; i++) {
var text = keyBuffer[i];
var match, key;
while (text) {
// Pull off one command key, which is either a single character
// or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
match = (/<\w+-.+?>|<\w+>|./).exec(text);
key = match[0];
text = text.substring(match.index + key.length);
CodeMirror.Vim.handleKey(cm, key);
if (vim.insertMode) {
repeatInsertModeChanges(
cm, register.insertModeChanges[imc++].changes, 1);
exitInsertMode(cm);
}
}
};
macroModeState.isPlaying = false;
}
function logKey(macroModeState, key) {
if (macroModeState.isPlaying) { return; }
var registerName = macroModeState.latestRegister;
var register = vimGlobalState.registerController.getRegister(registerName);
if (register) {
register.pushText(key);
}
}
function logInsertModeChange(macroModeState) {
if (macroModeState.isPlaying) { return; }
var registerName = macroModeState.latestRegister;
var register = vimGlobalState.registerController.getRegister(registerName);
if (register) {
register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
}
}
function logSearchQuery(macroModeState, query) {
if (macroModeState.isPlaying) { return; }
var registerName = macroModeState.latestRegister;
var register = vimGlobalState.registerController.getRegister(registerName);
if (register) {
register.pushSearchQuery(query);
}
}
/**
* Listens for changes made in insert mode.
* Should only be active in insert mode.
*/
function onChange(_cm, changeObj) {
var macroModeState = vimGlobalState.macroModeState;
var lastChange = macroModeState.lastInsertModeChanges;
if (!macroModeState.isPlaying) {
while(changeObj) {
lastChange.expectCursorActivityForChange = true;
if (changeObj.origin == '+input' || changeObj.origin == 'paste'
|| changeObj.origin === undefined /* only in testing */) {
var text = changeObj.text.join('\n');
lastChange.changes.push(text);
}
// Change objects may be chained with next.
changeObj = changeObj.next;
}
}
}
/**
* Listens for any kind of cursor activity on CodeMirror.
*/
function onCursorActivity(cm) {
var vim = cm.state.vim;
if (vim.insertMode) {
// Tracking cursor activity in insert mode (for macro support).
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isPlaying) { return; }
var lastChange = macroModeState.lastInsertModeChanges;
if (lastChange.expectCursorActivityForChange) {
lastChange.expectCursorActivityForChange = false;
} else {
// Cursor moved outside the context of an edit. Reset the change.
lastChange.changes = [];
}
} else if (cm.doc.history.lastSelOrigin == '*mouse') {
// Reset lastHPos if mouse click was done in normal mode.
vim.lastHPos = cm.doc.getCursor().ch;
}
}
/** Wrapper for special keys pressed in insert mode */
function InsertModeKey(keyName) {
this.keyName = keyName;
}
/**
* Handles raw key down events from the text area.
* - Should only be active in insert mode.
* - For recording deletes in insert mode.
*/
function onKeyEventTargetKeyDown(e) {
var macroModeState = vimGlobalState.macroModeState;
var lastChange = macroModeState.lastInsertModeChanges;
var keyName = CodeMirror.keyName(e);
function onKeyFound() {
lastChange.changes.push(new InsertModeKey(keyName));
return true;
}
if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
}
}
/**
* Repeats the last edit, which includes exactly 1 command and at most 1
* insert. Operator and motion commands are read from lastEditInputState,
* while action commands are read from lastEditActionCommand.
*
* If repeatForInsert is true, then the function was called by
* exitInsertMode to repeat the insert mode changes the user just made. The
* corresponding enterInsertMode call was made with a count.
*/
function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
var macroModeState = vimGlobalState.macroModeState;
macroModeState.isPlaying = true;
var isAction = !!vim.lastEditActionCommand;
var cachedInputState = vim.inputState;
function repeatCommand() {
if (isAction) {
commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
} else {
commandDispatcher.evalInput(cm, vim);
}
}
function repeatInsert(repeat) {
if (macroModeState.lastInsertModeChanges.changes.length > 0) {
// For some reason, repeat cw in desktop VIM does not repeat
// insert mode changes. Will conform to that behavior.
repeat = !vim.lastEditActionCommand ? 1 : repeat;
var changeObject = macroModeState.lastInsertModeChanges;
// This isn't strictly necessary, but since lastInsertModeChanges is
// supposed to be immutable during replay, this helps catch bugs.
macroModeState.lastInsertModeChanges = {};
repeatInsertModeChanges(cm, changeObject.changes, repeat);
macroModeState.lastInsertModeChanges = changeObject;
}
}
vim.inputState = vim.lastEditInputState;
if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
// o and O repeat have to be interlaced with insert repeats so that the
// insertions appear on separate lines instead of the last line.
for (var i = 0; i < repeat; i++) {
repeatCommand();
repeatInsert(1);
}
} else {
if (!repeatForInsert) {
// Hack to get the cursor to end up at the right place. If I is
// repeated in insert mode repeat, cursor will be 1 insert
// change set left of where it should be.
repeatCommand();
}
repeatInsert(repeat);
}
vim.inputState = cachedInputState;
if (vim.insertMode && !repeatForInsert) {
// Don't exit insert mode twice. If repeatForInsert is set, then we
// were called by an exitInsertMode call lower on the stack.
exitInsertMode(cm);
}
macroModeState.isPlaying = false;
};
function repeatInsertModeChanges(cm, changes, repeat) {
function keyHandler(binding) {
if (typeof binding == 'string') {
CodeMirror.commands[binding](cm);
} else {
binding(cm);
}
return true;
}
for (var i = 0; i < repeat; i++) {
for (var j = 0; j < changes.length; j++) {
var change = changes[j];
if (change instanceof InsertModeKey) {
CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler);
} else {
var cur = cm.getCursor();
cm.replaceRange(change, cur, cur);
}
}
}
}
resetVimGlobalState();
return vimApi;
};
// Initialize Vim and make it available as an API.
CodeMirror.Vim = Vim();
});
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
}
.CodeMirror-scroll {
/* Set scrolling behaviour here */
overflow: auto;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
/* CURSOR */
.CodeMirror div.CodeMirror-cursor {
border-left: 1px solid black;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor {
width: auto;
border: 0;
background: #7e7;
}
/* Can style cursor different in overwrite (non-insert) mode */
div.CodeMirror-overwrite div.CodeMirror-cursor {}
.cm-tab { display: inline-block; }
.CodeMirror-ruler {
border-left: 1px solid #ccc;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3 {color: #085;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}
.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-s-default .cm-error {color: #f00;}
.cm-invalidchar {color: #f00;}
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
.CodeMirror-activeline-background {background: #e8f2ff;}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
line-height: 1;
position: relative;
overflow: hidden;
background: white;
color: black;
}
.CodeMirror-scroll {
/* 30px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -30px; margin-right: -30px;
padding-bottom: 30px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-sizer {
position: relative;
border-right: 30px solid transparent;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actuall scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
}
.CodeMirror-vscrollbar {
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0; left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0; bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0; bottom: 0;
}
.CodeMirror-gutters {
position: absolute; left: 0; top: 0;
padding-bottom: 30px;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
-moz-box-sizing: content-box;
box-sizing: content-box;
padding-bottom: 30px;
margin-bottom: -32px;
display: inline-block;
/* Hack to make IE7 behave */
*zoom:1;
*display:inline;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-lines {
cursor: text;
}
.CodeMirror pre {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
}
.CodeMirror-wrap pre {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
overflow: auto;
}
.CodeMirror-widget {}
.CodeMirror-wrap .CodeMirror-scroll {
overflow-x: hidden;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-measure pre { position: static; }
.CodeMirror div.CodeMirror-cursor {
position: absolute;
border-right: none;
width: 0;
}
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 1;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-crosshair { cursor: crosshair; }
.cm-searching {
background: #ffa;
background: rgba(255, 255, 0, .4);
}
/* IE7 hack to prevent it from returning funny offsetTops on the spans */
.CodeMirror span { *vertical-align: text-bottom; }
/* Used to force a border model for a node */
.cm-force-border { padding-right: .1px; }
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
// This is CodeMirror (http://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
module.exports = mod();
else if (typeof define == "function" && define.amd) // AMD
return define([], mod);
else // Plain browser env
this.CodeMirror = mod();
})(function() {
"use strict";
// BROWSER SNIFFING
// Kludges for bugs and behavior differences that can't be feature
// detected are enabled based on userAgent etc sniffing.
var gecko = /gecko\/\d/i.test(navigator.userAgent);
// ie_uptoN means Internet Explorer version N or lower
var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
var ie_upto7 = ie_upto10 && (document.documentMode == null || document.documentMode < 8);
var ie_upto8 = ie_upto10 && (document.documentMode == null || document.documentMode < 9);
var ie_upto9 = ie_upto10 && (document.documentMode == null || document.documentMode < 10);
var ie_11up = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent);
var ie = ie_upto10 || ie_11up;
var webkit = /WebKit\//.test(navigator.userAgent);
var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
var chrome = /Chrome\//.test(navigator.userAgent);
var presto = /Opera\//.test(navigator.userAgent);
var safari = /Apple Computer/.test(navigator.vendor);
var khtml = /KHTML\//.test(navigator.userAgent);
var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
var phantom = /PhantomJS/.test(navigator.userAgent);
var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
// This is woefully incomplete. Suggestions for alternative methods welcome.
var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
var mac = ios || /Mac/.test(navigator.platform);
var windows = /win/i.test(navigator.platform);
var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
if (presto_version) presto_version = Number(presto_version[1]);
if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
// Some browsers use the wrong event properties to signal cmd/ctrl on OS X
var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
var captureRightClick = gecko || (ie && !ie_upto8);
// Optimize some code when these features are not used.
var sawReadOnlySpans = false, sawCollapsedSpans = false;
// EDITOR CONSTRUCTOR
// A CodeMirror instance represents an editor. This is the object
// that user code is usually dealing with.
function CodeMirror(place, options) {
if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
this.options = options = options || {};
// Determine effective options based on given values and defaults.
copyObj(defaults, options, false);
setGuttersForLineNumbers(options);
var doc = options.value;
if (typeof doc == "string") doc = new Doc(doc, options.mode);
this.doc = doc;
var display = this.display = new Display(place, doc);
display.wrapper.CodeMirror = this;
updateGutters(this);
themeChanged(this);
if (options.lineWrapping)
this.display.wrapper.className += " CodeMirror-wrap";
if (options.autofocus && !mobile) focusInput(this);
this.state = {
keyMaps: [], // stores maps added by addKeyMap
overlays: [], // highlighting overlays, as added by addOverlay
modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
overwrite: false, focused: false,
suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput
draggingText: false,
highlight: new Delayed() // stores highlight worker timeout
};
// Override magic textarea content restore that IE sometimes does
// on our hidden textarea on reload
if (ie_upto10) setTimeout(bind(resetInput, this, true), 20);
registerEventHandlers(this);
ensureGlobalHandlers();
var cm = this;
runInOp(this, function() {
cm.curOp.forceUpdate = true;
attachDoc(cm, doc);
if ((options.autofocus && !mobile) || activeElt() == display.input)
setTimeout(bind(onFocus, cm), 20);
else
onBlur(cm);
for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
optionHandlers[opt](cm, options[opt], Init);
for (var i = 0; i < initHooks.length; ++i) initHooks[i](cm);
});
}
// DISPLAY CONSTRUCTOR
// The display handles the DOM integration, both for input reading
// and content drawing. It holds references to DOM nodes and
// display-related state.
function Display(place, doc) {
var d = this;
// The semihidden textarea that is focused when the editor is
// focused, and receives input.
var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
// The textarea is kept positioned near the cursor to prevent the
// fact that it'll be scrolled into view on input from scrolling
// our fake cursor out of view. On webkit, when wrap=off, paste is
// very slow. So make the area wide instead.
if (webkit) input.style.width = "1000px";
else input.setAttribute("wrap", "off");
// If border: 0; -- iOS fails to open keyboard (issue #1287)
if (ios) input.style.border = "1px solid black";
input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
// Wraps and hides input textarea
d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
// The fake scrollbar elements.
d.scrollbarH = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
d.scrollbarV = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
// Covers bottom-right square when both scrollbars are present.
d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
// Covers bottom of gutter when coverGutterNextToScrollbar is on
// and h scrollbar is present.
d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
// Will contain the actual code, positioned to cover the viewport.
d.lineDiv = elt("div", null, "CodeMirror-code");
// Elements are added to these to represent selection and cursors.
d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
d.cursorDiv = elt("div", null, "CodeMirror-cursors");
// A visibility: hidden element used to find the size of things.
d.measure = elt("div", null, "CodeMirror-measure");
// When lines outside of the viewport are measured, they are drawn in this.
d.lineMeasure = elt("div", null, "CodeMirror-measure");
// Wraps everything that needs to exist inside the vertically-padded coordinate system
d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
null, "position: relative; outline: none");
// Moved around its parent to cover visible view.
d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
// Set to the height of the document, allowing scrolling.
d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
// Behavior of elts with overflow: auto and padding is
// inconsistent across browsers. This is used to ensure the
// scrollable area is big enough.
d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
// Will contain the gutters, if any.
d.gutters = elt("div", null, "CodeMirror-gutters");
d.lineGutter = null;
// Actual scrollable element.
d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
d.scroller.setAttribute("tabIndex", "-1");
// The element in which the editor lives.
d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
// Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
if (ie_upto7) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
// Needed to hide big blue blinking cursor on Mobile Safari
if (ios) input.style.width = "0px";
if (!webkit) d.scroller.draggable = true;
// Needed to handle Tab key in KHTML
if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
// Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
if (ie_upto7) d.scrollbarH.style.minHeight = d.scrollbarV.style.minWidth = "18px";
if (place.appendChild) place.appendChild(d.wrapper);
else place(d.wrapper);
// Current rendered range (may be bigger than the view window).
d.viewFrom = d.viewTo = doc.first;
// Information about the rendered lines.
d.view = [];
// Holds info about a single rendered line when it was rendered
// for measurement, while not in view.
d.externalMeasured = null;
// Empty space (in pixels) above the view
d.viewOffset = 0;
d.lastSizeC = 0;
d.updateLineNumbers = null;
// Used to only resize the line number gutter when necessary (when
// the amount of lines crosses a boundary that makes its width change)
d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
// See readInput and resetInput
d.prevInput = "";
// Set to true when a non-horizontal-scrolling line widget is
// added. As an optimization, line widget aligning is skipped when
// this is false.
d.alignWidgets = false;
// Flag that indicates whether we expect input to appear real soon
// now (after some event like 'keypress' or 'input') and are
// polling intensively.
d.pollingFast = false;
// Self-resetting timeout for the poller
d.poll = new Delayed();
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
// Tracks when resetInput has punted to just putting a short
// string into the textarea instead of the full selection.
d.inaccurateSelection = false;
// Tracks the maximum line length so that the horizontal scrollbar
// can be kept static when scrolling.
d.maxLine = null;
d.maxLineLength = 0;
d.maxLineChanged = false;
// Used for measuring wheel scrolling granularity
d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
// True when shift is held down.
d.shift = false;
// Used to track whether anything happened since the context menu
// was opened.
d.selForContextMenu = null;
}
// STATE UPDATES
// Used to get the editor into a consistent state again when options change.
function loadMode(cm) {
cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
resetModeState(cm);
}
function resetModeState(cm) {
cm.doc.iter(function(line) {
if (line.stateAfter) line.stateAfter = null;
if (line.styles) line.styles = null;
});
cm.doc.frontier = cm.doc.first;
startWorker(cm, 100);
cm.state.modeGen++;
if (cm.curOp) regChange(cm);
}
function wrappingChanged(cm) {
if (cm.options.lineWrapping) {
addClass(cm.display.wrapper, "CodeMirror-wrap");
cm.display.sizer.style.minWidth = "";
} else {
rmClass(cm.display.wrapper, "CodeMirror-wrap");
findMaxLine(cm);
}
estimateLineHeights(cm);
regChange(cm);
clearCaches(cm);
setTimeout(function(){updateScrollbars(cm);}, 100);
}
// Returns a function that estimates the height of a line, to use as
// first approximation until the line becomes visible (and is thus
// properly measurable).
function estimateHeight(cm) {
var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
return function(line) {
if (lineIsHidden(cm.doc, line)) return 0;
var widgetsHeight = 0;
if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
}
if (wrapping)
return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
else
return widgetsHeight + th;
};
}
function estimateLineHeights(cm) {
var doc = cm.doc, est = estimateHeight(cm);
doc.iter(function(line) {
var estHeight = est(line);
if (estHeight != line.height) updateLineHeight(line, estHeight);
});
}
function keyMapChanged(cm) {
var map = keyMap[cm.options.keyMap], style = map.style;
cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
(style ? " cm-keymap-" + style : "");
}
function themeChanged(cm) {
cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
clearCaches(cm);
}
function guttersChanged(cm) {
updateGutters(cm);
regChange(cm);
setTimeout(function(){alignHorizontally(cm);}, 20);
}
// Rebuild the gutter elements, ensure the margin to the left of the
// code matches their width.
function updateGutters(cm) {
var gutters = cm.display.gutters, specs = cm.options.gutters;
removeChildren(gutters);
for (var i = 0; i < specs.length; ++i) {
var gutterClass = specs[i];
var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
if (gutterClass == "CodeMirror-linenumbers") {
cm.display.lineGutter = gElt;
gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
}
}
gutters.style.display = i ? "" : "none";
updateGutterSpace(cm);
}
function updateGutterSpace(cm) {
var width = cm.display.gutters.offsetWidth;
cm.display.sizer.style.marginLeft = width + "px";
cm.display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0;
}
// Compute the character length of a line, taking into account
// collapsed ranges (see markText) that might hide parts, and join
// other lines onto it.
function lineLength(line) {
if (line.height == 0) return 0;
var len = line.text.length, merged, cur = line;
while (merged = collapsedSpanAtStart(cur)) {
var found = merged.find(0, true);
cur = found.from.line;
len += found.from.ch - found.to.ch;
}
cur = line;
while (merged = collapsedSpanAtEnd(cur)) {
var found = merged.find(0, true);
len -= cur.text.length - found.from.ch;
cur = found.to.line;
len += cur.text.length - found.to.ch;
}
return len;
}
// Find the longest line in the document.
function findMaxLine(cm) {
var d = cm.display, doc = cm.doc;
d.maxLine = getLine(doc, doc.first);
d.maxLineLength = lineLength(d.maxLine);
d.maxLineChanged = true;
doc.iter(function(line) {
var len = lineLength(line);
if (len > d.maxLineLength) {
d.maxLineLength = len;
d.maxLine = line;
}
});
}
// Make sure the gutters options contains the element
// "CodeMirror-linenumbers" when the lineNumbers option is true.
function setGuttersForLineNumbers(options) {
var found = indexOf(options.gutters, "CodeMirror-linenumbers");
if (found == -1 && options.lineNumbers) {
options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
} else if (found > -1 && !options.lineNumbers) {
options.gutters = options.gutters.slice(0);
options.gutters.splice(found, 1);
}
}
// SCROLLBARS
// Prepare DOM reads needed to update the scrollbars. Done in one
// shot to minimize update/measure roundtrips.
function measureForScrollbars(cm) {
var scroll = cm.display.scroller;
return {
clientHeight: scroll.clientHeight,
barHeight: cm.display.scrollbarV.clientHeight,
scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth,
barWidth: cm.display.scrollbarH.clientWidth,
docHeight: Math.round(cm.doc.height + paddingVert(cm.display))
};
}
// Re-synchronize the fake scrollbars with the actual size of the
// content.
function updateScrollbars(cm, measure) {
if (!measure) measure = measureForScrollbars(cm);
var d = cm.display;
var scrollHeight = measure.docHeight + scrollerCutOff;
var needsH = measure.scrollWidth > measure.clientWidth;
var needsV = scrollHeight > measure.clientHeight;
if (needsV) {
d.scrollbarV.style.display = "block";
d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
// A bug in IE8 can cause this value to be negative, so guard it.
d.scrollbarV.firstChild.style.height =
Math.max(0, scrollHeight - measure.clientHeight + (measure.barHeight || d.scrollbarV.clientHeight)) + "px";
} else {
d.scrollbarV.style.display = "";
d.scrollbarV.firstChild.style.height = "0";
}
if (needsH) {
d.scrollbarH.style.display = "block";
d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
d.scrollbarH.firstChild.style.width =
(measure.scrollWidth - measure.clientWidth + (measure.barWidth || d.scrollbarH.clientWidth)) + "px";
} else {
d.scrollbarH.style.display = "";
d.scrollbarH.firstChild.style.width = "0";
}
if (needsH && needsV) {
d.scrollbarFiller.style.display = "block";
d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
} else d.scrollbarFiller.style.display = "";
if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
d.gutterFiller.style.display = "block";
d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
} else d.gutterFiller.style.display = "";
if (!cm.state.checkedOverlayScrollbar && measure.clientHeight > 0) {
if (scrollbarWidth(d.measure) === 0) {
var w = mac && !mac_geMountainLion ? "12px" : "18px";
d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = w;
var barMouseDown = function(e) {
if (e_target(e) != d.scrollbarV && e_target(e) != d.scrollbarH)
operation(cm, onMouseDown)(e);
};
on(d.scrollbarV, "mousedown", barMouseDown);
on(d.scrollbarH, "mousedown", barMouseDown);
}
cm.state.checkedOverlayScrollbar = true;
}
}
// Compute the lines that are visible in a given viewport (defaults
// the the current scroll position). viewPort may contain top,
// height, and ensure (see op.scrollToPos) properties.
function visibleLines(display, doc, viewPort) {
var top = viewPort && viewPort.top != null ? viewPort.top : display.scroller.scrollTop;
top = Math.floor(top - paddingTop(display));
var bottom = viewPort && viewPort.bottom != null ? viewPort.bottom : top + display.wrapper.clientHeight;
var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
// Ensure is a {from: {line, ch}, to: {line, ch}} object, and
// forces those lines into the viewport (if possible).
if (viewPort && viewPort.ensure) {
var ensureFrom = viewPort.ensure.from.line, ensureTo = viewPort.ensure.to.line;
if (ensureFrom < from)
return {from: ensureFrom,
to: lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)};
if (Math.min(ensureTo, doc.lastLine()) >= to)
return {from: lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight),
to: ensureTo};
}
return {from: from, to: to};
}
// LINE NUMBERS
// Re-align line numbers and gutter marks to compensate for
// horizontal scrolling.
function alignHorizontally(cm) {
var display = cm.display, view = display.view;
if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
var gutterW = display.gutters.offsetWidth, left = comp + "px";
for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
if (cm.options.fixedGutter && view[i].gutter)
view[i].gutter.style.left = left;
var align = view[i].alignable;
if (align) for (var j = 0; j < align.length; j++)
align[j].style.left = left;
}
if (cm.options.fixedGutter)
display.gutters.style.left = (comp + gutterW) + "px";
}
// Used to ensure that the line number gutter is still the right
// size for the current document size. Returns true when an update
// is needed.
function maybeUpdateLineNumberWidth(cm) {
if (!cm.options.lineNumbers) return false;
var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
if (last.length != display.lineNumChars) {
var test = display.measure.appendChild(elt("div", [elt("div", last)],
"CodeMirror-linenumber CodeMirror-gutter-elt"));
var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
display.lineGutter.style.width = "";
display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
display.lineNumWidth = display.lineNumInnerWidth + padding;
display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
display.lineGutter.style.width = display.lineNumWidth + "px";
updateGutterSpace(cm);
return true;
}
return false;
}
function lineNumberFor(options, i) {
return String(options.lineNumberFormatter(i + options.firstLineNumber));
}
// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
// but using getBoundingClientRect to get a sub-pixel-accurate
// result.
function compensateForHScroll(display) {
return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
}
// DISPLAY DRAWING
// Updates the display, selection, and scrollbars, using the
// information in display.view to find out which nodes are no longer
// up-to-date. Tries to bail out early when no changes are needed,
// unless forced is true.
// Returns true if an actual update happened, false otherwise.
function updateDisplay(cm, viewPort, forced) {
var oldFrom = cm.display.viewFrom, oldTo = cm.display.viewTo, updated;
var visible = visibleLines(cm.display, cm.doc, viewPort);
for (var first = true;; first = false) {
var oldWidth = cm.display.scroller.clientWidth;
if (!updateDisplayInner(cm, visible, forced)) break;
updated = true;
// If the max line changed since it was last measured, measure it,
// and ensure the document's width matches it.
if (cm.display.maxLineChanged && !cm.options.lineWrapping)
adjustContentWidth(cm);
var barMeasure = measureForScrollbars(cm);
updateSelection(cm);
setDocumentHeight(cm, barMeasure);
updateScrollbars(cm, barMeasure);
if (webkit && cm.options.lineWrapping)
checkForWebkitWidthBug(cm, barMeasure); // (Issue #2420)
if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) {
forced = true;
continue;
}
forced = false;
// Clip forced viewport to actual scrollable area.
if (viewPort && viewPort.top != null)
viewPort = {top: Math.min(barMeasure.docHeight - scrollerCutOff - barMeasure.clientHeight, viewPort.top)};
// Updated line heights might result in the drawn area not
// actually covering the viewport. Keep looping until it does.
visible = visibleLines(cm.display, cm.doc, viewPort);
if (visible.from >= cm.display.viewFrom && visible.to <= cm.display.viewTo)
break;
}
cm.display.updateLineNumbers = null;
if (updated) {
signalLater(cm, "update", cm);
if (cm.display.viewFrom != oldFrom || cm.display.viewTo != oldTo)
signalLater(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
}
return updated;
}
// Does the actual updating of the line display. Bails out
// (returning false) when there is nothing to be done and forced is
// false.
function updateDisplayInner(cm, visible, forced) {
var display = cm.display, doc = cm.doc;
if (!display.wrapper.offsetWidth) {
resetView(cm);
return;
}
// Bail out if the visible area is already rendered and nothing changed.
if (!forced && visible.from >= display.viewFrom && visible.to <= display.viewTo &&
countDirtyView(cm) == 0)
return;
if (maybeUpdateLineNumberWidth(cm))
resetView(cm);
var dims = getDimensions(cm);
// Compute a suitable new viewport (from & to)
var end = doc.first + doc.size;
var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
var to = Math.min(end, visible.to + cm.options.viewportMargin);
if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
if (sawCollapsedSpans) {
from = visualLineNo(cm.doc, from);
to = visualLineEndNo(cm.doc, to);
}
var different = from != display.viewFrom || to != display.viewTo ||
display.lastSizeC != display.wrapper.clientHeight;
adjustView(cm, from, to);
display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
// Position the mover div to align with the current scroll position
cm.display.mover.style.top = display.viewOffset + "px";
var toUpdate = countDirtyView(cm);
if (!different && toUpdate == 0 && !forced) return;
// For big changes, we hide the enclosing element during the
// update, since that speeds up the operations on most browsers.
var focused = activeElt();
if (toUpdate > 4) display.lineDiv.style.display = "none";
patchDisplay(cm, display.updateLineNumbers, dims);
if (toUpdate > 4) display.lineDiv.style.display = "";
// There might have been a widget with a focused element that got
// hidden or updated, if so re-focus it.
if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
// Prevent selection and cursors from interfering with the scroll
// width.
removeChildren(display.cursorDiv);
removeChildren(display.selectionDiv);
if (different) {
display.lastSizeC = display.wrapper.clientHeight;
startWorker(cm, 400);
}
updateHeightsInViewport(cm);
return true;
}
function adjustContentWidth(cm) {
var display = cm.display;
var width = measureChar(cm, display.maxLine, display.maxLine.text.length).left;
display.maxLineChanged = false;
var minWidth = Math.max(0, width + 3);
var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + minWidth + scrollerCutOff - display.scroller.clientWidth);
display.sizer.style.minWidth = minWidth + "px";
if (maxScrollLeft < cm.doc.scrollLeft)
setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
}
function setDocumentHeight(cm, measure) {
cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = measure.docHeight + "px";
cm.display.gutters.style.height = Math.max(measure.docHeight, measure.clientHeight - scrollerCutOff) + "px";
}
function checkForWebkitWidthBug(cm, measure) {
// Work around Webkit bug where it sometimes reserves space for a
// non-existing phantom scrollbar in the scroller (Issue #2420)
if (cm.display.sizer.offsetWidth + cm.display.gutters.offsetWidth < cm.display.scroller.clientWidth - 1) {
cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = "0px";
cm.display.gutters.style.height = measure.docHeight + "px";
}
}
// Read the actual heights of the rendered lines, and update their
// stored heights to match.
function updateHeightsInViewport(cm) {
var display = cm.display;
var prevBottom = display.lineDiv.offsetTop;
for (var i = 0; i < display.view.length; i++) {
var cur = display.view[i], height;
if (cur.hidden) continue;
if (ie_upto7) {
var bot = cur.node.offsetTop + cur.node.offsetHeight;
height = bot - prevBottom;
prevBottom = bot;
} else {
var box = cur.node.getBoundingClientRect();
height = box.bottom - box.top;
}
var diff = cur.line.height - height;
if (height < 2) height = textHeight(display);
if (diff > .001 || diff < -.001) {
updateLineHeight(cur.line, height);
updateWidgetHeight(cur.line);
if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
updateWidgetHeight(cur.rest[j]);
}
}
}
// Read and store the height of line widgets associated with the
// given line.
function updateWidgetHeight(line) {
if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
line.widgets[i].height = line.widgets[i].node.offsetHeight;
}
// Do a bulk-read of the DOM positions and sizes needed to draw the
// view, so that we don't interleave reading and writing to the DOM.
function getDimensions(cm) {
var d = cm.display, left = {}, width = {};
for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
left[cm.options.gutters[i]] = n.offsetLeft;
width[cm.options.gutters[i]] = n.offsetWidth;
}
return {fixedPos: compensateForHScroll(d),
gutterTotalWidth: d.gutters.offsetWidth,
gutterLeft: left,
gutterWidth: width,
wrapperWidth: d.wrapper.clientWidth};
}
// Sync the actual display DOM structure with display.view, removing
// nodes for lines that are no longer in view, and creating the ones
// that are not there yet, and updating the ones that are out of
// date.
function patchDisplay(cm, updateNumbersFrom, dims) {
var display = cm.display, lineNumbers = cm.options.lineNumbers;
var container = display.lineDiv, cur = container.firstChild;
function rm(node) {
var next = node.nextSibling;
// Works around a throw-scroll bug in OS X Webkit
if (webkit && mac && cm.display.currentWheelTarget == node)
node.style.display = "none";
else
node.parentNode.removeChild(node);
return next;
}
var view = display.view, lineN = display.viewFrom;
// Loop over the elements in the view, syncing cur (the DOM nodes
// in display.lineDiv) with the view as we go.
for (var i = 0; i < view.length; i++) {
var lineView = view[i];
if (lineView.hidden) {
} else if (!lineView.node) { // Not drawn yet
var node = buildLineElement(cm, lineView, lineN, dims);
container.insertBefore(node, cur);
} else { // Already drawn
while (cur != lineView.node) cur = rm(cur);
var updateNumber = lineNumbers && updateNumbersFrom != null &&
updateNumbersFrom <= lineN && lineView.lineNumber;
if (lineView.changes) {
if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
updateLineForChanges(cm, lineView, lineN, dims);
}
if (updateNumber) {
removeChildren(lineView.lineNumber);
lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
}
cur = lineView.node.nextSibling;
}
lineN += lineView.size;
}
while (cur) cur = rm(cur);
}
// When an aspect of a line changes, a string is added to
// lineView.changes. This updates the relevant part of the line's
// DOM structure.
function updateLineForChanges(cm, lineView, lineN, dims) {
for (var j = 0; j < lineView.changes.length; j++) {
var type = lineView.changes[j];
if (type == "text") updateLineText(cm, lineView);
else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
else if (type == "class") updateLineClasses(lineView);
else if (type == "widget") updateLineWidgets(lineView, dims);
}
lineView.changes = null;
}
// Lines with gutter elements, widgets or a background class need to
// be wrapped, and have the extra elements added to the wrapper div
function ensureLineWrapped(lineView) {
if (lineView.node == lineView.text) {
lineView.node = elt("div", null, null, "position: relative");
if (lineView.text.parentNode)
lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
lineView.node.appendChild(lineView.text);
if (ie_upto7) lineView.node.style.zIndex = 2;
}
return lineView.node;
}
function updateLineBackground(lineView) {
var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
if (cls) cls += " CodeMirror-linebackground";
if (lineView.background) {
if (cls) lineView.background.className = cls;
else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
} else if (cls) {
var wrap = ensureLineWrapped(lineView);
lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
}
}
// Wrapper around buildLineContent which will reuse the structure
// in display.externalMeasured when possible.
function getLineContent(cm, lineView) {
var ext = cm.display.externalMeasured;
if (ext && ext.line == lineView.line) {
cm.display.externalMeasured = null;
lineView.measure = ext.measure;
return ext.built;
}
return buildLineContent(cm, lineView);
}
// Redraw the line's text. Interacts with the background and text
// classes because the mode may output tokens that influence these
// classes.
function updateLineText(cm, lineView) {
var cls = lineView.text.className;
var built = getLineContent(cm, lineView);
if (lineView.text == lineView.node) lineView.node = built.pre;
lineView.text.parentNode.replaceChild(built.pre, lineView.text);
lineView.text = built.pre;
if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
lineView.bgClass = built.bgClass;
lineView.textClass = built.textClass;
updateLineClasses(lineView);
} else if (cls) {
lineView.text.className = cls;
}
}
function updateLineClasses(lineView) {
updateLineBackground(lineView);
if (lineView.line.wrapClass)
ensureLineWrapped(lineView).className = lineView.line.wrapClass;
else if (lineView.node != lineView.text)
lineView.node.className = "";
var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
lineView.text.className = textClass || "";
}
function updateLineGutter(cm, lineView, lineN, dims) {
if (lineView.gutter) {
lineView.node.removeChild(lineView.gutter);
lineView.gutter = null;
}
var markers = lineView.line.gutterMarkers;
if (cm.options.lineNumbers || markers) {
var wrap = ensureLineWrapped(lineView);
var gutterWrap = lineView.gutter =
wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "position: absolute; left: " +
(cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
lineView.text);
if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
lineView.lineNumber = gutterWrap.appendChild(
elt("div", lineNumberFor(cm.options, lineN),
"CodeMirror-linenumber CodeMirror-gutter-elt",
"left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
+ cm.display.lineNumInnerWidth + "px"));
if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
if (found)
gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
}
}
}
function updateLineWidgets(lineView, dims) {
if (lineView.alignable) lineView.alignable = null;
for (var node = lineView.node.firstChild, next; node; node = next) {
var next = node.nextSibling;
if (node.className == "CodeMirror-linewidget")
lineView.node.removeChild(node);
}
insertLineWidgets(lineView, dims);
}
// Build a line's DOM representation from scratch
function buildLineElement(cm, lineView, lineN, dims) {
var built = getLineContent(cm, lineView);
lineView.text = lineView.node = built.pre;
if (built.bgClass) lineView.bgClass = built.bgClass;
if (built.textClass) lineView.textClass = built.textClass;
updateLineClasses(lineView);
updateLineGutter(cm, lineView, lineN, dims);
insertLineWidgets(lineView, dims);
return lineView.node;
}
// A lineView may contain multiple logical lines (when merged by
// collapsed spans). The widgets for all of them need to be drawn.
function insertLineWidgets(lineView, dims) {
insertLineWidgetsFor(lineView.line, lineView, dims, true);
if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
insertLineWidgetsFor(lineView.rest[i], lineView, dims, false);
}
function insertLineWidgetsFor(line, lineView, dims, allowAbove) {
if (!line.widgets) return;
var wrap = ensureLineWrapped(lineView);
for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
if (!widget.handleMouseEvents) node.ignoreEvents = true;
positionLineWidget(widget, node, lineView, dims);
if (allowAbove && widget.above)
wrap.insertBefore(node, lineView.gutter || lineView.text);
else
wrap.appendChild(node);
signalLater(widget, "redraw");
}
}
function positionLineWidget(widget, node, lineView, dims) {
if (widget.noHScroll) {
(lineView.alignable || (lineView.alignable = [])).push(node);
var width = dims.wrapperWidth;
node.style.left = dims.fixedPos + "px";
if (!widget.coverGutter) {
width -= dims.gutterTotalWidth;
node.style.paddingLeft = dims.gutterTotalWidth + "px";
}
node.style.width = width + "px";
}
if (widget.coverGutter) {
node.style.zIndex = 5;
node.style.position = "relative";
if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
}
}
// POSITION OBJECT
// A Pos instance represents a position within the text.
var Pos = CodeMirror.Pos = function(line, ch) {
if (!(this instanceof Pos)) return new Pos(line, ch);
this.line = line; this.ch = ch;
};
// Compare two positions, return 0 if they are the same, a negative
// number when a is less, and a positive number otherwise.
var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
function copyPos(x) {return Pos(x.line, x.ch);}
function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
// SELECTION / CURSOR
// Selection objects are immutable. A new one is created every time
// the selection changes. A selection is one or more non-overlapping
// (and non-touching) ranges, sorted, and an integer that indicates
// which one is the primary selection (the one that's scrolled into
// view, that getCursor returns, etc).
function Selection(ranges, primIndex) {
this.ranges = ranges;
this.primIndex = primIndex;
}
Selection.prototype = {
primary: function() { return this.ranges[this.primIndex]; },
equals: function(other) {
if (other == this) return true;
if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
for (var i = 0; i < this.ranges.length; i++) {
var here = this.ranges[i], there = other.ranges[i];
if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
}
return true;
},
deepCopy: function() {
for (var out = [], i = 0; i < this.ranges.length; i++)
out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
return new Selection(out, this.primIndex);
},
somethingSelected: function() {
for (var i = 0; i < this.ranges.length; i++)
if (!this.ranges[i].empty()) return true;
return false;
},
contains: function(pos, end) {
if (!end) end = pos;
for (var i = 0; i < this.ranges.length; i++) {
var range = this.ranges[i];
if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
return i;
}
return -1;
}
};
function Range(anchor, head) {
this.anchor = anchor; this.head = head;
}
Range.prototype = {
from: function() { return minPos(this.anchor, this.head); },
to: function() { return maxPos(this.anchor, this.head); },
empty: function() {
return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
}
};
// Take an unsorted, potentially overlapping set of ranges, and
// build a selection out of it. 'Consumes' ranges array (modifying
// it).
function normalizeSelection(ranges, primIndex) {
var prim = ranges[primIndex];
ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
primIndex = indexOf(ranges, prim);
for (var i = 1; i < ranges.length; i++) {
var cur = ranges[i], prev = ranges[i - 1];
if (cmp(prev.to(), cur.from()) >= 0) {
var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
if (i <= primIndex) --primIndex;
ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
}
}
return new Selection(ranges, primIndex);
}
function simpleSelection(anchor, head) {
return new Selection([new Range(anchor, head || anchor)], 0);
}
// Most of the external API clips given positions to make sure they
// actually exist within the document.
function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
function clipPos(doc, pos) {
if (pos.line < doc.first) return Pos(doc.first, 0);
var last = doc.first + doc.size - 1;
if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
return clipToLen(pos, getLine(doc, pos.line).text.length);
}
function clipToLen(pos, linelen) {
var ch = pos.ch;
if (ch == null || ch > linelen) return Pos(pos.line, linelen);
else if (ch < 0) return Pos(pos.line, 0);
else return pos;
}
function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
function clipPosArray(doc, array) {
for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
return out;
}
// SELECTION UPDATES
// The 'scroll' parameter given to many of these indicated whether
// the new cursor position should be scrolled into view after
// modifying the selection.
// If shift is held or the extend flag is set, extends a range to
// include a given position (and optionally a second position).
// Otherwise, simply returns the range between the given positions.
// Used for cursor motion and such.
function extendRange(doc, range, head, other) {
if (doc.cm && doc.cm.display.shift || doc.extend) {
var anchor = range.anchor;
if (other) {
var posBefore = cmp(head, anchor) < 0;
if (posBefore != (cmp(other, anchor) < 0)) {
anchor = head;
head = other;
} else if (posBefore != (cmp(head, other) < 0)) {
head = other;
}
}
return new Range(anchor, head);
} else {
return new Range(other || head, head);
}
}
// Extend the primary selection range, discard the rest.
function extendSelection(doc, head, other, options) {
setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
}
// Extend all selections (pos is an array of selections with length
// equal the number of selections)
function extendSelections(doc, heads, options) {
for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
var newSel = normalizeSelection(out, doc.sel.primIndex);
setSelection(doc, newSel, options);
}
// Updates a single range in the selection.
function replaceOneSelection(doc, i, range, options) {
var ranges = doc.sel.ranges.slice(0);
ranges[i] = range;
setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
}
// Reset the selection to a single range.
function setSimpleSelection(doc, anchor, head, options) {
setSelection(doc, simpleSelection(anchor, head), options);
}
// Give beforeSelectionChange handlers a change to influence a
// selection update.
function filterSelectionChange(doc, sel) {
var obj = {
ranges: sel.ranges,
update: function(ranges) {
this.ranges = [];
for (var i = 0; i < ranges.length; i++)
this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
clipPos(doc, ranges[i].head));
}
};
signal(doc, "beforeSelectionChange", doc, obj);
if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
else return sel;
}
function setSelectionReplaceHistory(doc, sel, options) {
var done = doc.history.done, last = lst(done);
if (last && last.ranges) {
done[done.length - 1] = sel;
setSelectionNoUndo(doc, sel, options);
} else {
setSelection(doc, sel, options);
}
}
// Set a new selection.
function setSelection(doc, sel, options) {
setSelectionNoUndo(doc, sel, options);
addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
}
function setSelectionNoUndo(doc, sel, options) {
if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
sel = filterSelectionChange(doc, sel);
var bias = cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1;
setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
if (!(options && options.scroll === false) && doc.cm)
ensureCursorVisible(doc.cm);
}
function setSelectionInner(doc, sel) {
if (sel.equals(doc.sel)) return;
doc.sel = sel;
if (doc.cm) {
doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
signalCursorActivity(doc.cm);
}
signalLater(doc, "cursorActivity", doc);
}
// Verify that the selection does not partially select any atomic
// marked ranges.
function reCheckSelection(doc) {
setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
}
// Return a selection that does not partially select any atomic
// ranges.
function skipAtomicInSelection(doc, sel, bias, mayClear) {
var out;
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i];
var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
var newHead = skipAtomic(doc, range.head, bias, mayClear);
if (out || newAnchor != range.anchor || newHead != range.head) {
if (!out) out = sel.ranges.slice(0, i);
out[i] = new Range(newAnchor, newHead);
}
}
return out ? normalizeSelection(out, sel.primIndex) : sel;
}
// Ensure a given position is not inside an atomic range.
function skipAtomic(doc, pos, bias, mayClear) {
var flipped = false, curPos = pos;
var dir = bias || 1;
doc.cantEdit = false;
search: for (;;) {
var line = getLine(doc, curPos.line);
if (line.markedSpans) {
for (var i = 0; i < line.markedSpans.length; ++i) {
var sp = line.markedSpans[i], m = sp.marker;
if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
(sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
if (mayClear) {
signal(m, "beforeCursorEnter");
if (m.explicitlyCleared) {
if (!line.markedSpans) break;
else {--i; continue;}
}
}
if (!m.atomic) continue;
var newPos = m.find(dir < 0 ? -1 : 1);
if (cmp(newPos, curPos) == 0) {
newPos.ch += dir;
if (newPos.ch < 0) {
if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
else newPos = null;
} else if (newPos.ch > line.text.length) {
if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
else newPos = null;
}
if (!newPos) {
if (flipped) {
// Driven in a corner -- no valid cursor position found at all
// -- try again *with* clearing, if we didn't already
if (!mayClear) return skipAtomic(doc, pos, bias, true);
// Otherwise, turn off editing until further notice, and return the start of the doc
doc.cantEdit = true;
return Pos(doc.first, 0);
}
flipped = true; newPos = pos; dir = -dir;
}
}
curPos = newPos;
continue search;
}
}
}
return curPos;
}
}
// SELECTION DRAWING
// Redraw the selection and/or cursor
function updateSelection(cm) {
var display = cm.display, doc = cm.doc;
var curFragment = document.createDocumentFragment();
var selFragment = document.createDocumentFragment();
for (var i = 0; i < doc.sel.ranges.length; i++) {
var range = doc.sel.ranges[i];
var collapsed = range.empty();
if (collapsed || cm.options.showCursorWhenSelecting)
drawSelectionCursor(cm, range, curFragment);
if (!collapsed)
drawSelectionRange(cm, range, selFragment);
}
// Move the hidden textarea near the cursor to prevent scrolling artifacts
if (cm.options.moveInputWithCursor) {
var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
var top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
headPos.top + lineOff.top - wrapOff.top));
var left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
headPos.left + lineOff.left - wrapOff.left));
display.inputDiv.style.top = top + "px";
display.inputDiv.style.left = left + "px";
}
removeChildrenAndAdd(display.cursorDiv, curFragment);
removeChildrenAndAdd(display.selectionDiv, selFragment);
}
// Draws a cursor for the given range
function drawSelectionCursor(cm, range, output) {
var pos = cursorCoords(cm, range.head, "div");
var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
cursor.style.left = pos.left + "px";
cursor.style.top = pos.top + "px";
cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
if (pos.other) {
// Secondary cursor, shown when on a 'jump' in bi-directional text
var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
otherCursor.style.display = "";
otherCursor.style.left = pos.other.left + "px";
otherCursor.style.top = pos.other.top + "px";
otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
}
}
// Draws the given range as a highlighted selection
function drawSelectionRange(cm, range, output) {
var display = cm.display, doc = cm.doc;
var fragment = document.createDocumentFragment();
var padding = paddingH(cm.display), leftSide = padding.left, rightSide = display.lineSpace.offsetWidth - padding.right;
function add(left, top, width, bottom) {
if (top < 0) top = 0;
top = Math.round(top);
bottom = Math.round(bottom);
fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
"px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
"px; height: " + (bottom - top) + "px"));
}
function drawForLine(line, fromArg, toArg) {
var lineObj = getLine(doc, line);
var lineLen = lineObj.text.length;
var start, end;
function coords(ch, bias) {
return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
}
iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
var leftPos = coords(from, "left"), rightPos, left, right;
if (from == to) {
rightPos = leftPos;
left = right = leftPos.left;
} else {
rightPos = coords(to - 1, "right");
if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
left = leftPos.left;
right = rightPos.right;
}
if (fromArg == null && from == 0) left = leftSide;
if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
add(left, leftPos.top, null, leftPos.bottom);
left = leftSide;
if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
}
if (toArg == null && to == lineLen) right = rightSide;
if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
start = leftPos;
if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
end = rightPos;
if (left < leftSide + 1) left = leftSide;
add(left, rightPos.top, right - left, rightPos.bottom);
});
return {start: start, end: end};
}
var sFrom = range.from(), sTo = range.to();
if (sFrom.line == sTo.line) {
drawForLine(sFrom.line, sFrom.ch, sTo.ch);
} else {
var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
var singleVLine = visualLine(fromLine) == visualLine(toLine);
var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
if (singleVLine) {
if (leftEnd.top < rightStart.top - 2) {
add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
} else {
add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
}
}
if (leftEnd.bottom < rightStart.top)
add(leftSide, leftEnd.bottom, null, rightStart.top);
}
output.appendChild(fragment);
}
// Cursor-blinking
function restartBlink(cm) {
if (!cm.state.focused) return;
var display = cm.display;
clearInterval(display.blinker);
var on = true;
display.cursorDiv.style.visibility = "";
if (cm.options.cursorBlinkRate > 0)
display.blinker = setInterval(function() {
display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
}, cm.options.cursorBlinkRate);
}
// HIGHLIGHT WORKER
function startWorker(cm, time) {
if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
cm.state.highlight.set(time, bind(highlightWorker, cm));
}
function highlightWorker(cm) {
var doc = cm.doc;
if (doc.frontier < doc.first) doc.frontier = doc.first;
if (doc.frontier >= cm.display.viewTo) return;
var end = +new Date + cm.options.workTime;
var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
runInOp(cm, function() {
doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
if (doc.frontier >= cm.display.viewFrom) { // Visible
var oldStyles = line.styles;
var highlighted = highlightLine(cm, line, state, true);
line.styles = highlighted.styles;
if (highlighted.classes) line.styleClasses = highlighted.classes;
else if (line.styleClasses) line.styleClasses = null;
var ischange = !oldStyles || oldStyles.length != line.styles.length;
for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
if (ischange) regLineChange(cm, doc.frontier, "text");
line.stateAfter = copyState(doc.mode, state);
} else {
processLine(cm, line.text, state);
line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
}
++doc.frontier;
if (+new Date > end) {
startWorker(cm, cm.options.workDelay);
return true;
}
});
});
}
// Finds the line to start with when starting a parse. Tries to
// find a line with a stateAfter, so that it can start with a
// valid state. If that fails, it returns the line with the
// smallest indentation, which tends to need the least context to
// parse correctly.
function findStartLine(cm, n, precise) {
var minindent, minline, doc = cm.doc;
var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
for (var search = n; search > lim; --search) {
if (search <= doc.first) return doc.first;
var line = getLine(doc, search - 1);
if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
var indented = countColumn(line.text, null, cm.options.tabSize);
if (minline == null || minindent > indented) {
minline = search - 1;
minindent = indented;
}
}
return minline;
}
function getStateBefore(cm, n, precise) {
var doc = cm.doc, display = cm.display;
if (!doc.mode.startState) return true;
var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
if (!state) state = startState(doc.mode);
else state = copyState(doc.mode, state);
doc.iter(pos, n, function(line) {
processLine(cm, line.text, state);
var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
line.stateAfter = save ? copyState(doc.mode, state) : null;
++pos;
});
if (precise) doc.frontier = pos;
return state;
}
// POSITION MEASUREMENT
function paddingTop(display) {return display.lineSpace.offsetTop;}
function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
function paddingH(display) {
if (display.cachedPaddingH) return display.cachedPaddingH;
var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
return data;
}
// Ensure the lineView.wrapping.heights array is populated. This is
// an array of bottom offsets for the lines that make up a drawn
// line. When lineWrapping is on, there might be more than one
// height.
function ensureLineHeights(cm, lineView, rect) {
var wrapping = cm.options.lineWrapping;
var curWidth = wrapping && cm.display.scroller.clientWidth;
if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
var heights = lineView.measure.heights = [];
if (wrapping) {
lineView.measure.width = curWidth;
var rects = lineView.text.firstChild.getClientRects();
for (var i = 0; i < rects.length - 1; i++) {
var cur = rects[i], next = rects[i + 1];
if (Math.abs(cur.bottom - next.bottom) > 2)
heights.push((cur.bottom + next.top) / 2 - rect.top);
}
}
heights.push(rect.bottom - rect.top);
}
}
// Find a line map (mapping character offsets to text nodes) and a
// measurement cache for the given line number. (A line view might
// contain multiple lines when collapsed ranges are present.)
function mapFromLineView(lineView, line, lineN) {
if (lineView.line == line)
return {map: lineView.measure.map, cache: lineView.measure.cache};
for (var i = 0; i < lineView.rest.length; i++)
if (lineView.rest[i] == line)
return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
for (var i = 0; i < lineView.rest.length; i++)
if (lineNo(lineView.rest[i]) > lineN)
return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
}
// Render a line into the hidden node display.externalMeasured. Used
// when measurement is needed for a line that's not in the viewport.
function updateExternalMeasurement(cm, line) {
line = visualLine(line);
var lineN = lineNo(line);
var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
view.lineN = lineN;
var built = view.built = buildLineContent(cm, view);
view.text = built.pre;
removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
return view;
}
// Get a {top, bottom, left, right} box (in line-local coordinates)
// for a given character.
function measureChar(cm, line, ch, bias) {
return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
}
// Find a line view that corresponds to the given line number.
function findViewForLine(cm, lineN) {
if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
return cm.display.view[findViewIndex(cm, lineN)];
var ext = cm.display.externalMeasured;
if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
return ext;
}
// Measurement can be split in two steps, the set-up work that
// applies to the whole line, and the measurement of the actual
// character. Functions like coordsChar, that need to do a lot of
// measurements in a row, can thus ensure that the set-up work is
// only done once.
function prepareMeasureForLine(cm, line) {
var lineN = lineNo(line);
var view = findViewForLine(cm, lineN);
if (view && !view.text)
view = null;
else if (view && view.changes)
updateLineForChanges(cm, view, lineN, getDimensions(cm));
if (!view)
view = updateExternalMeasurement(cm, line);
var info = mapFromLineView(view, line, lineN);
return {
line: line, view: view, rect: null,
map: info.map, cache: info.cache, before: info.before,
hasHeights: false
};
}
// Given a prepared measurement object, measures the position of an
// actual character (or fetches it from the cache).
function measureCharPrepared(cm, prepared, ch, bias) {
if (prepared.before) ch = -1;
var key = ch + (bias || ""), found;
if (prepared.cache.hasOwnProperty(key)) {
found = prepared.cache[key];
} else {
if (!prepared.rect)
prepared.rect = prepared.view.text.getBoundingClientRect();
if (!prepared.hasHeights) {
ensureLineHeights(cm, prepared.view, prepared.rect);
prepared.hasHeights = true;
}
found = measureCharInner(cm, prepared, ch, bias);
if (!found.bogus) prepared.cache[key] = found;
}
return {left: found.left, right: found.right, top: found.top, bottom: found.bottom};
}
var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
function measureCharInner(cm, prepared, ch, bias) {
var map = prepared.map;
var node, start, end, collapse;
// First, search the line map for the text node corresponding to,
// or closest to, the target character.
for (var i = 0; i < map.length; i += 3) {
var mStart = map[i], mEnd = map[i + 1];
if (ch < mStart) {
start = 0; end = 1;
collapse = "left";
} else if (ch < mEnd) {
start = ch - mStart;
end = start + 1;
} else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
end = mEnd - mStart;
start = end - 1;
if (ch >= mEnd) collapse = "right";
}
if (start != null) {
node = map[i + 2];
if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
collapse = bias;
if (bias == "left" && start == 0)
while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
node = map[(i -= 3) + 2];
collapse = "left";
}
if (bias == "right" && start == mEnd - mStart)
while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
node = map[(i += 3) + 2];
collapse = "right";
}
break;
}
}
var rect;
if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start;
while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end;
if (ie_upto8 && start == 0 && end == mEnd - mStart) {
rect = node.parentNode.getBoundingClientRect();
} else if (ie && cm.options.lineWrapping) {
var rects = range(node, start, end).getClientRects();
if (rects.length)
rect = rects[bias == "right" ? rects.length - 1 : 0];
else
rect = nullRect;
} else {
rect = range(node, start, end).getBoundingClientRect() || nullRect;
}
} else { // If it is a widget, simply get the box for the whole widget.
if (start > 0) collapse = bias = "right";
var rects;
if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
rect = rects[bias == "right" ? rects.length - 1 : 0];
else
rect = node.getBoundingClientRect();
}
if (ie_upto8 && !start && (!rect || !rect.left && !rect.right)) {
var rSpan = node.parentNode.getClientRects()[0];
if (rSpan)
rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
else
rect = nullRect;
}
var top, bot = (rect.bottom + rect.top) / 2 - prepared.rect.top;
var heights = prepared.view.measure.heights;
for (var i = 0; i < heights.length - 1; i++)
if (bot < heights[i]) break;
top = i ? heights[i - 1] : 0; bot = heights[i];
var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
top: top, bottom: bot};
if (!rect.left && !rect.right) result.bogus = true;
return result;
}
function clearLineMeasurementCacheFor(lineView) {
if (lineView.measure) {
lineView.measure.cache = {};
lineView.measure.heights = null;
if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
lineView.measure.caches[i] = {};
}
}
function clearLineMeasurementCache(cm) {
cm.display.externalMeasure = null;
removeChildren(cm.display.lineMeasure);
for (var i = 0; i < cm.display.view.length; i++)
clearLineMeasurementCacheFor(cm.display.view[i]);
}
function clearCaches(cm) {
clearLineMeasurementCache(cm);
cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
cm.display.lineNumChars = null;
}
function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
// Converts a {top, bottom, left, right} box from line-local
// coordinates into another coordinate system. Context may be one of
// "line", "div" (display.lineDiv), "local"/null (editor), or "page".
function intoCoordSystem(cm, lineObj, rect, context) {
if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
var size = widgetHeight(lineObj.widgets[i]);
rect.top += size; rect.bottom += size;
}
if (context == "line") return rect;
if (!context) context = "local";
var yOff = heightAtLine(lineObj);
if (context == "local") yOff += paddingTop(cm.display);
else yOff -= cm.display.viewOffset;
if (context == "page" || context == "window") {
var lOff = cm.display.lineSpace.getBoundingClientRect();
yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
rect.left += xOff; rect.right += xOff;
}
rect.top += yOff; rect.bottom += yOff;
return rect;
}
// Coverts a box from "div" coords to another coordinate system.
// Context may be "window", "page", "div", or "local"/null.
function fromCoordSystem(cm, coords, context) {
if (context == "div") return coords;
var left = coords.left, top = coords.top;
// First move into "page" coordinate system
if (context == "page") {
left -= pageScrollX();
top -= pageScrollY();
} else if (context == "local" || !context) {
var localBox = cm.display.sizer.getBoundingClientRect();
left += localBox.left;
top += localBox.top;
}
var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
}
function charCoords(cm, pos, context, lineObj, bias) {
if (!lineObj) lineObj = getLine(cm.doc, pos.line);
return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
}
// Returns a box for a given cursor position, which may have an
// 'other' property containing the position of the secondary cursor
// on a bidi boundary.
function cursorCoords(cm, pos, context, lineObj, preparedMeasure) {
lineObj = lineObj || getLine(cm.doc, pos.line);
if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
function get(ch, right) {
var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left");
if (right) m.left = m.right; else m.right = m.left;
return intoCoordSystem(cm, lineObj, m, context);
}
function getBidi(ch, partPos) {
var part = order[partPos], right = part.level % 2;
if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
part = order[--partPos];
ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
right = true;
} else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
part = order[++partPos];
ch = bidiLeft(part) - part.level % 2;
right = false;
}
if (right && ch == part.to && ch > part.from) return get(ch - 1);
return get(ch, right);
}
var order = getOrder(lineObj), ch = pos.ch;
if (!order) return get(ch);
var partPos = getBidiPartAt(order, ch);
var val = getBidi(ch, partPos);
if (bidiOther != null) val.other = getBidi(ch, bidiOther);
return val;
}
// Used to cheaply estimate the coordinates for a position. Used for
// intermediate scroll updates.
function estimateCoords(cm, pos) {
var left = 0, pos = clipPos(cm.doc, pos);
if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
var lineObj = getLine(cm.doc, pos.line);
var top = heightAtLine(lineObj) + paddingTop(cm.display);
return {left: left, right: left, top: top, bottom: top + lineObj.height};
}
// Positions returned by coordsChar contain some extra information.
// xRel is the relative x position of the input coordinates compared
// to the found position (so xRel > 0 means the coordinates are to
// the right of the character position, for example). When outside
// is true, that means the coordinates lie outside the line's
// vertical range.
function PosWithInfo(line, ch, outside, xRel) {
var pos = Pos(line, ch);
pos.xRel = xRel;
if (outside) pos.outside = true;
return pos;
}
// Compute the character position closest to the given coordinates.
// Input must be lineSpace-local ("div" coordinate system).
function coordsChar(cm, x, y) {
var doc = cm.doc;
y += cm.display.viewOffset;
if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
if (lineN > last)
return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
if (x < 0) x = 0;
var lineObj = getLine(doc, lineN);
for (;;) {
var found = coordsCharInner(cm, lineObj, lineN, x, y);
var merged = collapsedSpanAtEnd(lineObj);
var mergedPos = merged && merged.find(0, true);
if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
lineN = lineNo(lineObj = mergedPos.to.line);
else
return found;
}
}
function coordsCharInner(cm, lineObj, lineNo, x, y) {
var innerOff = y - heightAtLine(lineObj);
var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
var preparedMeasure = prepareMeasureForLine(cm, lineObj);
function getX(ch) {
var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
wrongLine = true;
if (innerOff > sp.bottom) return sp.left - adjust;
else if (innerOff < sp.top) return sp.left + adjust;
else wrongLine = false;
return sp.left;
}
var bidi = getOrder(lineObj), dist = lineObj.text.length;
var from = lineLeft(lineObj), to = lineRight(lineObj);
var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
// Do a binary search between these bounds.
for (;;) {
if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
var ch = x < fromX || x - fromX <= toX - x ? from : to;
var xDiff = x - (ch == from ? fromX : toX);
while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
return pos;
}
var step = Math.ceil(dist / 2), middle = from + step;
if (bidi) {
middle = from;
for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
}
var middleX = getX(middle);
if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
}
}
var measureText;
// Compute the default text height.
function textHeight(display) {
if (display.cachedTextHeight != null) return display.cachedTextHeight;
if (measureText == null) {
measureText = elt("pre");
// Measure a bunch of lines, for browsers that compute
// fractional heights.
for (var i = 0; i < 49; ++i) {
measureText.appendChild(document.createTextNode("x"));
measureText.appendChild(elt("br"));
}
measureText.appendChild(document.createTextNode("x"));
}
removeChildrenAndAdd(display.measure, measureText);
var height = measureText.offsetHeight / 50;
if (height > 3) display.cachedTextHeight = height;
removeChildren(display.measure);
return height || 1;
}
// Compute the default character width.
function charWidth(display) {
if (display.cachedCharWidth != null) return display.cachedCharWidth;
var anchor = elt("span", "xxxxxxxxxx");
var pre = elt("pre", [anchor]);
removeChildrenAndAdd(display.measure, pre);
var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
if (width > 2) display.cachedCharWidth = width;
return width || 10;
}
// OPERATIONS
// Operations are used to wrap a series of changes to the editor
// state in such a way that each change won't have to update the
// cursor and display (which would be awkward, slow, and
// error-prone). Instead, display updates are batched and then all
// combined and executed at once.
var nextOpId = 0;
// Start a new operation.
function startOperation(cm) {
cm.curOp = {
viewChanged: false, // Flag that indicates that lines might need to be redrawn
startHeight: cm.doc.height, // Used to detect need to update scrollbar
forceUpdate: false, // Used to force a redraw
updateInput: null, // Whether to reset the input textarea
typing: false, // Whether this reset should be careful to leave existing text (for compositing)
changeObjs: null, // Accumulated changes, for firing change events
cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
selectionChanged: false, // Whether the selection needs to be redrawn
updateMaxLine: false, // Set when the widest line needs to be determined anew
scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
scrollToPos: null, // Used to scroll to a specific position
id: ++nextOpId // Unique ID
};
if (!delayedCallbackDepth++) delayedCallbacks = [];
}
// Finish an operation, updating the display and signalling delayed events
function endOperation(cm) {
var op = cm.curOp, doc = cm.doc, display = cm.display;
cm.curOp = null;
if (op.updateMaxLine) findMaxLine(cm);
// If it looks like an update might be needed, call updateDisplay
if (op.viewChanged || op.forceUpdate || op.scrollTop != null ||
op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
op.scrollToPos.to.line >= display.viewTo) ||
display.maxLineChanged && cm.options.lineWrapping) {
var updated = updateDisplay(cm, {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
}
// If no update was run, but the selection changed, redraw that.
if (!updated && op.selectionChanged) updateSelection(cm);
if (!updated && op.startHeight != cm.doc.height) updateScrollbars(cm);
// Propagate the scroll position to the actual DOM scroller
if (op.scrollTop != null && display.scroller.scrollTop != op.scrollTop) {
var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top;
}
if (op.scrollLeft != null && display.scroller.scrollLeft != op.scrollLeft) {
var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left;
alignHorizontally(cm);
}
// If we need to scroll a specific position into view, do so.
if (op.scrollToPos) {
var coords = scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from),
clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.margin);
if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
}
if (op.selectionChanged) restartBlink(cm);
if (cm.state.focused && op.updateInput)
resetInput(cm, op.typing);
// Fire events for markers that are hidden/unidden by editing or
// undoing
var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
if (hidden) for (var i = 0; i < hidden.length; ++i)
if (!hidden[i].lines.length) signal(hidden[i], "hide");
if (unhidden) for (var i = 0; i < unhidden.length; ++i)
if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
var delayed;
if (!--delayedCallbackDepth) {
delayed = delayedCallbacks;
delayedCallbacks = null;
}
// Fire change events, and delayed event handlers
if (op.changeObjs)
signal(cm, "changes", cm, op.changeObjs);
if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
if (op.cursorActivityHandlers)
for (var i = 0; i < op.cursorActivityHandlers.length; i++)
op.cursorActivityHandlers[i](cm);
}
// Run the given function in an operation
function runInOp(cm, f) {
if (cm.curOp) return f();
startOperation(cm);
try { return f(); }
finally { endOperation(cm); }
}
// Wraps a function in an operation. Returns the wrapped function.
function operation(cm, f) {
return function() {
if (cm.curOp) return f.apply(cm, arguments);
startOperation(cm);
try { return f.apply(cm, arguments); }
finally { endOperation(cm); }
};
}
// Used to add methods to editor and doc instances, wrapping them in
// operations.
function methodOp(f) {
return function() {
if (this.curOp) return f.apply(this, arguments);
startOperation(this);
try { return f.apply(this, arguments); }
finally { endOperation(this); }
};
}
function docMethodOp(f) {
return function() {
var cm = this.cm;
if (!cm || cm.curOp) return f.apply(this, arguments);
startOperation(cm);
try { return f.apply(this, arguments); }
finally { endOperation(cm); }
};
}
// VIEW TRACKING
// These objects are used to represent the visible (currently drawn)
// part of the document. A LineView may correspond to multiple
// logical lines, if those are connected by collapsed ranges.
function LineView(doc, line, lineN) {
// The starting line
this.line = line;
// Continuing lines, if any
this.rest = visualLineContinued(line);
// Number of logical lines in this visual line
this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
this.node = this.text = null;
this.hidden = lineIsHidden(doc, line);
}
// Create a range of LineView objects for the given lines.
function buildViewArray(cm, from, to) {
var array = [], nextPos;
for (var pos = from; pos < to; pos = nextPos) {
var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
nextPos = pos + view.size;
array.push(view);
}
return array;
}
// Updates the display.view data structure for a given change to the
// document. From and to are in pre-change coordinates. Lendiff is
// the amount of lines added or subtracted by the change. This is
// used for changes that span multiple lines, or change the way
// lines are divided into visual lines. regLineChange (below)
// registers single-line changes.
function regChange(cm, from, to, lendiff) {
if (from == null) from = cm.doc.first;
if (to == null) to = cm.doc.first + cm.doc.size;
if (!lendiff) lendiff = 0;
var display = cm.display;
if (lendiff && to < display.viewTo &&
(display.updateLineNumbers == null || display.updateLineNumbers > from))
display.updateLineNumbers = from;
cm.curOp.viewChanged = true;
if (from >= display.viewTo) { // Change after
if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
resetView(cm);
} else if (to <= display.viewFrom) { // Change before
if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
resetView(cm);
} else {
display.viewFrom += lendiff;
display.viewTo += lendiff;
}
} else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
resetView(cm);
} else if (from <= display.viewFrom) { // Top overlap
var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
if (cut) {
display.view = display.view.slice(cut.index);
display.viewFrom = cut.lineN;
display.viewTo += lendiff;
} else {
resetView(cm);
}
} else if (to >= display.viewTo) { // Bottom overlap
var cut = viewCuttingPoint(cm, from, from, -1);
if (cut) {
display.view = display.view.slice(0, cut.index);
display.viewTo = cut.lineN;
} else {
resetView(cm);
}
} else { // Gap in the middle
var cutTop = viewCuttingPoint(cm, from, from, -1);
var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
if (cutTop && cutBot) {
display.view = display.view.slice(0, cutTop.index)
.concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
.concat(display.view.slice(cutBot.index));
display.viewTo += lendiff;
} else {
resetView(cm);
}
}
var ext = display.externalMeasured;
if (ext) {
if (to < ext.lineN)
ext.lineN += lendiff;
else if (from < ext.lineN + ext.size)
display.externalMeasured = null;
}
}
// Register a change to a single line. Type must be one of "text",
// "gutter", "class", "widget"
function regLineChange(cm, line, type) {
cm.curOp.viewChanged = true;
var display = cm.display, ext = cm.display.externalMeasured;
if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
display.externalMeasured = null;
if (line < display.viewFrom || line >= display.viewTo) return;
var lineView = display.view[findViewIndex(cm, line)];
if (lineView.node == null) return;
var arr = lineView.changes || (lineView.changes = []);
if (indexOf(arr, type) == -1) arr.push(type);
}
// Clear the view.
function resetView(cm) {
cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
cm.display.view = [];
cm.display.viewOffset = 0;
}
// Find the view element corresponding to a given line. Return null
// when the line isn't visible.
function findViewIndex(cm, n) {
if (n >= cm.display.viewTo) return null;
n -= cm.display.viewFrom;
if (n < 0) return null;
var view = cm.display.view;
for (var i = 0; i < view.length; i++) {
n -= view[i].size;
if (n < 0) return i;
}
}
function viewCuttingPoint(cm, oldN, newN, dir) {
var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
return {index: index, lineN: newN};
for (var i = 0, n = cm.display.viewFrom; i < index; i++)
n += view[i].size;
if (n != oldN) {
if (dir > 0) {
if (index == view.length - 1) return null;
diff = (n + view[index].size) - oldN;
index++;
} else {
diff = n - oldN;
}
oldN += diff; newN += diff;
}
while (visualLineNo(cm.doc, newN) != newN) {
if (index == (dir < 0 ? 0 : view.length - 1)) return null;
newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
index += dir;
}
return {index: index, lineN: newN};
}
// Force the view to cover a given range, adding empty view element
// or clipping off existing ones as needed.
function adjustView(cm, from, to) {
var display = cm.display, view = display.view;
if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
display.view = buildViewArray(cm, from, to);
display.viewFrom = from;
} else {
if (display.viewFrom > from)
display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
else if (display.viewFrom < from)
display.view = display.view.slice(findViewIndex(cm, from));
display.viewFrom = from;
if (display.viewTo < to)
display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
else if (display.viewTo > to)
display.view = display.view.slice(0, findViewIndex(cm, to));
}
display.viewTo = to;
}
// Count the number of lines in the view whose DOM representation is
// out of date (or nonexistent).
function countDirtyView(cm) {
var view = cm.display.view, dirty = 0;
for (var i = 0; i < view.length; i++) {
var lineView = view[i];
if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
}
return dirty;
}
// INPUT HANDLING
// Poll for input changes, using the normal rate of polling. This
// runs as long as the editor is focused.
function slowPoll(cm) {
if (cm.display.pollingFast) return;
cm.display.poll.set(cm.options.pollInterval, function() {
readInput(cm);
if (cm.state.focused) slowPoll(cm);
});
}
// When an event has just come in that is likely to add or change
// something in the input textarea, we poll faster, to ensure that
// the change appears on the screen quickly.
function fastPoll(cm) {
var missed = false;
cm.display.pollingFast = true;
function p() {
var changed = readInput(cm);
if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
else {cm.display.pollingFast = false; slowPoll(cm);}
}
cm.display.poll.set(20, p);
}
// Read input from the textarea, and update the document to match.
// When something is selected, it is present in the textarea, and
// selected (unless it is huge, in which case a placeholder is
// used). When nothing is selected, the cursor sits after previously
// seen text (can be empty), which is stored in prevInput (we must
// not reset the textarea when typing, because that breaks IME).
function readInput(cm) {
var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc;
// Since this is called a *lot*, try to bail out as cheaply as
// possible when it is clear that nothing happened. hasSelection
// will be the case when there is a lot of text in the textarea,
// in which case reading its value would be expensive.
if (!cm.state.focused || (hasSelection(input) && !prevInput) || isReadOnly(cm) || cm.options.disableInput)
return false;
// See paste handler for more on the fakedLastChar kludge
if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
input.value = input.value.substring(0, input.value.length - 1);
cm.state.fakedLastChar = false;
}
var text = input.value;
// If nothing changed, bail.
if (text == prevInput && !cm.somethingSelected()) return false;
// Work around nonsensical selection resetting in IE9/10
if (ie && !ie_upto8 && cm.display.inputHasSelection === text) {
resetInput(cm);
return false;
}
var withOp = !cm.curOp;
if (withOp) startOperation(cm);
cm.display.shift = false;
if (text.charCodeAt(0) == 0x200b && doc.sel == cm.display.selForContextMenu && !prevInput)
prevInput = "\u200b";
// Find the part of the input that is actually new
var same = 0, l = Math.min(prevInput.length, text.length);
while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
var inserted = text.slice(same), textLines = splitLines(inserted);
// When pasing N lines into N selections, insert one line per selection
var multiPaste = cm.state.pasteIncoming && textLines.length > 1 && doc.sel.ranges.length == textLines.length;
// Normal behavior is to insert the new text into every selection
for (var i = doc.sel.ranges.length - 1; i >= 0; i--) {
var range = doc.sel.ranges[i];
var from = range.from(), to = range.to();
// Handle deletion
if (same < prevInput.length)
from = Pos(from.line, from.ch - (prevInput.length - same));
// Handle overwrite
else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming)
to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
var updateInput = cm.curOp.updateInput;
var changeEvent = {from: from, to: to, text: multiPaste ? [textLines[i]] : textLines,
origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
makeChange(cm.doc, changeEvent);
signalLater(cm, "inputRead", cm, changeEvent);
// When an 'electric' character is inserted, immediately trigger a reindent
if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
cm.options.smartIndent && range.head.ch < 100 &&
(!i || doc.sel.ranges[i - 1].head.line != range.head.line)) {
var mode = cm.getModeAt(range.head);
if (mode.electricChars) {
for (var j = 0; j < mode.electricChars.length; j++)
if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
indentLine(cm, range.head.line, "smart");
break;
}
} else if (mode.electricInput) {
var end = changeEnd(changeEvent);
if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch)))
indentLine(cm, range.head.line, "smart");
}
}
}
ensureCursorVisible(cm);
cm.curOp.updateInput = updateInput;
cm.curOp.typing = true;
// Don't leave long text in the textarea, since it makes further polling slow
if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
else cm.display.prevInput = text;
if (withOp) endOperation(cm);
cm.state.pasteIncoming = cm.state.cutIncoming = false;
return true;
}
// Reset the input to correspond to the selection (or to be empty,
// when not typing and nothing is selected)
function resetInput(cm, typing) {
var minimal, selected, doc = cm.doc;
if (cm.somethingSelected()) {
cm.display.prevInput = "";
var range = doc.sel.primary();
minimal = hasCopyEvent &&
(range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
var content = minimal ? "-" : selected || cm.getSelection();
cm.display.input.value = content;
if (cm.state.focused) selectInput(cm.display.input);
if (ie && !ie_upto8) cm.display.inputHasSelection = content;
} else if (!typing) {
cm.display.prevInput = cm.display.input.value = "";
if (ie && !ie_upto8) cm.display.inputHasSelection = null;
}
cm.display.inaccurateSelection = minimal;
}
function focusInput(cm) {
if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.display.input))
cm.display.input.focus();
}
function ensureFocus(cm) {
if (!cm.state.focused) { focusInput(cm); onFocus(cm); }
}
function isReadOnly(cm) {
return cm.options.readOnly || cm.doc.cantEdit;
}
// EVENT HANDLERS
// Attach the necessary event handlers when initializing the editor
function registerEventHandlers(cm) {
var d = cm.display;
on(d.scroller, "mousedown", operation(cm, onMouseDown));
// Older IE's will not fire a second mousedown for a double click
if (ie_upto10)
on(d.scroller, "dblclick", operation(cm, function(e) {
if (signalDOMEvent(cm, e)) return;
var pos = posFromMouse(cm, e);
if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
e_preventDefault(e);
var word = findWordAt(cm, pos);
extendSelection(cm.doc, word.anchor, word.head);
}));
else
on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
// Prevent normal selection in the editor (we handle our own)
on(d.lineSpace, "selectstart", function(e) {
if (!eventInWidget(d, e)) e_preventDefault(e);
});
// Some browsers fire contextmenu *after* opening the menu, at
// which point we can't mess with it anymore. Context menu is
// handled in onMouseDown for these browsers.
if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
// Sync scrolling between fake scrollbars and real scrollable
// area, ensure viewport is updated when scrolling.
on(d.scroller, "scroll", function() {
if (d.scroller.clientHeight) {
setScrollTop(cm, d.scroller.scrollTop);
setScrollLeft(cm, d.scroller.scrollLeft, true);
signal(cm, "scroll", cm);
}
});
on(d.scrollbarV, "scroll", function() {
if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
});
on(d.scrollbarH, "scroll", function() {
if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
});
// Listen to wheel events in order to try and update the viewport on time.
on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
// Prevent clicks in the scrollbars from killing focus
function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
on(d.scrollbarH, "mousedown", reFocus);
on(d.scrollbarV, "mousedown", reFocus);
// Prevent wrapper from ever scrolling
on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
on(d.input, "keyup", operation(cm, onKeyUp));
on(d.input, "input", function() {
if (ie && !ie_upto8 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;
fastPoll(cm);
});
on(d.input, "keydown", operation(cm, onKeyDown));
on(d.input, "keypress", operation(cm, onKeyPress));
on(d.input, "focus", bind(onFocus, cm));
on(d.input, "blur", bind(onBlur, cm));
function drag_(e) {
if (!signalDOMEvent(cm, e)) e_stop(e);
}
if (cm.options.dragDrop) {
on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
on(d.scroller, "dragenter", drag_);
on(d.scroller, "dragover", drag_);
on(d.scroller, "drop", operation(cm, onDrop));
}
on(d.scroller, "paste", function(e) {
if (eventInWidget(d, e)) return;
cm.state.pasteIncoming = true;
focusInput(cm);
fastPoll(cm);
});
on(d.input, "paste", function() {
// Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
// Add a char to the end of textarea before paste occur so that
// selection doesn't span to the end of textarea.
if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
var start = d.input.selectionStart, end = d.input.selectionEnd;
d.input.value += "$";
d.input.selectionStart = start;
d.input.selectionEnd = end;
cm.state.fakedLastChar = true;
}
cm.state.pasteIncoming = true;
fastPoll(cm);
});
function prepareCopyCut(e) {
if (cm.somethingSelected()) {
if (d.inaccurateSelection) {
d.prevInput = "";
d.inaccurateSelection = false;
d.input.value = cm.getSelection();
selectInput(d.input);
}
} else {
var text = "", ranges = [];
for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
var line = cm.doc.sel.ranges[i].head.line;
var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
ranges.push(lineRange);
text += cm.getRange(lineRange.anchor, lineRange.head);
}
if (e.type == "cut") {
cm.setSelections(ranges, null, sel_dontScroll);
} else {
d.prevInput = "";
d.input.value = text;
selectInput(d.input);
}
}
if (e.type == "cut") cm.state.cutIncoming = true;
}
on(d.input, "cut", prepareCopyCut);
on(d.input, "copy", prepareCopyCut);
// Needed to handle Tab key in KHTML
if (khtml) on(d.sizer, "mouseup", function() {
if (activeElt() == d.input) d.input.blur();
focusInput(cm);
});
}
// Called when the window resizes
function onResize(cm) {
// Might be a text scaling operation, clear size caches.
var d = cm.display;
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
cm.setSize();
}
// MOUSE EVENTS
// Return true when the given mouse event happened in a widget
function eventInWidget(display, e) {
for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
}
}
// Given a mouse event, find the corresponding position. If liberal
// is false, it checks whether a gutter or scrollbar was clicked,
// and returns null if it was. forRect is used by rectangular
// selections, and tries to estimate a character position even for
// coordinates beyond the right of the text.
function posFromMouse(cm, e, liberal, forRect) {
var display = cm.display;
if (!liberal) {
var target = e_target(e);
if (target == display.scrollbarH || target == display.scrollbarV ||
target == display.scrollbarFiller || target == display.gutterFiller) return null;
}
var x, y, space = display.lineSpace.getBoundingClientRect();
// Fails unpredictably on IE[67] when mouse is dragged around quickly.
try { x = e.clientX - space.left; y = e.clientY - space.top; }
catch (e) { return null; }
var coords = coordsChar(cm, x, y), line;
if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
}
return coords;
}
// A mouse down can be a single click, double click, triple click,
// start of selection drag, start of text drag, new cursor
// (ctrl-click), rectangle drag (alt-drag), or xwin
// middle-click-paste. Or it might be a click on something we should
// not interfere with, such as a scrollbar or widget.
function onMouseDown(e) {
if (signalDOMEvent(this, e)) return;
var cm = this, display = cm.display;
display.shift = e.shiftKey;
if (eventInWidget(display, e)) {
if (!webkit) {
// Briefly turn off draggability, to allow widgets to do
// normal dragging things.
display.scroller.draggable = false;
setTimeout(function(){display.scroller.draggable = true;}, 100);
}
return;
}
if (clickInGutter(cm, e)) return;
var start = posFromMouse(cm, e);
window.focus();
switch (e_button(e)) {
case 1:
if (start)
leftButtonDown(cm, e, start);
else if (e_target(e) == display.scroller)
e_preventDefault(e);
break;
case 2:
if (webkit) cm.state.lastMiddleDown = +new Date;
if (start) extendSelection(cm.doc, start);
setTimeout(bind(focusInput, cm), 20);
e_preventDefault(e);
break;
case 3:
if (captureRightClick) onContextMenu(cm, e);
break;
}
}
var lastClick, lastDoubleClick;
function leftButtonDown(cm, e, start) {
setTimeout(bind(ensureFocus, cm), 0);
var now = +new Date, type;
if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
type = "triple";
} else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
type = "double";
lastDoubleClick = {time: now, pos: start};
} else {
type = "single";
lastClick = {time: now, pos: start};
}
var sel = cm.doc.sel, addNew = mac ? e.metaKey : e.ctrlKey;
if (cm.options.dragDrop && dragAndDrop && !addNew && !isReadOnly(cm) &&
type == "single" && sel.contains(start) > -1 && sel.somethingSelected())
leftButtonStartDrag(cm, e, start);
else
leftButtonSelect(cm, e, start, type, addNew);
}
// Start a text drag. When it ends, see if any dragging actually
// happen, and treat as a click if it didn't.
function leftButtonStartDrag(cm, e, start) {
var display = cm.display;
var dragEnd = operation(cm, function(e2) {
if (webkit) display.scroller.draggable = false;
cm.state.draggingText = false;
off(document, "mouseup", dragEnd);
off(display.scroller, "drop", dragEnd);
if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
e_preventDefault(e2);
extendSelection(cm.doc, start);
focusInput(cm);
// Work around unexplainable focus problem in IE9 (#2127)
if (ie_upto10 && !ie_upto8)
setTimeout(function() {document.body.focus(); focusInput(cm);}, 20);
}
});
// Let the drag handler handle this.
if (webkit) display.scroller.draggable = true;
cm.state.draggingText = dragEnd;
// IE's approach to draggable
if (display.scroller.dragDrop) display.scroller.dragDrop();
on(document, "mouseup", dragEnd);
on(display.scroller, "drop", dragEnd);
}
// Normal selection, as opposed to text dragging.
function leftButtonSelect(cm, e, start, type, addNew) {
var display = cm.display, doc = cm.doc;
e_preventDefault(e);
var ourRange, ourIndex, startSel = doc.sel;
if (addNew && !e.shiftKey) {
ourIndex = doc.sel.contains(start);
if (ourIndex > -1)
ourRange = doc.sel.ranges[ourIndex];
else
ourRange = new Range(start, start);
} else {
ourRange = doc.sel.primary();
}
if (e.altKey) {
type = "rect";
if (!addNew) ourRange = new Range(start, start);
start = posFromMouse(cm, e, true, true);
ourIndex = -1;
} else if (type == "double") {
var word = findWordAt(cm, start);
if (cm.display.shift || doc.extend)
ourRange = extendRange(doc, ourRange, word.anchor, word.head);
else
ourRange = word;
} else if (type == "triple") {
var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
if (cm.display.shift || doc.extend)
ourRange = extendRange(doc, ourRange, line.anchor, line.head);
else
ourRange = line;
} else {
ourRange = extendRange(doc, ourRange, start);
}
if (!addNew) {
ourIndex = 0;
setSelection(doc, new Selection([ourRange], 0), sel_mouse);
startSel = doc.sel;
} else if (ourIndex > -1) {
replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
} else {
ourIndex = doc.sel.ranges.length;
setSelection(doc, normalizeSelection(doc.sel.ranges.concat([ourRange]), ourIndex),
{scroll: false, origin: "*mouse"});
}
var lastPos = start;
function extendTo(pos) {
if (cmp(lastPos, pos) == 0) return;
lastPos = pos;
if (type == "rect") {
var ranges = [], tabSize = cm.options.tabSize;
var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
line <= end; line++) {
var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
if (left == right)
ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
else if (text.length > leftPos)
ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
}
if (!ranges.length) ranges.push(new Range(start, start));
setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
{origin: "*mouse", scroll: false});
cm.scrollIntoView(pos);
} else {
var oldRange = ourRange;
var anchor = oldRange.anchor, head = pos;
if (type != "single") {
if (type == "double")
var range = findWordAt(cm, pos);
else
var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
if (cmp(range.anchor, anchor) > 0) {
head = range.head;
anchor = minPos(oldRange.from(), range.anchor);
} else {
head = range.anchor;
anchor = maxPos(oldRange.to(), range.head);
}
}
var ranges = startSel.ranges.slice(0);
ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
}
}
var editorSize = display.wrapper.getBoundingClientRect();
// Used to ensure timeout re-tries don't fire when another extend
// happened in the meantime (clearTimeout isn't reliable -- at
// least on Chrome, the timeouts still happen even when cleared,
// if the clear happens after their scheduled firing time).
var counter = 0;
function extend(e) {
var curCount = ++counter;
var cur = posFromMouse(cm, e, true, type == "rect");
if (!cur) return;
if (cmp(cur, lastPos) != 0) {
ensureFocus(cm);
extendTo(cur);
var visible = visibleLines(display, doc);
if (cur.line >= visible.to || cur.line < visible.from)
setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
} else {
var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
if (outside) setTimeout(operation(cm, function() {
if (counter != curCount) return;
display.scroller.scrollTop += outside;
extend(e);
}), 50);
}
}
function done(e) {
counter = Infinity;
e_preventDefault(e);
focusInput(cm);
off(document, "mousemove", move);
off(document, "mouseup", up);
doc.history.lastSelOrigin = null;
}
var move = operation(cm, function(e) {
if ((ie && !ie_upto9) ? !e.buttons : !e_button(e)) done(e);
else extend(e);
});
var up = operation(cm, done);
on(document, "mousemove", move);
on(document, "mouseup", up);
}
// Determines whether an event happened in the gutter, and fires the
// handlers for the corresponding event.
function gutterEvent(cm, e, type, prevent, signalfn) {
try { var mX = e.clientX, mY = e.clientY; }
catch(e) { return false; }
if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
if (prevent) e_preventDefault(e);
var display = cm.display;
var lineBox = display.lineDiv.getBoundingClientRect();
if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
mY -= lineBox.top - display.viewOffset;
for (var i = 0; i < cm.options.gutters.length; ++i) {
var g = display.gutters.childNodes[i];
if (g && g.getBoundingClientRect().right >= mX) {
var line = lineAtHeight(cm.doc, mY);
var gutter = cm.options.gutters[i];
signalfn(cm, type, cm, line, gutter, e);
return e_defaultPrevented(e);
}
}
}
function clickInGutter(cm, e) {
return gutterEvent(cm, e, "gutterClick", true, signalLater);
}
// Kludge to work around strange IE behavior where it'll sometimes
// re-fire a series of drag-related events right after the drop (#1551)
var lastDrop = 0;
function onDrop(e) {
var cm = this;
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
return;
e_preventDefault(e);
if (ie) lastDrop = +new Date;
var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
if (!pos || isReadOnly(cm)) return;
// Might be a file drop, in which case we simply extract the text
// and insert it.
if (files && files.length && window.FileReader && window.File) {
var n = files.length, text = Array(n), read = 0;
var loadFile = function(file, i) {
var reader = new FileReader;
reader.onload = operation(cm, function() {
text[i] = reader.result;
if (++read == n) {
pos = clipPos(cm.doc, pos);
var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
makeChange(cm.doc, change);
setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
}
});
reader.readAsText(file);
};
for (var i = 0; i < n; ++i) loadFile(files[i], i);
} else { // Normal drop
// Don't do a replace if the drop happened inside of the selected text.
if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
cm.state.draggingText(e);
// Ensure the editor is re-focused
setTimeout(bind(focusInput, cm), 20);
return;
}
try {
var text = e.dataTransfer.getData("Text");
if (text) {
var selected = cm.state.draggingText && cm.listSelections();
setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
if (selected) for (var i = 0; i < selected.length; ++i)
replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
cm.replaceSelection(text, "around", "paste");
focusInput(cm);
}
}
catch(e){}
}
}
function onDragStart(cm, e) {
if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
e.dataTransfer.setData("Text", cm.getSelection());
// Use dummy image instead of default browsers image.
// Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
if (e.dataTransfer.setDragImage && !safari) {
var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
if (presto) {
img.width = img.height = 1;
cm.display.wrapper.appendChild(img);
// Force a relayout, or Opera won't use our image for some obscure reason
img._top = img.offsetTop;
}
e.dataTransfer.setDragImage(img, 0, 0);
if (presto) img.parentNode.removeChild(img);
}
}
// SCROLL EVENTS
// Sync the scrollable area and scrollbars, ensure the viewport
// covers the visible area.
function setScrollTop(cm, val) {
if (Math.abs(cm.doc.scrollTop - val) < 2) return;
cm.doc.scrollTop = val;
if (!gecko) updateDisplay(cm, {top: val});
if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
if (gecko) updateDisplay(cm);
startWorker(cm, 100);
}
// Sync scroller and scrollbar, ensure the gutter elements are
// aligned.
function setScrollLeft(cm, val, isScroller) {
if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
cm.doc.scrollLeft = val;
alignHorizontally(cm);
if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
}
// Since the delta values reported on mouse wheel events are
// unstandardized between browsers and even browser versions, and
// generally horribly unpredictable, this code starts by measuring
// the scroll effect that the first few mouse wheel events have,
// and, from that, detects the way it can convert deltas to pixel
// offsets afterwards.
//
// The reason we want to know the amount a wheel event will scroll
// is that it gives us a chance to update the display before the
// actual scrolling happens, reducing flickering.
var wheelSamples = 0, wheelPixelsPerUnit = null;
// Fill in a browser-detected starting value on browsers where we
// know one. These don't have to be accurate -- the result of them
// being wrong would just be a slight flicker on the first wheel
// scroll (if it is large enough).
if (ie) wheelPixelsPerUnit = -.53;
else if (gecko) wheelPixelsPerUnit = 15;
else if (chrome) wheelPixelsPerUnit = -.7;
else if (safari) wheelPixelsPerUnit = -1/3;
function onScrollWheel(cm, e) {
var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
else if (dy == null) dy = e.wheelDelta;
var display = cm.display, scroll = display.scroller;
// Quit if there's nothing to scroll here
if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
dy && scroll.scrollHeight > scroll.clientHeight)) return;
// Webkit browsers on OS X abort momentum scrolls when the target
// of the scroll event is removed from the scrollable element.
// This hack (see related code in patchDisplay) makes sure the
// element is kept around.
if (dy && mac && webkit) {
outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
for (var i = 0; i < view.length; i++) {
if (view[i].node == cur) {
cm.display.currentWheelTarget = cur;
break outer;
}
}
}
}
// On some browsers, horizontal scrolling will cause redraws to
// happen before the gutter has been realigned, causing it to
// wriggle around in a most unseemly way. When we have an
// estimated pixels/delta value, we just handle horizontal
// scrolling entirely here. It'll be slightly off from native, but
// better than glitching out.
if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
if (dy)
setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
e_preventDefault(e);
display.wheelStartX = null; // Abort measurement, if in progress
return;
}
// 'Project' the visible viewport to cover the area that is being
// scrolled into view (if we know enough to estimate it).
if (dy && wheelPixelsPerUnit != null) {
var pixels = dy * wheelPixelsPerUnit;
var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
if (pixels < 0) top = Math.max(0, top + pixels - 50);
else bot = Math.min(cm.doc.height, bot + pixels + 50);
updateDisplay(cm, {top: top, bottom: bot});
}
if (wheelSamples < 20) {
if (display.wheelStartX == null) {
display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
display.wheelDX = dx; display.wheelDY = dy;
setTimeout(function() {
if (display.wheelStartX == null) return;
var movedX = scroll.scrollLeft - display.wheelStartX;
var movedY = scroll.scrollTop - display.wheelStartY;
var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
(movedX && display.wheelDX && movedX / display.wheelDX);
display.wheelStartX = display.wheelStartY = null;
if (!sample) return;
wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
++wheelSamples;
}, 200);
} else {
display.wheelDX += dx; display.wheelDY += dy;
}
}
}
// KEY EVENTS
// Run a handler that was bound to a key.
function doHandleBinding(cm, bound, dropShift) {
if (typeof bound == "string") {
bound = commands[bound];
if (!bound) return false;
}
// Ensure previous input has been read, so that the handler sees a
// consistent view of the document
if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
var prevShift = cm.display.shift, done = false;
try {
if (isReadOnly(cm)) cm.state.suppressEdits = true;
if (dropShift) cm.display.shift = false;
done = bound(cm) != Pass;
} finally {
cm.display.shift = prevShift;
cm.state.suppressEdits = false;
}
return done;
}
// Collect the currently active keymaps.
function allKeyMaps(cm) {
var maps = cm.state.keyMaps.slice(0);
if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
maps.push(cm.options.keyMap);
return maps;
}
var maybeTransition;
// Handle a key from the keydown event.
function handleKeyBinding(cm, e) {
// Handle automatic keymap transitions
var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
clearTimeout(maybeTransition);
if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
if (getKeyMap(cm.options.keyMap) == startMap) {
cm.options.keyMap = (next.call ? next.call(null, cm) : next);
keyMapChanged(cm);
}
}, 50);
var name = keyName(e, true), handled = false;
if (!name) return false;
var keymaps = allKeyMaps(cm);
if (e.shiftKey) {
// First try to resolve full name (including 'Shift-'). Failing
// that, see if there is a cursor-motion command (starting with
// 'go') bound to the keyname without 'Shift-'.
handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
|| lookupKey(name, keymaps, function(b) {
if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
return doHandleBinding(cm, b);
});
} else {
handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
}
if (handled) {
e_preventDefault(e);
restartBlink(cm);
signalLater(cm, "keyHandled", cm, name, e);
}
return handled;
}
// Handle a key from the keypress event
function handleCharBinding(cm, e, ch) {
var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
function(b) { return doHandleBinding(cm, b, true); });
if (handled) {
e_preventDefault(e);
restartBlink(cm);
signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
}
return handled;
}
var lastStoppedKey = null;
function onKeyDown(e) {
var cm = this;
ensureFocus(cm);
if (signalDOMEvent(cm, e)) return;
// IE does strange things with escape.
if (ie_upto10 && e.keyCode == 27) e.returnValue = false;
var code = e.keyCode;
cm.display.shift = code == 16 || e.shiftKey;
var handled = handleKeyBinding(cm, e);
if (presto) {
lastStoppedKey = handled ? code : null;
// Opera has no cut event... we try to at least catch the key combo
if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
cm.replaceSelection("", null, "cut");
}
// Turn mouse into crosshair when Alt is held on Mac.
if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
showCrossHair(cm);
}
function showCrossHair(cm) {
var lineDiv = cm.display.lineDiv;
addClass(lineDiv, "CodeMirror-crosshair");
function up(e) {
if (e.keyCode == 18 || !e.altKey) {
rmClass(lineDiv, "CodeMirror-crosshair");
off(document, "keyup", up);
off(document, "mouseover", up);
}
}
on(document, "keyup", up);
on(document, "mouseover", up);
}
function onKeyUp(e) {
if (signalDOMEvent(this, e)) return;
if (e.keyCode == 16) this.doc.sel.shift = false;
}
function onKeyPress(e) {
var cm = this;
if (signalDOMEvent(cm, e)) return;
var keyCode = e.keyCode, charCode = e.charCode;
if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
if (handleCharBinding(cm, e, ch)) return;
if (ie && !ie_upto8) cm.display.inputHasSelection = null;
fastPoll(cm);
}
// FOCUS/BLUR EVENTS
function onFocus(cm) {
if (cm.options.readOnly == "nocursor") return;
if (!cm.state.focused) {
signal(cm, "focus", cm);
cm.state.focused = true;
addClass(cm.display.wrapper, "CodeMirror-focused");
// The prevInput test prevents this from firing when a context
// menu is closed (since the resetInput would kill the
// select-all detection hack)
if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
resetInput(cm);
if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730
}
}
slowPoll(cm);
restartBlink(cm);
}
function onBlur(cm) {
if (cm.state.focused) {
signal(cm, "blur", cm);
cm.state.focused = false;
rmClass(cm.display.wrapper, "CodeMirror-focused");
}
clearInterval(cm.display.blinker);
setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
}
// CONTEXT MENU HANDLING
// To make the context menu work, we need to briefly unhide the
// textarea (making it as unobtrusive as possible) to let the
// right-click take effect on it.
function onContextMenu(cm, e) {
if (signalDOMEvent(cm, e, "contextmenu")) return;
var display = cm.display;
if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;
var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
if (!pos || presto) return; // Opera is difficult.
// Reset the current text selection only if the click is done outside of the selection
// and 'resetSelectionOnContextMenu' option is true.
var reset = cm.options.resetSelectionOnContextMenu;
if (reset && cm.doc.sel.contains(pos) == -1)
operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
var oldCSS = display.input.style.cssText;
display.inputDiv.style.position = "absolute";
display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
"px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
(ie ? "rgba(255, 255, 255, .05)" : "transparent") +
"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
focusInput(cm);
resetInput(cm);
// Adds "Select all" to context menu in FF
if (!cm.somethingSelected()) display.input.value = display.prevInput = " ";
display.selForContextMenu = cm.doc.sel;
clearTimeout(display.detectingSelectAll);
// Select-all will be greyed out if there's nothing to select, so
// this adds a zero-width space so that we can later check whether
// it got selected.
function prepareSelectAllHack() {
if (display.input.selectionStart != null) {
var selected = cm.somethingSelected();
var extval = display.input.value = "\u200b" + (selected ? display.input.value : "");
display.prevInput = selected ? "" : "\u200b";
display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
}
}
function rehide() {
display.inputDiv.style.position = "relative";
display.input.style.cssText = oldCSS;
if (ie_upto8) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
slowPoll(cm);
// Try to detect the user choosing select-all
if (display.input.selectionStart != null) {
if (!ie || ie_upto8) prepareSelectAllHack();
var i = 0, poll = function() {
if (display.selForContextMenu == cm.doc.sel && display.input.selectionStart == 0)
operation(cm, commands.selectAll)(cm);
else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
else resetInput(cm);
};
display.detectingSelectAll = setTimeout(poll, 200);
}
}
if (ie && !ie_upto8) prepareSelectAllHack();
if (captureRightClick) {
e_stop(e);
var mouseup = function() {
off(window, "mouseup", mouseup);
setTimeout(rehide, 20);
};
on(window, "mouseup", mouseup);
} else {
setTimeout(rehide, 50);
}
}
function contextMenuInGutter(cm, e) {
if (!hasHandler(cm, "gutterContextMenu")) return false;
return gutterEvent(cm, e, "gutterContextMenu", false, signal);
}
// UPDATING
// Compute the position of the end of a change (its 'to' property
// refers to the pre-change end).
var changeEnd = CodeMirror.changeEnd = function(change) {
if (!change.text) return change.to;
return Pos(change.from.line + change.text.length - 1,
lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
};
// Adjust a position to refer to the post-change position of the
// same text, or the end of the change if the change covers it.
function adjustForChange(pos, change) {
if (cmp(pos, change.from) < 0) return pos;
if (cmp(pos, change.to) <= 0) return changeEnd(change);
var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
return Pos(line, ch);
}
function computeSelAfterChange(doc, change) {
var out = [];
for (var i = 0; i < doc.sel.ranges.length; i++) {
var range = doc.sel.ranges[i];
out.push(new Range(adjustForChange(range.anchor, change),
adjustForChange(range.head, change)));
}
return normalizeSelection(out, doc.sel.primIndex);
}
function offsetPos(pos, old, nw) {
if (pos.line == old.line)
return Pos(nw.line, pos.ch - old.ch + nw.ch);
else
return Pos(nw.line + (pos.line - old.line), pos.ch);
}
// Used by replaceSelections to allow moving the selection to the
// start or around the replaced test. Hint may be "start" or "around".
function computeReplacedSel(doc, changes, hint) {
var out = [];
var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
var from = offsetPos(change.from, oldPrev, newPrev);
var to = offsetPos(changeEnd(change), oldPrev, newPrev);
oldPrev = change.to;
newPrev = to;
if (hint == "around") {
var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
out[i] = new Range(inv ? to : from, inv ? from : to);
} else {
out[i] = new Range(from, from);
}
}
return new Selection(out, doc.sel.primIndex);
}
// Allow "beforeChange" event handlers to influence a change
function filterChange(doc, change, update) {
var obj = {
canceled: false,
from: change.from,
to: change.to,
text: change.text,
origin: change.origin,
cancel: function() { this.canceled = true; }
};
if (update) obj.update = function(from, to, text, origin) {
if (from) this.from = clipPos(doc, from);
if (to) this.to = clipPos(doc, to);
if (text) this.text = text;
if (origin !== undefined) this.origin = origin;
};
signal(doc, "beforeChange", doc, obj);
if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
if (obj.canceled) return null;
return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
}
// Apply a change to a document, and add it to the document's
// history, and propagating it to all linked documents.
function makeChange(doc, change, ignoreReadOnly) {
if (doc.cm) {
if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
if (doc.cm.state.suppressEdits) return;
}
if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
change = filterChange(doc, change, true);
if (!change) return;
}
// Possibly split or suppress the update based on the presence
// of read-only spans in its range.
var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
if (split) {
for (var i = split.length - 1; i >= 0; --i)
makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
} else {
makeChangeInner(doc, change);
}
}
function makeChangeInner(doc, change) {
if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
var selAfter = computeSelAfterChange(doc, change);
addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
var rebased = [];
linkedDocs(doc, function(doc, sharedHist) {
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
rebaseHist(doc.history, change);
rebased.push(doc.history);
}
makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
});
}
// Revert a change stored in a document's history.
function makeChangeFromHistory(doc, type, allowSelectionOnly) {
if (doc.cm && doc.cm.state.suppressEdits) return;
var hist = doc.history, event, selAfter = doc.sel;
var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
// Verify that there is a useable event (so that ctrl-z won't
// needlessly clear selection events)
for (var i = 0; i < source.length; i++) {
event = source[i];
if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
break;
}
if (i == source.length) return;
hist.lastOrigin = hist.lastSelOrigin = null;
for (;;) {
event = source.pop();
if (event.ranges) {
pushSelectionToHistory(event, dest);
if (allowSelectionOnly && !event.equals(doc.sel)) {
setSelection(doc, event, {clearRedo: false});
return;
}
selAfter = event;
}
else break;
}
// Build up a reverse change object to add to the opposite history
// stack (redo when undoing, and vice versa).
var antiChanges = [];
pushSelectionToHistory(selAfter, dest);
dest.push({changes: antiChanges, generation: hist.generation});
hist.generation = event.generation || ++hist.maxGeneration;
var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
for (var i = event.changes.length - 1; i >= 0; --i) {
var change = event.changes[i];
change.origin = type;
if (filter && !filterChange(doc, change, false)) {
source.length = 0;
return;
}
antiChanges.push(historyChangeFromChange(doc, change));
var after = i ? computeSelAfterChange(doc, change, null) : lst(source);
makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
if (!i && doc.cm) doc.cm.scrollIntoView(change);
var rebased = [];
// Propagate to the linked documents
linkedDocs(doc, function(doc, sharedHist) {
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
rebaseHist(doc.history, change);
rebased.push(doc.history);
}
makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
});
}
}
// Sub-views need their line numbers shifted when text is added
// above or below them in the parent document.
function shiftDoc(doc, distance) {
if (distance == 0) return;
doc.first += distance;
doc.sel = new Selection(map(doc.sel.ranges, function(range) {
return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
Pos(range.head.line + distance, range.head.ch));
}), doc.sel.primIndex);
if (doc.cm) {
regChange(doc.cm, doc.first, doc.first - distance, distance);
for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
regLineChange(doc.cm, l, "gutter");
}
}
// More lower-level change function, handling only a single document
// (not linked ones).
function makeChangeSingleDoc(doc, change, selAfter, spans) {
if (doc.cm && !doc.cm.curOp)
return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
if (change.to.line < doc.first) {
shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
return;
}
if (change.from.line > doc.lastLine()) return;
// Clip the change to the size of this doc
if (change.from.line < doc.first) {
var shift = change.text.length - 1 - (doc.first - change.from.line);
shiftDoc(doc, shift);
change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
text: [lst(change.text)], origin: change.origin};
}
var last = doc.lastLine();
if (change.to.line > last) {
change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
text: [change.text[0]], origin: change.origin};
}
change.removed = getBetween(doc, change.from, change.to);
if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
else updateDoc(doc, change, spans);
setSelectionNoUndo(doc, selAfter, sel_dontScroll);
}
// Handle the interaction of a change to a document with the editor
// that this document is part of.
function makeChangeSingleDocInEditor(cm, change, spans) {
var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
var recomputeMaxLength = false, checkWidthStart = from.line;
if (!cm.options.lineWrapping) {
checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
doc.iter(checkWidthStart, to.line + 1, function(line) {
if (line == display.maxLine) {
recomputeMaxLength = true;
return true;
}
});
}
if (doc.sel.contains(change.from, change.to) > -1)
signalCursorActivity(cm);
updateDoc(doc, change, spans, estimateHeight(cm));
if (!cm.options.lineWrapping) {
doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
var len = lineLength(line);
if (len > display.maxLineLength) {
display.maxLine = line;
display.maxLineLength = len;
display.maxLineChanged = true;
recomputeMaxLength = false;
}
});
if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
}
// Adjust frontier, schedule worker
doc.frontier = Math.min(doc.frontier, from.line);
startWorker(cm, 400);
var lendiff = change.text.length - (to.line - from.line) - 1;
// Remember that these lines changed, for updating the display
if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
regLineChange(cm, from.line, "text");
else
regChange(cm, from.line, to.line + 1, lendiff);
var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
if (changeHandler || changesHandler) {
var obj = {
from: from, to: to,
text: change.text,
removed: change.removed,
origin: change.origin
};
if (changeHandler) signalLater(cm, "change", cm, obj);
if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
}
cm.display.selForContextMenu = null;
}
function replaceRange(doc, code, from, to, origin) {
if (!to) to = from;
if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
if (typeof code == "string") code = splitLines(code);
makeChange(doc, {from: from, to: to, text: code, origin: origin});
}
// SCROLLING THINGS INTO VIEW
// If an editor sits on the top or bottom of the window, partially
// scrolled out of view, this ensures that the cursor is visible.
function maybeScrollWindow(cm, coords) {
var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
if (coords.top + box.top < 0) doScroll = true;
else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
if (doScroll != null && !phantom) {
var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
(coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
(coords.bottom - coords.top + scrollerCutOff) + "px; left: " +
coords.left + "px; width: 2px;");
cm.display.lineSpace.appendChild(scrollNode);
scrollNode.scrollIntoView(doScroll);
cm.display.lineSpace.removeChild(scrollNode);
}
}
// Scroll a given position into view (immediately), verifying that
// it actually became visible (as line heights are accurately
// measured, the position of something may 'drift' during drawing).
function scrollPosIntoView(cm, pos, end, margin) {
if (margin == null) margin = 0;
for (;;) {
var changed = false, coords = cursorCoords(cm, pos);
var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
Math.min(coords.top, endCoords.top) - margin,
Math.max(coords.left, endCoords.left),
Math.max(coords.bottom, endCoords.bottom) + margin);
var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
if (scrollPos.scrollTop != null) {
setScrollTop(cm, scrollPos.scrollTop);
if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
}
if (scrollPos.scrollLeft != null) {
setScrollLeft(cm, scrollPos.scrollLeft);
if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
}
if (!changed) return coords;
}
}
// Scroll a given set of coordinates into view (immediately).
function scrollIntoView(cm, x1, y1, x2, y2) {
var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
}
// Calculate a new scroll position needed to scroll the given
// rectangle into view. Returns an object with scrollTop and
// scrollLeft properties. When these are undefined, the
// vertical/horizontal position does not need to be adjusted.
function calculateScrollPos(cm, x1, y1, x2, y2) {
var display = cm.display, snapMargin = textHeight(cm.display);
if (y1 < 0) y1 = 0;
var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
var screen = display.scroller.clientHeight - scrollerCutOff, result = {};
var docBottom = cm.doc.height + paddingVert(display);
var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
if (y1 < screentop) {
result.scrollTop = atTop ? 0 : y1;
} else if (y2 > screentop + screen) {
var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
if (newTop != screentop) result.scrollTop = newTop;
}
var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
var screenw = display.scroller.clientWidth - scrollerCutOff;
x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
var gutterw = display.gutters.offsetWidth;
var atLeft = x1 < gutterw + 10;
if (x1 < screenleft + gutterw || atLeft) {
if (atLeft) x1 = 0;
result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
} else if (x2 > screenw + screenleft - 3) {
result.scrollLeft = x2 + 10 - screenw;
}
return result;
}
// Store a relative adjustment to the scroll position in the current
// operation (to be applied when the operation finishes).
function addToScrollPos(cm, left, top) {
if (left != null || top != null) resolveScrollToPos(cm);
if (left != null)
cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
if (top != null)
cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
}
// Make sure that at the end of the operation the current cursor is
// shown.
function ensureCursorVisible(cm) {
resolveScrollToPos(cm);
var cur = cm.getCursor(), from = cur, to = cur;
if (!cm.options.lineWrapping) {
from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
to = Pos(cur.line, cur.ch + 1);
}
cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
}
// When an operation has its scrollToPos property set, and another
// scroll action is applied before the end of the operation, this
// 'simulates' scrolling that position into view in a cheap way, so
// that the effect of intermediate scroll commands is not ignored.
function resolveScrollToPos(cm) {
var range = cm.curOp.scrollToPos;
if (range) {
cm.curOp.scrollToPos = null;
var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
Math.min(from.top, to.top) - range.margin,
Math.max(from.right, to.right),
Math.max(from.bottom, to.bottom) + range.margin);
cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
}
}
// API UTILITIES
// Indent the given line. The how parameter can be "smart",
// "add"/null, "subtract", or "prev". When aggressive is false
// (typically set to true for forced single-line indents), empty
// lines are not indented, and places where the mode returns Pass
// are left alone.
function indentLine(cm, n, how, aggressive) {
var doc = cm.doc, state;
if (how == null) how = "add";
if (how == "smart") {
// Fall back to "prev" when the mode doesn't have an indentation
// method.
if (!cm.doc.mode.indent) how = "prev";
else state = getStateBefore(cm, n);
}
var tabSize = cm.options.tabSize;
var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
if (line.stateAfter) line.stateAfter = null;
var curSpaceString = line.text.match(/^\s*/)[0], indentation;
if (!aggressive && !/\S/.test(line.text)) {
indentation = 0;
how = "not";
} else if (how == "smart") {
indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
if (indentation == Pass) {
if (!aggressive) return;
how = "prev";
}
}
if (how == "prev") {
if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
else indentation = 0;
} else if (how == "add") {
indentation = curSpace + cm.options.indentUnit;
} else if (how == "subtract") {
indentation = curSpace - cm.options.indentUnit;
} else if (typeof how == "number") {
indentation = curSpace + how;
}
indentation = Math.max(0, indentation);
var indentString = "", pos = 0;
if (cm.options.indentWithTabs)
for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
if (pos < indentation) indentString += spaceStr(indentation - pos);
if (indentString != curSpaceString) {
replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
} else {
// Ensure that, if the cursor was in the whitespace at the start
// of the line, it is moved to the end of that space.
for (var i = 0; i < doc.sel.ranges.length; i++) {
var range = doc.sel.ranges[i];
if (range.head.line == n && range.head.ch < curSpaceString.length) {
var pos = Pos(n, curSpaceString.length);
replaceOneSelection(doc, i, new Range(pos, pos));
break;
}
}
}
line.stateAfter = null;
}
// Utility for applying a change to a line by handle or number,
// returning the number and optionally registering the line as
// changed.
function changeLine(cm, handle, changeType, op) {
var no = handle, line = handle, doc = cm.doc;
if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
else no = lineNo(handle);
if (no == null) return null;
if (op(line, no)) regLineChange(cm, no, changeType);
return line;
}
// Helper for deleting text near the selection(s), used to implement
// backspace, delete, and similar functionality.
function deleteNearSelection(cm, compute) {
var ranges = cm.doc.sel.ranges, kill = [];
// Build up a set of ranges to kill first, merging overlapping
// ranges.
for (var i = 0; i < ranges.length; i++) {
var toKill = compute(ranges[i]);
while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
var replaced = kill.pop();
if (cmp(replaced.from, toKill.from) < 0) {
toKill.from = replaced.from;
break;
}
}
kill.push(toKill);
}
// Next, remove those actual ranges.
runInOp(cm, function() {
for (var i = kill.length - 1; i >= 0; i--)
replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
ensureCursorVisible(cm);
});
}
// Used for horizontal relative motion. Dir is -1 or 1 (left or
// right), unit can be "char", "column" (like char, but doesn't
// cross line boundaries), "word" (across next word), or "group" (to
// the start of next group of word or non-word-non-whitespace
// chars). The visually param controls whether, in right-to-left
// text, direction 1 means to move towards the next index in the
// string, or towards the character to the right of the current
// position. The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosH(doc, pos, dir, unit, visually) {
var line = pos.line, ch = pos.ch, origDir = dir;
var lineObj = getLine(doc, line);
var possible = true;
function findNextLine() {
var l = line + dir;
if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
line = l;
return lineObj = getLine(doc, l);
}
function moveOnce(boundToLine) {
var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
if (next == null) {
if (!boundToLine && findNextLine()) {
if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
else ch = dir < 0 ? lineObj.text.length : 0;
} else return (possible = false);
} else ch = next;
return true;
}
if (unit == "char") moveOnce();
else if (unit == "column") moveOnce(true);
else if (unit == "word" || unit == "group") {
var sawType = null, group = unit == "group";
var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
for (var first = true;; first = false) {
if (dir < 0 && !moveOnce(!first)) break;
var cur = lineObj.text.charAt(ch) || "\n";
var type = isWordChar(cur, helper) ? "w"
: group && cur == "\n" ? "n"
: !group || /\s/.test(cur) ? null
: "p";
if (group && !first && !type) type = "s";
if (sawType && sawType != type) {
if (dir < 0) {dir = 1; moveOnce();}
break;
}
if (type) sawType = type;
if (dir > 0 && !moveOnce(!first)) break;
}
}
var result = skipAtomic(doc, Pos(line, ch), origDir, true);
if (!possible) result.hitSide = true;
return result;
}
// For relative vertical movement. Dir may be -1 or 1. Unit can be
// "page" or "line". The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosV(cm, pos, dir, unit) {
var doc = cm.doc, x = pos.left, y;
if (unit == "page") {
var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
} else if (unit == "line") {
y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
}
for (;;) {
var target = coordsChar(cm, x, y);
if (!target.outside) break;
if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
y += dir * 5;
}
return target;
}
// Find the word at the given position (as returned by coordsChar).
function findWordAt(cm, pos) {
var doc = cm.doc, line = getLine(doc, pos.line).text;
var start = pos.ch, end = pos.ch;
if (line) {
var helper = cm.getHelper(pos, "wordChars");
if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
var startChar = line.charAt(start);
var check = isWordChar(startChar, helper)
? function(ch) { return isWordChar(ch, helper); }
: /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
: function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
while (start > 0 && check(line.charAt(start - 1))) --start;
while (end < line.length && check(line.charAt(end))) ++end;
}
return new Range(Pos(pos.line, start), Pos(pos.line, end));
}
// EDITOR METHODS
// The publicly visible API. Note that methodOp(f) means
// 'wrap f in an operation, performed on its `this` parameter'.
// This is not the complete set of editor methods. Most of the
// methods defined on the Doc type are also injected into
// CodeMirror.prototype, for backwards compatibility and
// convenience.
CodeMirror.prototype = {
constructor: CodeMirror,
focus: function(){window.focus(); focusInput(this); fastPoll(this);},
setOption: function(option, value) {
var options = this.options, old = options[option];
if (options[option] == value && option != "mode") return;
options[option] = value;
if (optionHandlers.hasOwnProperty(option))
operation(this, optionHandlers[option])(this, value, old);
},
getOption: function(option) {return this.options[option];},
getDoc: function() {return this.doc;},
addKeyMap: function(map, bottom) {
this.state.keyMaps[bottom ? "push" : "unshift"](map);
},
removeKeyMap: function(map) {
var maps = this.state.keyMaps;
for (var i = 0; i < maps.length; ++i)
if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
maps.splice(i, 1);
return true;
}
},
addOverlay: methodOp(function(spec, options) {
var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
if (mode.startState) throw new Error("Overlays may not be stateful.");
this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
this.state.modeGen++;
regChange(this);
}),
removeOverlay: methodOp(function(spec) {
var overlays = this.state.overlays;
for (var i = 0; i < overlays.length; ++i) {
var cur = overlays[i].modeSpec;
if (cur == spec || typeof spec == "string" && cur.name == spec) {
overlays.splice(i, 1);
this.state.modeGen++;
regChange(this);
return;
}
}
}),
indentLine: methodOp(function(n, dir, aggressive) {
if (typeof dir != "string" && typeof dir != "number") {
if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
else dir = dir ? "add" : "subtract";
}
if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
}),
indentSelection: methodOp(function(how) {
var ranges = this.doc.sel.ranges, end = -1;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (!range.empty()) {
var start = Math.max(end, range.from().line);
var to = range.to();
end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
for (var j = start; j < end; ++j)
indentLine(this, j, how);
} else if (range.head.line > end) {
indentLine(this, range.head.line, how, true);
end = range.head.line;
if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
}
}
}),
// Fetch the parser token for a given character. Useful for hacks
// that want to inspect the mode state (say, for completion).
getTokenAt: function(pos, precise) {
var doc = this.doc;
pos = clipPos(doc, pos);
var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
var line = getLine(doc, pos.line);
var stream = new StringStream(line.text, this.options.tabSize);
while (stream.pos < pos.ch && !stream.eol()) {
stream.start = stream.pos;
var style = readToken(mode, stream, state);
}
return {start: stream.start,
end: stream.pos,
string: stream.current(),
type: style || null,
state: state};
},
getTokenTypeAt: function(pos) {
pos = clipPos(this.doc, pos);
var styles = getLineStyles(this, getLine(this.doc, pos.line));
var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
var type;
if (ch == 0) type = styles[2];
else for (;;) {
var mid = (before + after) >> 1;
if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
else if (styles[mid * 2 + 1] < ch) before = mid + 1;
else { type = styles[mid * 2 + 2]; break; }
}
var cut = type ? type.indexOf("cm-overlay ") : -1;
return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
},
getModeAt: function(pos) {
var mode = this.doc.mode;
if (!mode.innerMode) return mode;
return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
},
getHelper: function(pos, type) {
return this.getHelpers(pos, type)[0];
},
getHelpers: function(pos, type) {
var found = [];
if (!helpers.hasOwnProperty(type)) return helpers;
var help = helpers[type], mode = this.getModeAt(pos);
if (typeof mode[type] == "string") {
if (help[mode[type]]) found.push(help[mode[type]]);
} else if (mode[type]) {
for (var i = 0; i < mode[type].length; i++) {
var val = help[mode[type][i]];
if (val) found.push(val);
}
} else if (mode.helperType && help[mode.helperType]) {
found.push(help[mode.helperType]);
} else if (help[mode.name]) {
found.push(help[mode.name]);
}
for (var i = 0; i < help._global.length; i++) {
var cur = help._global[i];
if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
found.push(cur.val);
}
return found;
},
getStateAfter: function(line, precise) {
var doc = this.doc;
line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
return getStateBefore(this, line + 1, precise);
},
cursorCoords: function(start, mode) {
var pos, range = this.doc.sel.primary();
if (start == null) pos = range.head;
else if (typeof start == "object") pos = clipPos(this.doc, start);
else pos = start ? range.from() : range.to();
return cursorCoords(this, pos, mode || "page");
},
charCoords: function(pos, mode) {
return charCoords(this, clipPos(this.doc, pos), mode || "page");
},
coordsChar: function(coords, mode) {
coords = fromCoordSystem(this, coords, mode || "page");
return coordsChar(this, coords.left, coords.top);
},
lineAtHeight: function(height, mode) {
height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
return lineAtHeight(this.doc, height + this.display.viewOffset);
},
heightAtLine: function(line, mode) {
var end = false, last = this.doc.first + this.doc.size - 1;
if (line < this.doc.first) line = this.doc.first;
else if (line > last) { line = last; end = true; }
var lineObj = getLine(this.doc, line);
return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
(end ? this.doc.height - heightAtLine(lineObj) : 0);
},
defaultTextHeight: function() { return textHeight(this.display); },
defaultCharWidth: function() { return charWidth(this.display); },
setGutterMarker: methodOp(function(line, gutterID, value) {
return changeLine(this, line, "gutter", function(line) {
var markers = line.gutterMarkers || (line.gutterMarkers = {});
markers[gutterID] = value;
if (!value && isEmpty(markers)) line.gutterMarkers = null;
return true;
});
}),
clearGutter: methodOp(function(gutterID) {
var cm = this, doc = cm.doc, i = doc.first;
doc.iter(function(line) {
if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
line.gutterMarkers[gutterID] = null;
regLineChange(cm, i, "gutter");
if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
}
++i;
});
}),
addLineClass: methodOp(function(handle, where, cls) {
return changeLine(this, handle, "class", function(line) {
var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
if (!line[prop]) line[prop] = cls;
else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
else line[prop] += " " + cls;
return true;
});
}),
removeLineClass: methodOp(function(handle, where, cls) {
return changeLine(this, handle, "class", function(line) {
var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
var cur = line[prop];
if (!cur) return false;
else if (cls == null) line[prop] = null;
else {
var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
if (!found) return false;
var end = found.index + found[0].length;
line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
}
return true;
});
}),
addLineWidget: methodOp(function(handle, node, options) {
return addLineWidget(this, handle, node, options);
}),
removeLineWidget: function(widget) { widget.clear(); },
lineInfo: function(line) {
if (typeof line == "number") {
if (!isLine(this.doc, line)) return null;
var n = line;
line = getLine(this.doc, line);
if (!line) return null;
} else {
var n = lineNo(line);
if (n == null) return null;
}
return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
widgets: line.widgets};
},
getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
addWidget: function(pos, node, scroll, vert, horiz) {
var display = this.display;
pos = cursorCoords(this, clipPos(this.doc, pos));
var top = pos.bottom, left = pos.left;
node.style.position = "absolute";
display.sizer.appendChild(node);
if (vert == "over") {
top = pos.top;
} else if (vert == "above" || vert == "near") {
var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
// Default to positioning above (if specified and possible); otherwise default to positioning below
if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
top = pos.top - node.offsetHeight;
else if (pos.bottom + node.offsetHeight <= vspace)
top = pos.bottom;
if (left + node.offsetWidth > hspace)
left = hspace - node.offsetWidth;
}
node.style.top = top + "px";
node.style.left = node.style.right = "";
if (horiz == "right") {
left = display.sizer.clientWidth - node.offsetWidth;
node.style.right = "0px";
} else {
if (horiz == "left") left = 0;
else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
node.style.left = left + "px";
}
if (scroll)
scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
},
triggerOnKeyDown: methodOp(onKeyDown),
triggerOnKeyPress: methodOp(onKeyPress),
triggerOnKeyUp: methodOp(onKeyUp),
execCommand: function(cmd) {
if (commands.hasOwnProperty(cmd))
return commands[cmd](this);
},
findPosH: function(from, amount, unit, visually) {
var dir = 1;
if (amount < 0) { dir = -1; amount = -amount; }
for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
cur = findPosH(this.doc, cur, dir, unit, visually);
if (cur.hitSide) break;
}
return cur;
},
moveH: methodOp(function(dir, unit) {
var cm = this;
cm.extendSelectionsBy(function(range) {
if (cm.display.shift || cm.doc.extend || range.empty())
return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
else
return dir < 0 ? range.from() : range.to();
}, sel_move);
}),
deleteH: methodOp(function(dir, unit) {
var sel = this.doc.sel, doc = this.doc;
if (sel.somethingSelected())
doc.replaceSelection("", null, "+delete");
else
deleteNearSelection(this, function(range) {
var other = findPosH(doc, range.head, dir, unit, false);
return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
});
}),
findPosV: function(from, amount, unit, goalColumn) {
var dir = 1, x = goalColumn;
if (amount < 0) { dir = -1; amount = -amount; }
for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
var coords = cursorCoords(this, cur, "div");
if (x == null) x = coords.left;
else coords.left = x;
cur = findPosV(this, coords, dir, unit);
if (cur.hitSide) break;
}
return cur;
},
moveV: methodOp(function(dir, unit) {
var cm = this, doc = this.doc, goals = [];
var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
doc.extendSelectionsBy(function(range) {
if (collapse)
return dir < 0 ? range.from() : range.to();
var headPos = cursorCoords(cm, range.head, "div");
if (range.goalColumn != null) headPos.left = range.goalColumn;
goals.push(headPos.left);
var pos = findPosV(cm, headPos, dir, unit);
if (unit == "page" && range == doc.sel.primary())
addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
return pos;
}, sel_move);
if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
doc.sel.ranges[i].goalColumn = goals[i];
}),
toggleOverwrite: function(value) {
if (value != null && value == this.state.overwrite) return;
if (this.state.overwrite = !this.state.overwrite)
addClass(this.display.cursorDiv, "CodeMirror-overwrite");
else
rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
signal(this, "overwriteToggle", this, this.state.overwrite);
},
hasFocus: function() { return activeElt() == this.display.input; },
scrollTo: methodOp(function(x, y) {
if (x != null || y != null) resolveScrollToPos(this);
if (x != null) this.curOp.scrollLeft = x;
if (y != null) this.curOp.scrollTop = y;
}),
getScrollInfo: function() {
var scroller = this.display.scroller, co = scrollerCutOff;
return {left: scroller.scrollLeft, top: scroller.scrollTop,
height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
},
scrollIntoView: methodOp(function(range, margin) {
if (range == null) {
range = {from: this.doc.sel.primary().head, to: null};
if (margin == null) margin = this.options.cursorScrollMargin;
} else if (typeof range == "number") {
range = {from: Pos(range, 0), to: null};
} else if (range.from == null) {
range = {from: range, to: null};
}
if (!range.to) range.to = range.from;
range.margin = margin || 0;
if (range.from.line != null) {
resolveScrollToPos(this);
this.curOp.scrollToPos = range;
} else {
var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
Math.min(range.from.top, range.to.top) - range.margin,
Math.max(range.from.right, range.to.right),
Math.max(range.from.bottom, range.to.bottom) + range.margin);
this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
}
}),
setSize: methodOp(function(width, height) {
function interpret(val) {
return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
}
if (width != null) this.display.wrapper.style.width = interpret(width);
if (height != null) this.display.wrapper.style.height = interpret(height);
if (this.options.lineWrapping) clearLineMeasurementCache(this);
this.curOp.forceUpdate = true;
signal(this, "refresh", this);
}),
operation: function(f){return runInOp(this, f);},
refresh: methodOp(function() {
var oldHeight = this.display.cachedTextHeight;
regChange(this);
this.curOp.forceUpdate = true;
clearCaches(this);
this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
updateGutterSpace(this);
if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
estimateLineHeights(this);
signal(this, "refresh", this);
}),
swapDoc: methodOp(function(doc) {
var old = this.doc;
old.cm = null;
attachDoc(this, doc);
clearCaches(this);
resetInput(this);
this.scrollTo(doc.scrollLeft, doc.scrollTop);
signalLater(this, "swapDoc", this, old);
return old;
}),
getInputField: function(){return this.display.input;},
getWrapperElement: function(){return this.display.wrapper;},
getScrollerElement: function(){return this.display.scroller;},
getGutterElement: function(){return this.display.gutters;}
};
eventMixin(CodeMirror);
// OPTION DEFAULTS
// The default configuration options.
var defaults = CodeMirror.defaults = {};
// Functions to run when options are changed.
var optionHandlers = CodeMirror.optionHandlers = {};
function option(name, deflt, handle, notOnInit) {
CodeMirror.defaults[name] = deflt;
if (handle) optionHandlers[name] =
notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
}
// Passed to option handlers when there is no old value.
var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
// These two are, on init, called from the constructor because they
// have to be initialized before the editor can start at all.
option("value", "", function(cm, val) {
cm.setValue(val);
}, true);
option("mode", null, function(cm, val) {
cm.doc.modeOption = val;
loadMode(cm);
}, true);
option("indentUnit", 2, loadMode, true);
option("indentWithTabs", false);
option("smartIndent", true);
option("tabSize", 4, function(cm) {
resetModeState(cm);
clearCaches(cm);
regChange(cm);
}, true);
option("specialChars", /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g, function(cm, val) {
cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
cm.refresh();
}, true);
option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
option("electricChars", true);
option("rtlMoveVisually", !windows);
option("wholeLineUpdateBefore", true);
option("theme", "default", function(cm) {
themeChanged(cm);
guttersChanged(cm);
}, true);
option("keyMap", "default", keyMapChanged);
option("extraKeys", null);
option("lineWrapping", false, wrappingChanged, true);
option("gutters", [], function(cm) {
setGuttersForLineNumbers(cm.options);
guttersChanged(cm);
}, true);
option("fixedGutter", true, function(cm, val) {
cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
cm.refresh();
}, true);
option("coverGutterNextToScrollbar", false, updateScrollbars, true);
option("lineNumbers", false, function(cm) {
setGuttersForLineNumbers(cm.options);
guttersChanged(cm);
}, true);
option("firstLineNumber", 1, guttersChanged, true);
option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
option("showCursorWhenSelecting", false, updateSelection, true);
option("resetSelectionOnContextMenu", true);
option("readOnly", false, function(cm, val) {
if (val == "nocursor") {
onBlur(cm);
cm.display.input.blur();
cm.display.disabled = true;
} else {
cm.display.disabled = false;
if (!val) resetInput(cm);
}
});
option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, true);
option("dragDrop", true);
option("cursorBlinkRate", 530);
option("cursorScrollMargin", 0);
option("cursorHeight", 1);
option("workTime", 100);
option("workDelay", 100);
option("flattenSpans", true, resetModeState, true);
option("addModeClass", false, resetModeState, true);
option("pollInterval", 100);
option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
option("historyEventDelay", 1250);
option("viewportMargin", 10, function(cm){cm.refresh();}, true);
option("maxHighlightLength", 10000, resetModeState, true);
option("moveInputWithCursor", true, function(cm, val) {
if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
});
option("tabindex", null, function(cm, val) {
cm.display.input.tabIndex = val || "";
});
option("autofocus", null);
// MODE DEFINITION AND QUERYING
// Known modes, by name and by MIME
var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
CodeMirror.defineMode = function(name, mode) {
if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
if (arguments.length > 2) {
mode.dependencies = [];
for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
}
modes[name] = mode;
};
CodeMirror.defineMIME = function(mime, spec) {
mimeModes[mime] = spec;
};
// Given a MIME type, a {name, ...options} config object, or a name
// string, return a mode config object.
CodeMirror.resolveMode = function(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
spec = mimeModes[spec];
} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
var found = mimeModes[spec.name];
if (typeof found == "string") found = {name: found};
spec = createObj(found, spec);
spec.name = found.name;
} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
return CodeMirror.resolveMode("application/xml");
}
if (typeof spec == "string") return {name: spec};
else return spec || {name: "null"};
};
// Given a mode spec (anything that resolveMode accepts), find and
// initialize an actual mode object.
CodeMirror.getMode = function(options, spec) {
var spec = CodeMirror.resolveMode(spec);
var mfactory = modes[spec.name];
if (!mfactory) return CodeMirror.getMode(options, "text/plain");
var modeObj = mfactory(options, spec);
if (modeExtensions.hasOwnProperty(spec.name)) {
var exts = modeExtensions[spec.name];
for (var prop in exts) {
if (!exts.hasOwnProperty(prop)) continue;
if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
modeObj[prop] = exts[prop];
}
}
modeObj.name = spec.name;
if (spec.helperType) modeObj.helperType = spec.helperType;
if (spec.modeProps) for (var prop in spec.modeProps)
modeObj[prop] = spec.modeProps[prop];
return modeObj;
};
// Minimal default mode.
CodeMirror.defineMode("null", function() {
return {token: function(stream) {stream.skipToEnd();}};
});
CodeMirror.defineMIME("text/plain", "null");
// This can be used to attach properties to mode objects from
// outside the actual mode definition.
var modeExtensions = CodeMirror.modeExtensions = {};
CodeMirror.extendMode = function(mode, properties) {
var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
copyObj(properties, exts);
};
// EXTENSIONS
CodeMirror.defineExtension = function(name, func) {
CodeMirror.prototype[name] = func;
};
CodeMirror.defineDocExtension = function(name, func) {
Doc.prototype[name] = func;
};
CodeMirror.defineOption = option;
var initHooks = [];
CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
var helpers = CodeMirror.helpers = {};
CodeMirror.registerHelper = function(type, name, value) {
if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
helpers[type][name] = value;
};
CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
CodeMirror.registerHelper(type, name, value);
helpers[type]._global.push({pred: predicate, val: value});
};
// MODE STATE HANDLING
// Utility functions for working with state. Exported because nested
// modes need to do this for their inner modes.
var copyState = CodeMirror.copyState = function(mode, state) {
if (state === true) return state;
if (mode.copyState) return mode.copyState(state);
var nstate = {};
for (var n in state) {
var val = state[n];
if (val instanceof Array) val = val.concat([]);
nstate[n] = val;
}
return nstate;
};
var startState = CodeMirror.startState = function(mode, a1, a2) {
return mode.startState ? mode.startState(a1, a2) : true;
};
// Given a mode and a state (for that mode), find the inner mode and
// state at the position that the state refers to.
CodeMirror.innerMode = function(mode, state) {
while (mode.innerMode) {
var info = mode.innerMode(state);
if (!info || info.mode == mode) break;
state = info.state;
mode = info.mode;
}
return info || {mode: mode, state: state};
};
// STANDARD COMMANDS
// Commands are parameter-less actions that can be performed on an
// editor, mostly used for keybindings.
var commands = CodeMirror.commands = {
selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
singleSelection: function(cm) {
cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
},
killLine: function(cm) {
deleteNearSelection(cm, function(range) {
if (range.empty()) {
var len = getLine(cm.doc, range.head.line).text.length;
if (range.head.ch == len && range.head.line < cm.lastLine())
return {from: range.head, to: Pos(range.head.line + 1, 0)};
else
return {from: range.head, to: Pos(range.head.line, len)};
} else {
return {from: range.from(), to: range.to()};
}
});
},
deleteLine: function(cm) {
deleteNearSelection(cm, function(range) {
return {from: Pos(range.from().line, 0),
to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
});
},
delLineLeft: function(cm) {
deleteNearSelection(cm, function(range) {
return {from: Pos(range.from().line, 0), to: range.from()};
});
},
undo: function(cm) {cm.undo();},
redo: function(cm) {cm.redo();},
undoSelection: function(cm) {cm.undoSelection();},
redoSelection: function(cm) {cm.redoSelection();},
goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
goLineStart: function(cm) {
cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, sel_move);
},
goLineStartSmart: function(cm) {
cm.extendSelectionsBy(function(range) {
var start = lineStart(cm, range.head.line);
var line = cm.getLineHandle(start.line);
var order = getOrder(line);
if (!order || order[0].level == 0) {
var firstNonWS = Math.max(0, line.text.search(/\S/));
var inWS = range.head.line == start.line && range.head.ch <= firstNonWS && range.head.ch;
return Pos(start.line, inWS ? 0 : firstNonWS);
}
return start;
}, sel_move);
},
goLineEnd: function(cm) {
cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, sel_move);
},
goLineRight: function(cm) {
cm.extendSelectionsBy(function(range) {
var top = cm.charCoords(range.head, "div").top + 5;
return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
}, sel_move);
},
goLineLeft: function(cm) {
cm.extendSelectionsBy(function(range) {
var top = cm.charCoords(range.head, "div").top + 5;
return cm.coordsChar({left: 0, top: top}, "div");
}, sel_move);
},
goLineUp: function(cm) {cm.moveV(-1, "line");},
goLineDown: function(cm) {cm.moveV(1, "line");},
goPageUp: function(cm) {cm.moveV(-1, "page");},
goPageDown: function(cm) {cm.moveV(1, "page");},
goCharLeft: function(cm) {cm.moveH(-1, "char");},
goCharRight: function(cm) {cm.moveH(1, "char");},
goColumnLeft: function(cm) {cm.moveH(-1, "column");},
goColumnRight: function(cm) {cm.moveH(1, "column");},
goWordLeft: function(cm) {cm.moveH(-1, "word");},
goGroupRight: function(cm) {cm.moveH(1, "group");},
goGroupLeft: function(cm) {cm.moveH(-1, "group");},
goWordRight: function(cm) {cm.moveH(1, "word");},
delCharBefore: function(cm) {cm.deleteH(-1, "char");},
delCharAfter: function(cm) {cm.deleteH(1, "char");},
delWordBefore: function(cm) {cm.deleteH(-1, "word");},
delWordAfter: function(cm) {cm.deleteH(1, "word");},
delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
delGroupAfter: function(cm) {cm.deleteH(1, "group");},
indentAuto: function(cm) {cm.indentSelection("smart");},
indentMore: function(cm) {cm.indentSelection("add");},
indentLess: function(cm) {cm.indentSelection("subtract");},
insertTab: function(cm) {cm.replaceSelection("\t");},
insertSoftTab: function(cm) {
var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
for (var i = 0; i < ranges.length; i++) {
var pos = ranges[i].from();
var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
}
cm.replaceSelections(spaces);
},
defaultTab: function(cm) {
if (cm.somethingSelected()) cm.indentSelection("add");
else cm.execCommand("insertTab");
},
transposeChars: function(cm) {
runInOp(cm, function() {
var ranges = cm.listSelections(), newSel = [];
for (var i = 0; i < ranges.length; i++) {
var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
if (line) {
if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
if (cur.ch > 0) {
cur = new Pos(cur.line, cur.ch + 1);
cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
Pos(cur.line, cur.ch - 2), cur, "+transpose");
} else if (cur.line > cm.doc.first) {
var prev = getLine(cm.doc, cur.line - 1).text;
if (prev)
cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),
Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
}
}
newSel.push(new Range(cur, cur));
}
cm.setSelections(newSel);
});
},
newlineAndIndent: function(cm) {
runInOp(cm, function() {
var len = cm.listSelections().length;
for (var i = 0; i < len; i++) {
var range = cm.listSelections()[i];
cm.replaceRange("\n", range.anchor, range.head, "+input");
cm.indentLine(range.from().line + 1, null, true);
ensureCursorVisible(cm);
}
});
},
toggleOverwrite: function(cm) {cm.toggleOverwrite();}
};
// STANDARD KEYMAPS
var keyMap = CodeMirror.keyMap = {};
keyMap.basic = {
"Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
"End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
"Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
"Tab": "defaultTab", "Shift-Tab": "indentAuto",
"Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
"Esc": "singleSelection"
};
// Note that the save and find-related commands aren't defined by
// default. User code or addons can define them. Unknown commands
// are simply ignored.
keyMap.pcDefault = {
"Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
"Ctrl-Home": "goDocStart", "Ctrl-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
"Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
"Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
"Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
"Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
"Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
fallthrough: "basic"
};
keyMap.macDefault = {
"Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
"Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
"Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
"Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
"Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
"Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
"Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection",
fallthrough: ["basic", "emacsy"]
};
// Very basic readline/emacs-style bindings, which are standard on Mac.
keyMap.emacsy = {
"Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
"Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
"Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
"Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
};
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
// KEYMAP DISPATCH
function getKeyMap(val) {
if (typeof val == "string") return keyMap[val];
else return val;
}
// Given an array of keymaps and a key name, call handle on any
// bindings found, until that returns a truthy value, at which point
// we consider the key handled. Implements things like binding a key
// to false stopping further handling and keymap fallthrough.
var lookupKey = CodeMirror.lookupKey = function(name, maps, handle) {
function lookup(map) {
map = getKeyMap(map);
var found = map[name];
if (found === false) return "stop";
if (found != null && handle(found)) return true;
if (map.nofallthrough) return "stop";
var fallthrough = map.fallthrough;
if (fallthrough == null) return false;
if (Object.prototype.toString.call(fallthrough) != "[object Array]")
return lookup(fallthrough);
for (var i = 0; i < fallthrough.length; ++i) {
var done = lookup(fallthrough[i]);
if (done) return done;
}
return false;
}
for (var i = 0; i < maps.length; ++i) {
var done = lookup(maps[i]);
if (done) return done != "stop";
}
};
// Modifier key presses don't count as 'real' key presses for the
// purpose of keymap fallthrough.
var isModifierKey = CodeMirror.isModifierKey = function(event) {
var name = keyNames[event.keyCode];
return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
};
// Look up the name of a key as indicated by an event object.
var keyName = CodeMirror.keyName = function(event, noShift) {
if (presto && event.keyCode == 34 && event["char"]) return false;
var name = keyNames[event.keyCode];
if (name == null || event.altGraphKey) return false;
if (event.altKey) name = "Alt-" + name;
if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
if (!noShift && event.shiftKey) name = "Shift-" + name;
return name;
};
// FROMTEXTAREA
CodeMirror.fromTextArea = function(textarea, options) {
if (!options) options = {};
options.value = textarea.value;
if (!options.tabindex && textarea.tabindex)
options.tabindex = textarea.tabindex;
if (!options.placeholder && textarea.placeholder)
options.placeholder = textarea.placeholder;
// Set autofocus to true if this textarea is focused, or if it has
// autofocus and no other element is focused.
if (options.autofocus == null) {
var hasFocus = activeElt();
options.autofocus = hasFocus == textarea ||
textarea.getAttribute("autofocus") != null && hasFocus == document.body;
}
function save() {textarea.value = cm.getValue();}
if (textarea.form) {
on(textarea.form, "submit", save);
// Deplorable hack to make the submit method do the right thing.
if (!options.leaveSubmitMethodAlone) {
var form = textarea.form, realSubmit = form.submit;
try {
var wrappedSubmit = form.submit = function() {
save();
form.submit = realSubmit;
form.submit();
form.submit = wrappedSubmit;
};
} catch(e) {}
}
}
textarea.style.display = "none";
var cm = CodeMirror(function(node) {
textarea.parentNode.insertBefore(node, textarea.nextSibling);
}, options);
cm.save = save;
cm.getTextArea = function() { return textarea; };
cm.toTextArea = function() {
save();
textarea.parentNode.removeChild(cm.getWrapperElement());
textarea.style.display = "";
if (textarea.form) {
off(textarea.form, "submit", save);
if (typeof textarea.form.submit == "function")
textarea.form.submit = realSubmit;
}
};
return cm;
};
// STRING STREAM
// Fed to the mode parsers, provides helper functions to make
// parsers more succinct.
var StringStream = CodeMirror.StringStream = function(string, tabSize) {
this.pos = this.start = 0;
this.string = string;
this.tabSize = tabSize || 8;
this.lastColumnPos = this.lastColumnValue = 0;
this.lineStart = 0;
};
StringStream.prototype = {
eol: function() {return this.pos >= this.string.length;},
sol: function() {return this.pos == this.lineStart;},
peek: function() {return this.string.charAt(this.pos) || undefined;},
next: function() {
if (this.pos < this.string.length)
return this.string.charAt(this.pos++);
},
eat: function(match) {
var ch = this.string.charAt(this.pos);
if (typeof match == "string") var ok = ch == match;
else var ok = ch && (match.test ? match.test(ch) : match(ch));
if (ok) {++this.pos; return ch;}
},
eatWhile: function(match) {
var start = this.pos;
while (this.eat(match)){}
return this.pos > start;
},
eatSpace: function() {
var start = this.pos;
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
return this.pos > start;
},
skipToEnd: function() {this.pos = this.string.length;},
skipTo: function(ch) {
var found = this.string.indexOf(ch, this.pos);
if (found > -1) {this.pos = found; return true;}
},
backUp: function(n) {this.pos -= n;},
column: function() {
if (this.lastColumnPos < this.start) {
this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
this.lastColumnPos = this.start;
}
return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
},
indentation: function() {
return countColumn(this.string, null, this.tabSize) -
(this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
},
match: function(pattern, consume, caseInsensitive) {
if (typeof pattern == "string") {
var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
var substr = this.string.substr(this.pos, pattern.length);
if (cased(substr) == cased(pattern)) {
if (consume !== false) this.pos += pattern.length;
return true;
}
} else {
var match = this.string.slice(this.pos).match(pattern);
if (match && match.index > 0) return null;
if (match && consume !== false) this.pos += match[0].length;
return match;
}
},
current: function(){return this.string.slice(this.start, this.pos);},
hideFirstChars: function(n, inner) {
this.lineStart += n;
try { return inner(); }
finally { this.lineStart -= n; }
}
};
// TEXTMARKERS
// Created with markText and setBookmark methods. A TextMarker is a
// handle that can be used to clear or find a marked position in the
// document. Line objects hold arrays (markedSpans) containing
// {from, to, marker} object pointing to such marker objects, and
// indicating that such a marker is present on that line. Multiple
// lines may point to the same marker when it spans across lines.
// The spans will have null for their from/to properties when the
// marker continues beyond the start/end of the line. Markers have
// links back to the lines they currently touch.
var TextMarker = CodeMirror.TextMarker = function(doc, type) {
this.lines = [];
this.type = type;
this.doc = doc;
};
eventMixin(TextMarker);
// Clear the marker.
TextMarker.prototype.clear = function() {
if (this.explicitlyCleared) return;
var cm = this.doc.cm, withOp = cm && !cm.curOp;
if (withOp) startOperation(cm);
if (hasHandler(this, "clear")) {
var found = this.find();
if (found) signalLater(this, "clear", found.from, found.to);
}
var min = null, max = null;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
else if (cm) {
if (span.to != null) max = lineNo(line);
if (span.from != null) min = lineNo(line);
}
line.markedSpans = removeMarkedSpan(line.markedSpans, span);
if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
updateLineHeight(line, textHeight(cm.display));
}
if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
var visual = visualLine(this.lines[i]), len = lineLength(visual);
if (len > cm.display.maxLineLength) {
cm.display.maxLine = visual;
cm.display.maxLineLength = len;
cm.display.maxLineChanged = true;
}
}
if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
this.lines.length = 0;
this.explicitlyCleared = true;
if (this.atomic && this.doc.cantEdit) {
this.doc.cantEdit = false;
if (cm) reCheckSelection(cm.doc);
}
if (cm) signalLater(cm, "markerCleared", cm, this);
if (withOp) endOperation(cm);
if (this.parent) this.parent.clear();
};
// Find the position of the marker in the document. Returns a {from,
// to} object by default. Side can be passed to get a specific side
// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
// Pos objects returned contain a line object, rather than a line
// number (used to prevent looking up the same line twice).
TextMarker.prototype.find = function(side, lineObj) {
if (side == null && this.type == "bookmark") side = 1;
var from, to;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (span.from != null) {
from = Pos(lineObj ? line : lineNo(line), span.from);
if (side == -1) return from;
}
if (span.to != null) {
to = Pos(lineObj ? line : lineNo(line), span.to);
if (side == 1) return to;
}
}
return from && {from: from, to: to};
};
// Signals that the marker's widget changed, and surrounding layout
// should be recomputed.
TextMarker.prototype.changed = function() {
var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
if (!pos || !cm) return;
runInOp(cm, function() {
var line = pos.line, lineN = lineNo(pos.line);
var view = findViewForLine(cm, lineN);
if (view) {
clearLineMeasurementCacheFor(view);
cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
}
cm.curOp.updateMaxLine = true;
if (!lineIsHidden(widget.doc, line) && widget.height != null) {
var oldHeight = widget.height;
widget.height = null;
var dHeight = widgetHeight(widget) - oldHeight;
if (dHeight)
updateLineHeight(line, line.height + dHeight);
}
});
};
TextMarker.prototype.attachLine = function(line) {
if (!this.lines.length && this.doc.cm) {
var op = this.doc.cm.curOp;
if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
(op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
}
this.lines.push(line);
};
TextMarker.prototype.detachLine = function(line) {
this.lines.splice(indexOf(this.lines, line), 1);
if (!this.lines.length && this.doc.cm) {
var op = this.doc.cm.curOp;
(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
}
};
// Collapsed markers have unique ids, in order to be able to order
// them, which is needed for uniquely determining an outer marker
// when they overlap (they may nest, but not partially overlap).
var nextMarkerId = 0;
// Create a marker, wire it up to the right lines, and
function markText(doc, from, to, options, type) {
// Shared markers (across linked documents) are handled separately
// (markTextShared will call out to this again, once per
// document).
if (options && options.shared) return markTextShared(doc, from, to, options, type);
// Ensure we are in an operation.
if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
var marker = new TextMarker(doc, type), diff = cmp(from, to);
if (options) copyObj(options, marker, false);
// Don't connect empty markers unless clearWhenEmpty is false
if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
return marker;
if (marker.replacedWith) {
// Showing up as a widget implies collapsed (widget replaces text)
marker.collapsed = true;
marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
if (!options.handleMouseEvents) marker.widgetNode.ignoreEvents = true;
if (options.insertLeft) marker.widgetNode.insertLeft = true;
}
if (marker.collapsed) {
if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
throw new Error("Inserting collapsed marker partially overlapping an existing one");
sawCollapsedSpans = true;
}
if (marker.addToHistory)
addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
var curLine = from.line, cm = doc.cm, updateMaxLine;
doc.iter(curLine, to.line + 1, function(line) {
if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
updateMaxLine = true;
if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
addMarkedSpan(line, new MarkedSpan(marker,
curLine == from.line ? from.ch : null,
curLine == to.line ? to.ch : null));
++curLine;
});
// lineIsHidden depends on the presence of the spans, so needs a second pass
if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
});
if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
if (marker.readOnly) {
sawReadOnlySpans = true;
if (doc.history.done.length || doc.history.undone.length)
doc.clearHistory();
}
if (marker.collapsed) {
marker.id = ++nextMarkerId;
marker.atomic = true;
}
if (cm) {
// Sync editor state
if (updateMaxLine) cm.curOp.updateMaxLine = true;
if (marker.collapsed)
regChange(cm, from.line, to.line + 1);
else if (marker.className || marker.title || marker.startStyle || marker.endStyle)
for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
if (marker.atomic) reCheckSelection(cm.doc);
signalLater(cm, "markerAdded", cm, marker);
}
return marker;
}
// SHARED TEXTMARKERS
// A shared marker spans multiple linked documents. It is
// implemented as a meta-marker-object controlling multiple normal
// markers.
var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
this.markers = markers;
this.primary = primary;
for (var i = 0; i < markers.length; ++i)
markers[i].parent = this;
};
eventMixin(SharedTextMarker);
SharedTextMarker.prototype.clear = function() {
if (this.explicitlyCleared) return;
this.explicitlyCleared = true;
for (var i = 0; i < this.markers.length; ++i)
this.markers[i].clear();
signalLater(this, "clear");
};
SharedTextMarker.prototype.find = function(side, lineObj) {
return this.primary.find(side, lineObj);
};
function markTextShared(doc, from, to, options, type) {
options = copyObj(options);
options.shared = false;
var markers = [markText(doc, from, to, options, type)], primary = markers[0];
var widget = options.widgetNode;
linkedDocs(doc, function(doc) {
if (widget) options.widgetNode = widget.cloneNode(true);
markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
for (var i = 0; i < doc.linked.length; ++i)
if (doc.linked[i].isParent) return;
primary = lst(markers);
});
return new SharedTextMarker(markers, primary);
}
function findSharedMarkers(doc) {
return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
function(m) { return m.parent; });
}
function copySharedMarkers(doc, markers) {
for (var i = 0; i < markers.length; i++) {
var marker = markers[i], pos = marker.find();
var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
if (cmp(mFrom, mTo)) {
var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
marker.markers.push(subMark);
subMark.parent = marker;
}
}
}
function detachSharedMarkers(markers) {
for (var i = 0; i < markers.length; i++) {
var marker = markers[i], linked = [marker.primary.doc];;
linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
for (var j = 0; j < marker.markers.length; j++) {
var subMarker = marker.markers[j];
if (indexOf(linked, subMarker.doc) == -1) {
subMarker.parent = null;
marker.markers.splice(j--, 1);
}
}
}
}
// TEXTMARKER SPANS
function MarkedSpan(marker, from, to) {
this.marker = marker;
this.from = from; this.to = to;
}
// Search an array of spans for a span matching the given marker.
function getMarkedSpanFor(spans, marker) {
if (spans) for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if (span.marker == marker) return span;
}
}
// Remove a span from an array, returning undefined if no spans are
// left (we don't store arrays for lines without spans).
function removeMarkedSpan(spans, span) {
for (var r, i = 0; i < spans.length; ++i)
if (spans[i] != span) (r || (r = [])).push(spans[i]);
return r;
}
// Add a span to a line.
function addMarkedSpan(line, span) {
line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
span.marker.attachLine(line);
}
// Used for the algorithm that adjusts markers for a change in the
// document. These functions cut an array of spans at a given
// character position, returning an array of remaining chunks (or
// undefined if nothing remains).
function markedSpansBefore(old, startCh, isInsert) {
if (old) for (var i = 0, nw; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
}
}
return nw;
}
function markedSpansAfter(old, endCh, isInsert) {
if (old) for (var i = 0, nw; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
span.to == null ? null : span.to - endCh));
}
}
return nw;
}
// Given a change object, compute the new set of marker spans that
// cover the line in which the change took place. Removes spans
// entirely within the change, reconnects spans belonging to the
// same marker that appear on both sides of the change, and cuts off
// spans partially within the change. Returns an array of span
// arrays with one element for each line in (after) the change.
function stretchSpansOverChange(doc, change) {
var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
if (!oldFirst && !oldLast) return null;
var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
// Get the spans that 'stick out' on both sides
var first = markedSpansBefore(oldFirst, startCh, isInsert);
var last = markedSpansAfter(oldLast, endCh, isInsert);
// Next, merge those two ends
var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
if (first) {
// Fix up .to properties of first
for (var i = 0; i < first.length; ++i) {
var span = first[i];
if (span.to == null) {
var found = getMarkedSpanFor(last, span.marker);
if (!found) span.to = startCh;
else if (sameLine) span.to = found.to == null ? null : found.to + offset;
}
}
}
if (last) {
// Fix up .from in last (or move them into first in case of sameLine)
for (var i = 0; i < last.length; ++i) {
var span = last[i];
if (span.to != null) span.to += offset;
if (span.from == null) {
var found = getMarkedSpanFor(first, span.marker);
if (!found) {
span.from = offset;
if (sameLine) (first || (first = [])).push(span);
}
} else {
span.from += offset;
if (sameLine) (first || (first = [])).push(span);
}
}
}
// Make sure we didn't create any zero-length spans
if (first) first = clearEmptySpans(first);
if (last && last != first) last = clearEmptySpans(last);
var newMarkers = [first];
if (!sameLine) {
// Fill gap with whole-line-spans
var gap = change.text.length - 2, gapMarkers;
if (gap > 0 && first)
for (var i = 0; i < first.length; ++i)
if (first[i].to == null)
(gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
for (var i = 0; i < gap; ++i)
newMarkers.push(gapMarkers);
newMarkers.push(last);
}
return newMarkers;
}
// Remove spans that are empty and don't have a clearWhenEmpty
// option of false.
function clearEmptySpans(spans) {
for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
spans.splice(i--, 1);
}
if (!spans.length) return null;
return spans;
}
// Used for un/re-doing changes from the history. Combines the
// result of computing the existing spans with the set of spans that
// existed in the history (so that deleting around a span and then
// undoing brings back the span).
function mergeOldSpans(doc, change) {
var old = getOldSpans(doc, change);
var stretched = stretchSpansOverChange(doc, change);
if (!old) return stretched;
if (!stretched) return old;
for (var i = 0; i < old.length; ++i) {
var oldCur = old[i], stretchCur = stretched[i];
if (oldCur && stretchCur) {
spans: for (var j = 0; j < stretchCur.length; ++j) {
var span = stretchCur[j];
for (var k = 0; k < oldCur.length; ++k)
if (oldCur[k].marker == span.marker) continue spans;
oldCur.push(span);
}
} else if (stretchCur) {
old[i] = stretchCur;
}
}
return old;
}
// Used to 'clip' out readOnly ranges when making a change.
function removeReadOnlyRanges(doc, from, to) {
var markers = null;
doc.iter(from.line, to.line + 1, function(line) {
if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
var mark = line.markedSpans[i].marker;
if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
(markers || (markers = [])).push(mark);
}
});
if (!markers) return null;
var parts = [{from: from, to: to}];
for (var i = 0; i < markers.length; ++i) {
var mk = markers[i], m = mk.find(0);
for (var j = 0; j < parts.length; ++j) {
var p = parts[j];
if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
newParts.push({from: p.from, to: m.from});
if (dto > 0 || !mk.inclusiveRight && !dto)
newParts.push({from: m.to, to: p.to});
parts.splice.apply(parts, newParts);
j += newParts.length - 1;
}
}
return parts;
}
// Connect or disconnect spans from a line.
function detachMarkedSpans(line) {
var spans = line.markedSpans;
if (!spans) return;
for (var i = 0; i < spans.length; ++i)
spans[i].marker.detachLine(line);
line.markedSpans = null;
}
function attachMarkedSpans(line, spans) {
if (!spans) return;
for (var i = 0; i < spans.length; ++i)
spans[i].marker.attachLine(line);
line.markedSpans = spans;
}
// Helpers used when computing which overlapping collapsed span
// counts as the larger one.
function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
// Returns a number indicating which of two overlapping collapsed
// spans is larger (and thus includes the other). Falls back to
// comparing ids when the spans cover exactly the same range.
function compareCollapsedMarkers(a, b) {
var lenDiff = a.lines.length - b.lines.length;
if (lenDiff != 0) return lenDiff;
var aPos = a.find(), bPos = b.find();
var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
if (fromCmp) return -fromCmp;
var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
if (toCmp) return toCmp;
return b.id - a.id;
}
// Find out whether a line ends or starts in a collapsed span. If
// so, return the marker for that span.
function collapsedSpanAtSide(line, start) {
var sps = sawCollapsedSpans && line.markedSpans, found;
if (sps) for (var sp, i = 0; i < sps.length; ++i) {
sp = sps[i];
if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
(!found || compareCollapsedMarkers(found, sp.marker) < 0))
found = sp.marker;
}
return found;
}
function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
// Test whether there exists a collapsed span that partially
// overlaps (covers the start or end, but not both) of a new span.
// Such overlap is not allowed.
function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
var line = getLine(doc, lineNo);
var sps = sawCollapsedSpans && line.markedSpans;
if (sps) for (var i = 0; i < sps.length; ++i) {
var sp = sps[i];
if (!sp.marker.collapsed) continue;
var found = sp.marker.find(0);
var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
if (fromCmp <= 0 && (cmp(found.to, from) || extraRight(sp.marker) - extraLeft(marker)) > 0 ||
fromCmp >= 0 && (cmp(found.from, to) || extraLeft(sp.marker) - extraRight(marker)) < 0)
return true;
}
}
// A visual line is a line as drawn on the screen. Folding, for
// example, can cause multiple logical lines to appear on the same
// visual line. This finds the start of the visual line that the
// given line is part of (usually that is the line itself).
function visualLine(line) {
var merged;
while (merged = collapsedSpanAtStart(line))
line = merged.find(-1, true).line;
return line;
}
// Returns an array of logical lines that continue the visual line
// started by the argument, or undefined if there are no such lines.
function visualLineContinued(line) {
var merged, lines;
while (merged = collapsedSpanAtEnd(line)) {
line = merged.find(1, true).line;
(lines || (lines = [])).push(line);
}
return lines;
}
// Get the line number of the start of the visual line that the
// given line number is part of.
function visualLineNo(doc, lineN) {
var line = getLine(doc, lineN), vis = visualLine(line);
if (line == vis) return lineN;
return lineNo(vis);
}
// Get the line number of the start of the next visual line after
// the given line.
function visualLineEndNo(doc, lineN) {
if (lineN > doc.lastLine()) return lineN;
var line = getLine(doc, lineN), merged;
if (!lineIsHidden(doc, line)) return lineN;
while (merged = collapsedSpanAtEnd(line))
line = merged.find(1, true).line;
return lineNo(line) + 1;
}
// Compute whether a line is hidden. Lines count as hidden when they
// are part of a visual line that starts with another line, or when
// they are entirely covered by collapsed, non-widget span.
function lineIsHidden(doc, line) {
var sps = sawCollapsedSpans && line.markedSpans;
if (sps) for (var sp, i = 0; i < sps.length; ++i) {
sp = sps[i];
if (!sp.marker.collapsed) continue;
if (sp.from == null) return true;
if (sp.marker.widgetNode) continue;
if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
return true;
}
}
function lineIsHiddenInner(doc, line, span) {
if (span.to == null) {
var end = span.marker.find(1, true);
return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
}
if (span.marker.inclusiveRight && span.to == line.text.length)
return true;
for (var sp, i = 0; i < line.markedSpans.length; ++i) {
sp = line.markedSpans[i];
if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
(sp.to == null || sp.to != span.from) &&
(sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
lineIsHiddenInner(doc, line, sp)) return true;
}
}
// LINE WIDGETS
// Line widgets are block elements displayed above or below a line.
var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
if (options) for (var opt in options) if (options.hasOwnProperty(opt))
this[opt] = options[opt];
this.cm = cm;
this.node = node;
};
eventMixin(LineWidget);
function adjustScrollWhenAboveVisible(cm, line, diff) {
if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
addToScrollPos(cm, null, diff);
}
LineWidget.prototype.clear = function() {
var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
if (no == null || !ws) return;
for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
if (!ws.length) line.widgets = null;
var height = widgetHeight(this);
runInOp(cm, function() {
adjustScrollWhenAboveVisible(cm, line, -height);
regLineChange(cm, no, "widget");
updateLineHeight(line, Math.max(0, line.height - height));
});
};
LineWidget.prototype.changed = function() {
var oldH = this.height, cm = this.cm, line = this.line;
this.height = null;
var diff = widgetHeight(this) - oldH;
if (!diff) return;
runInOp(cm, function() {
cm.curOp.forceUpdate = true;
adjustScrollWhenAboveVisible(cm, line, diff);
updateLineHeight(line, line.height + diff);
});
};
function widgetHeight(widget) {
if (widget.height != null) return widget.height;
if (!contains(document.body, widget.node))
removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
return widget.height = widget.node.offsetHeight;
}
function addLineWidget(cm, handle, node, options) {
var widget = new LineWidget(cm, node, options);
if (widget.noHScroll) cm.display.alignWidgets = true;
changeLine(cm, handle, "widget", function(line) {
var widgets = line.widgets || (line.widgets = []);
if (widget.insertAt == null) widgets.push(widget);
else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
widget.line = line;
if (!lineIsHidden(cm.doc, line)) {
var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;
updateLineHeight(line, line.height + widgetHeight(widget));
if (aboveVisible) addToScrollPos(cm, null, widget.height);
cm.curOp.forceUpdate = true;
}
return true;
});
return widget;
}
// LINE DATA STRUCTURE
// Line objects. These hold state related to a line, including
// highlighting info (the styles array).
var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
this.text = text;
attachMarkedSpans(this, markedSpans);
this.height = estimateHeight ? estimateHeight(this) : 1;
};
eventMixin(Line);
Line.prototype.lineNo = function() { return lineNo(this); };
// Change the content (text, markers) of a line. Automatically
// invalidates cached information and tries to re-estimate the
// line's height.
function updateLine(line, text, markedSpans, estimateHeight) {
line.text = text;
if (line.stateAfter) line.stateAfter = null;
if (line.styles) line.styles = null;
if (line.order != null) line.order = null;
detachMarkedSpans(line);
attachMarkedSpans(line, markedSpans);
var estHeight = estimateHeight ? estimateHeight(line) : 1;
if (estHeight != line.height) updateLineHeight(line, estHeight);
}
// Detach a line from the document tree and its markers.
function cleanUpLine(line) {
line.parent = null;
detachMarkedSpans(line);
}
function extractLineClasses(type, output) {
if (type) for (;;) {
var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
if (!lineClass) break;
type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
var prop = lineClass[1] ? "bgClass" : "textClass";
if (output[prop] == null)
output[prop] = lineClass[2];
else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
output[prop] += " " + lineClass[2];
}
return type;
}
function callBlankLine(mode, state) {
if (mode.blankLine) return mode.blankLine(state);
if (!mode.innerMode) return;
var inner = CodeMirror.innerMode(mode, state);
if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
}
function readToken(mode, stream, state) {
for (var i = 0; i < 10; i++) {
var style = mode.token(stream, state);
if (stream.pos > stream.start) return style;
}
throw new Error("Mode " + mode.name + " failed to advance stream.");
}
// Run the given mode's parser over a line, calling f for each token.
function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
var flattenSpans = mode.flattenSpans;
if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
var curStart = 0, curStyle = null;
var stream = new StringStream(text, cm.options.tabSize), style;
if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
while (!stream.eol()) {
if (stream.pos > cm.options.maxHighlightLength) {
flattenSpans = false;
if (forceToEnd) processLine(cm, text, state, stream.pos);
stream.pos = text.length;
style = null;
} else {
style = extractLineClasses(readToken(mode, stream, state), lineClasses);
}
if (cm.options.addModeClass) {
var mName = CodeMirror.innerMode(mode, state).mode.name;
if (mName) style = "m-" + (style ? mName + " " + style : mName);
}
if (!flattenSpans || curStyle != style) {
if (curStart < stream.start) f(stream.start, curStyle);
curStart = stream.start; curStyle = style;
}
stream.start = stream.pos;
}
while (curStart < stream.pos) {
// Webkit seems to refuse to render text nodes longer than 57444 characters
var pos = Math.min(stream.pos, curStart + 50000);
f(pos, curStyle);
curStart = pos;
}
}
// Compute a style array (an array starting with a mode generation
// -- for invalidation -- followed by pairs of end positions and
// style strings), which is used to highlight the tokens on the
// line.
function highlightLine(cm, line, state, forceToEnd) {
// A styles array always starts with a number identifying the
// mode/overlays that it is based on (for easy invalidation).
var st = [cm.state.modeGen], lineClasses = {};
// Compute the base array of styles
runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
st.push(end, style);
}, lineClasses, forceToEnd);
// Run overlays, adjust style array.
for (var o = 0; o < cm.state.overlays.length; ++o) {
var overlay = cm.state.overlays[o], i = 1, at = 0;
runMode(cm, line.text, overlay.mode, true, function(end, style) {
var start = i;
// Ensure there's a token end at the current position, and that i points at it
while (at < end) {
var i_end = st[i];
if (i_end > end)
st.splice(i, 1, end, st[i+1], i_end);
i += 2;
at = Math.min(end, i_end);
}
if (!style) return;
if (overlay.opaque) {
st.splice(start, i - start, end, "cm-overlay " + style);
i = start + 2;
} else {
for (; start < i; start += 2) {
var cur = st[start+1];
st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
}
}
}, lineClasses);
}
return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
}
function getLineStyles(cm, line) {
if (!line.styles || line.styles[0] != cm.state.modeGen) {
var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
line.styles = result.styles;
if (result.classes) line.styleClasses = result.classes;
else if (line.styleClasses) line.styleClasses = null;
}
return line.styles;
}
// Lightweight form of highlight -- proceed over this line and
// update state, but don't save a style array. Used for lines that
// aren't currently visible.
function processLine(cm, text, state, startAt) {
var mode = cm.doc.mode;
var stream = new StringStream(text, cm.options.tabSize);
stream.start = stream.pos = startAt || 0;
if (text == "") callBlankLine(mode, state);
while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
readToken(mode, stream, state);
stream.start = stream.pos;
}
}
// Convert a style as returned by a mode (either null, or a string
// containing one or more styles) to a CSS style. This is cached,
// and also looks for line-wide styles.
var styleToClassCache = {}, styleToClassCacheWithMode = {};
function interpretTokenStyle(style, options) {
if (!style || /^\s*$/.test(style)) return null;
var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
return cache[style] ||
(cache[style] = style.replace(/\S+/g, "cm-$&"));
}
// Render the DOM representation of the text of a line. Also builds
// up a 'line map', which points at the DOM nodes that represent
// specific stretches of text, and is used by the measuring code.
// The returned object contains the DOM node, this map, and
// information about line-wide styles that were set by the mode.
function buildLineContent(cm, lineView) {
// The padding-right forces the element to have a 'border', which
// is needed on Webkit to be able to get line-level bounding
// rectangles for it (in measureChar).
var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
lineView.measure = {};
// Iterate over the logical lines that make up this visual line.
for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
var line = i ? lineView.rest[i - 1] : lineView.line, order;
builder.pos = 0;
builder.addToken = buildToken;
// Optionally wire in some hacks into the token-rendering
// algorithm, to deal with browser quirks.
if ((ie || webkit) && cm.getOption("lineWrapping"))
builder.addToken = buildTokenSplitSpaces(builder.addToken);
if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
builder.addToken = buildTokenBadBidi(builder.addToken, order);
builder.map = [];
insertLineContent(line, builder, getLineStyles(cm, line));
if (line.styleClasses) {
if (line.styleClasses.bgClass)
builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
if (line.styleClasses.textClass)
builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
}
// Ensure at least a single node is present, for measuring.
if (builder.map.length == 0)
builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
// Store the map and a cache object for the current logical line
if (i == 0) {
lineView.measure.map = builder.map;
lineView.measure.cache = {};
} else {
(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
(lineView.measure.caches || (lineView.measure.caches = [])).push({});
}
}
signal(cm, "renderLine", cm, lineView.line, builder.pre);
return builder;
}
function defaultSpecialCharPlaceholder(ch) {
var token = elt("span", "\u2022", "cm-invalidchar");
token.title = "\\u" + ch.charCodeAt(0).toString(16);
return token;
}
// Build up the DOM representation for a single token, and add it to
// the line map. Takes care to render special characters separately.
function buildToken(builder, text, style, startStyle, endStyle, title) {
if (!text) return;
var special = builder.cm.options.specialChars, mustWrap = false;
if (!special.test(text)) {
builder.col += text.length;
var content = document.createTextNode(text);
builder.map.push(builder.pos, builder.pos + text.length, content);
if (ie_upto8) mustWrap = true;
builder.pos += text.length;
} else {
var content = document.createDocumentFragment(), pos = 0;
while (true) {
special.lastIndex = pos;
var m = special.exec(text);
var skipped = m ? m.index - pos : text.length - pos;
if (skipped) {
var txt = document.createTextNode(text.slice(pos, pos + skipped));
if (ie_upto8) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.map.push(builder.pos, builder.pos + skipped, txt);
builder.col += skipped;
builder.pos += skipped;
}
if (!m) break;
pos += skipped + 1;
if (m[0] == "\t") {
var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
builder.col += tabWidth;
} else {
var txt = builder.cm.options.specialCharPlaceholder(m[0]);
if (ie_upto8) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.col += 1;
}
builder.map.push(builder.pos, builder.pos + 1, txt);
builder.pos++;
}
}
if (style || startStyle || endStyle || mustWrap) {
var fullStyle = style || "";
if (startStyle) fullStyle += startStyle;
if (endStyle) fullStyle += endStyle;
var token = elt("span", [content], fullStyle);
if (title) token.title = title;
return builder.content.appendChild(token);
}
builder.content.appendChild(content);
}
function buildTokenSplitSpaces(inner) {
function split(old) {
var out = " ";
for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
out += " ";
return out;
}
return function(builder, text, style, startStyle, endStyle, title) {
inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);
};
}
// Work around nonsense dimensions being reported for stretches of
// right-to-left text.
function buildTokenBadBidi(inner, order) {
return function(builder, text, style, startStyle, endStyle, title) {
style = style ? style + " cm-force-border" : "cm-force-border";
var start = builder.pos, end = start + text.length;
for (;;) {
// Find the part that overlaps with the start of this text
for (var i = 0; i < order.length; i++) {
var part = order[i];
if (part.to > start && part.from <= start) break;
}
if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);
inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);
startStyle = null;
text = text.slice(part.to - start);
start = part.to;
}
};
}
function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
var widget = !ignoreWidget && marker.widgetNode;
if (widget) {
builder.map.push(builder.pos, builder.pos + size, widget);
builder.content.appendChild(widget);
}
builder.pos += size;
}
// Outputs a number of spans to make up a line, taking highlighting
// and marked text into account.
function insertLineContent(line, builder, styles) {
var spans = line.markedSpans, allText = line.text, at = 0;
if (!spans) {
for (var i = 1; i < styles.length; i+=2)
builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
return;
}
var len = allText.length, pos = 0, i = 1, text = "", style;
var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
for (;;) {
if (nextChange == pos) { // Update current marker set
spanStyle = spanEndStyle = spanStartStyle = title = "";
collapsed = null; nextChange = Infinity;
var foundBookmarks = [];
for (var j = 0; j < spans.length; ++j) {
var sp = spans[j], m = sp.marker;
if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
if (m.className) spanStyle += " " + m.className;
if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
if (m.title && !title) title = m.title;
if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
collapsed = sp;
} else if (sp.from > pos && nextChange > sp.from) {
nextChange = sp.from;
}
if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);
}
if (collapsed && (collapsed.from || 0) == pos) {
buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
collapsed.marker, collapsed.from == null);
if (collapsed.to == null) return;
}
if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
buildCollapsedSpan(builder, 0, foundBookmarks[j]);
}
if (pos >= len) break;
var upto = Math.min(len, nextChange);
while (true) {
if (text) {
var end = pos + text.length;
if (!collapsed) {
var tokenText = end > upto ? text.slice(0, upto - pos) : text;
builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title);
}
if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
pos = end;
spanStartStyle = "";
}
text = allText.slice(at, at = styles[i++]);
style = interpretTokenStyle(styles[i++], builder.cm.options);
}
}
}
// DOCUMENT DATA STRUCTURE
// By default, updates that start and end at the beginning of a line
// are treated specially, in order to make the association of line
// widgets and marker elements with the text behave more intuitive.
function isWholeLineUpdate(doc, change) {
return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
(!doc.cm || doc.cm.options.wholeLineUpdateBefore);
}
// Perform a change on the document data structure.
function updateDoc(doc, change, markedSpans, estimateHeight) {
function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
function update(line, text, spans) {
updateLine(line, text, spans, estimateHeight);
signalLater(line, "change", line, change);
}
var from = change.from, to = change.to, text = change.text;
var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
// Adjust the line structure
if (isWholeLineUpdate(doc, change)) {
// This is a whole-line replace. Treated specially to make
// sure line objects move the way they are supposed to.
for (var i = 0, added = []; i < text.length - 1; ++i)
added.push(new Line(text[i], spansFor(i), estimateHeight));
update(lastLine, lastLine.text, lastSpans);
if (nlines) doc.remove(from.line, nlines);
if (added.length) doc.insert(from.line, added);
} else if (firstLine == lastLine) {
if (text.length == 1) {
update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
} else {
for (var added = [], i = 1; i < text.length - 1; ++i)
added.push(new Line(text[i], spansFor(i), estimateHeight));
added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
doc.insert(from.line + 1, added);
}
} else if (text.length == 1) {
update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
doc.remove(from.line + 1, nlines);
} else {
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
for (var i = 1, added = []; i < text.length - 1; ++i)
added.push(new Line(text[i], spansFor(i), estimateHeight));
if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
doc.insert(from.line + 1, added);
}
signalLater(doc, "change", doc, change);
}
// The document is represented as a BTree consisting of leaves, with
// chunk of lines in them, and branches, with up to ten leaves or
// other branch nodes below them. The top node is always a branch
// node, and is the document object itself (meaning it has
// additional methods and properties).
//
// All nodes have parent links. The tree is used both to go from
// line numbers to line objects, and to go from objects to numbers.
// It also indexes by height, and is used to convert between height
// and line object, and to find the total height of the document.
//
// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
function LeafChunk(lines) {
this.lines = lines;
this.parent = null;
for (var i = 0, height = 0; i < lines.length; ++i) {
lines[i].parent = this;
height += lines[i].height;
}
this.height = height;
}
LeafChunk.prototype = {
chunkSize: function() { return this.lines.length; },
// Remove the n lines at offset 'at'.
removeInner: function(at, n) {
for (var i = at, e = at + n; i < e; ++i) {
var line = this.lines[i];
this.height -= line.height;
cleanUpLine(line);
signalLater(line, "delete");
}
this.lines.splice(at, n);
},
// Helper used to collapse a small branch into a single leaf.
collapse: function(lines) {
lines.push.apply(lines, this.lines);
},
// Insert the given array of lines at offset 'at', count them as
// having the given height.
insertInner: function(at, lines, height) {
this.height += height;
this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
},
// Used to iterate over a part of the tree.
iterN: function(at, n, op) {
for (var e = at + n; at < e; ++at)
if (op(this.lines[at])) return true;
}
};
function BranchChunk(children) {
this.children = children;
var size = 0, height = 0;
for (var i = 0; i < children.length; ++i) {
var ch = children[i];
size += ch.chunkSize(); height += ch.height;
ch.parent = this;
}
this.size = size;
this.height = height;
this.parent = null;
}
BranchChunk.prototype = {
chunkSize: function() { return this.size; },
removeInner: function(at, n) {
this.size -= n;
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var rm = Math.min(n, sz - at), oldHeight = child.height;
child.removeInner(at, rm);
this.height -= oldHeight - child.height;
if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
if ((n -= rm) == 0) break;
at = 0;
} else at -= sz;
}
// If the result is smaller than 25 lines, ensure that it is a
// single leaf node.
if (this.size - n < 25 &&
(this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
var lines = [];
this.collapse(lines);
this.children = [new LeafChunk(lines)];
this.children[0].parent = this;
}
},
collapse: function(lines) {
for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
},
insertInner: function(at, lines, height) {
this.size += lines.length;
this.height += height;
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at <= sz) {
child.insertInner(at, lines, height);
if (child.lines && child.lines.length > 50) {
while (child.lines.length > 50) {
var spilled = child.lines.splice(child.lines.length - 25, 25);
var newleaf = new LeafChunk(spilled);
child.height -= newleaf.height;
this.children.splice(i + 1, 0, newleaf);
newleaf.parent = this;
}
this.maybeSpill();
}
break;
}
at -= sz;
}
},
// When a node has grown, check whether it should be split.
maybeSpill: function() {
if (this.children.length <= 10) return;
var me = this;
do {
var spilled = me.children.splice(me.children.length - 5, 5);
var sibling = new BranchChunk(spilled);
if (!me.parent) { // Become the parent node
var copy = new BranchChunk(me.children);
copy.parent = me;
me.children = [copy, sibling];
me = copy;
} else {
me.size -= sibling.size;
me.height -= sibling.height;
var myIndex = indexOf(me.parent.children, me);
me.parent.children.splice(myIndex + 1, 0, sibling);
}
sibling.parent = me.parent;
} while (me.children.length > 10);
me.parent.maybeSpill();
},
iterN: function(at, n, op) {
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var used = Math.min(n, sz - at);
if (child.iterN(at, used, op)) return true;
if ((n -= used) == 0) break;
at = 0;
} else at -= sz;
}
}
};
var nextDocId = 0;
var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
if (firstLine == null) firstLine = 0;
BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
this.first = firstLine;
this.scrollTop = this.scrollLeft = 0;
this.cantEdit = false;
this.cleanGeneration = 1;
this.frontier = firstLine;
var start = Pos(firstLine, 0);
this.sel = simpleSelection(start);
this.history = new History(null);
this.id = ++nextDocId;
this.modeOption = mode;
if (typeof text == "string") text = splitLines(text);
updateDoc(this, {from: start, to: start, text: text});
setSelection(this, simpleSelection(start), sel_dontScroll);
};
Doc.prototype = createObj(BranchChunk.prototype, {
constructor: Doc,
// Iterate over the document. Supports two forms -- with only one
// argument, it calls that for each line in the document. With
// three, it iterates over the range given by the first two (with
// the second being non-inclusive).
iter: function(from, to, op) {
if (op) this.iterN(from - this.first, to - from, op);
else this.iterN(this.first, this.first + this.size, from);
},
// Non-public interface for adding and removing lines.
insert: function(at, lines) {
var height = 0;
for (var i = 0; i < lines.length; ++i) height += lines[i].height;
this.insertInner(at - this.first, lines, height);
},
remove: function(at, n) { this.removeInner(at - this.first, n); },
// From here, the methods are part of the public interface. Most
// are also available from CodeMirror (editor) instances.
getValue: function(lineSep) {
var lines = getLines(this, this.first, this.first + this.size);
if (lineSep === false) return lines;
return lines.join(lineSep || "\n");
},
setValue: docMethodOp(function(code) {
var top = Pos(this.first, 0), last = this.first + this.size - 1;
makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
text: splitLines(code), origin: "setValue"}, true);
setSelection(this, simpleSelection(top));
}),
replaceRange: function(code, from, to, origin) {
from = clipPos(this, from);
to = to ? clipPos(this, to) : from;
replaceRange(this, code, from, to, origin);
},
getRange: function(from, to, lineSep) {
var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
if (lineSep === false) return lines;
return lines.join(lineSep || "\n");
},
getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
getLineNumber: function(line) {return lineNo(line);},
getLineHandleVisualStart: function(line) {
if (typeof line == "number") line = getLine(this, line);
return visualLine(line);
},
lineCount: function() {return this.size;},
firstLine: function() {return this.first;},
lastLine: function() {return this.first + this.size - 1;},
clipPos: function(pos) {return clipPos(this, pos);},
getCursor: function(start) {
var range = this.sel.primary(), pos;
if (start == null || start == "head") pos = range.head;
else if (start == "anchor") pos = range.anchor;
else if (start == "end" || start == "to" || start === false) pos = range.to();
else pos = range.from();
return pos;
},
listSelections: function() { return this.sel.ranges; },
somethingSelected: function() {return this.sel.somethingSelected();},
setCursor: docMethodOp(function(line, ch, options) {
setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
}),
setSelection: docMethodOp(function(anchor, head, options) {
setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
}),
extendSelection: docMethodOp(function(head, other, options) {
extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
}),
extendSelections: docMethodOp(function(heads, options) {
extendSelections(this, clipPosArray(this, heads, options));
}),
extendSelectionsBy: docMethodOp(function(f, options) {
extendSelections(this, map(this.sel.ranges, f), options);
}),
setSelections: docMethodOp(function(ranges, primary, options) {
if (!ranges.length) return;
for (var i = 0, out = []; i < ranges.length; i++)
out[i] = new Range(clipPos(this, ranges[i].anchor),
clipPos(this, ranges[i].head));
if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
setSelection(this, normalizeSelection(out, primary), options);
}),
addSelection: docMethodOp(function(anchor, head, options) {
var ranges = this.sel.ranges.slice(0);
ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
}),
getSelection: function(lineSep) {
var ranges = this.sel.ranges, lines;
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this, ranges[i].from(), ranges[i].to());
lines = lines ? lines.concat(sel) : sel;
}
if (lineSep === false) return lines;
else return lines.join(lineSep || "\n");
},
getSelections: function(lineSep) {
var parts = [], ranges = this.sel.ranges;
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this, ranges[i].from(), ranges[i].to());
if (lineSep !== false) sel = sel.join(lineSep || "\n");
parts[i] = sel;
}
return parts;
},
replaceSelection: function(code, collapse, origin) {
var dup = [];
for (var i = 0; i < this.sel.ranges.length; i++)
dup[i] = code;
this.replaceSelections(dup, collapse, origin || "+input");
},
replaceSelections: docMethodOp(function(code, collapse, origin) {
var changes = [], sel = this.sel;
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i];
changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
}
var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
for (var i = changes.length - 1; i >= 0; i--)
makeChange(this, changes[i]);
if (newSel) setSelectionReplaceHistory(this, newSel);
else if (this.cm) ensureCursorVisible(this.cm);
}),
undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
setExtending: function(val) {this.extend = val;},
getExtending: function() {return this.extend;},
historySize: function() {
var hist = this.history, done = 0, undone = 0;
for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
return {undo: done, redo: undone};
},
clearHistory: function() {this.history = new History(this.history.maxGeneration);},
markClean: function() {
this.cleanGeneration = this.changeGeneration(true);
},
changeGeneration: function(forceSplit) {
if (forceSplit)
this.history.lastOp = this.history.lastOrigin = null;
return this.history.generation;
},
isClean: function (gen) {
return this.history.generation == (gen || this.cleanGeneration);
},
getHistory: function() {
return {done: copyHistoryArray(this.history.done),
undone: copyHistoryArray(this.history.undone)};
},
setHistory: function(histData) {
var hist = this.history = new History(this.history.maxGeneration);
hist.done = copyHistoryArray(histData.done.slice(0), null, true);
hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
},
markText: function(from, to, options) {
return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
},
setBookmark: function(pos, options) {
var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
insertLeft: options && options.insertLeft,
clearWhenEmpty: false, shared: options && options.shared};
pos = clipPos(this, pos);
return markText(this, pos, pos, realOpts, "bookmark");
},
findMarksAt: function(pos) {
pos = clipPos(this, pos);
var markers = [], spans = getLine(this, pos.line).markedSpans;
if (spans) for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if ((span.from == null || span.from <= pos.ch) &&
(span.to == null || span.to >= pos.ch))
markers.push(span.marker.parent || span.marker);
}
return markers;
},
findMarks: function(from, to, filter) {
from = clipPos(this, from); to = clipPos(this, to);
var found = [], lineNo = from.line;
this.iter(from.line, to.line + 1, function(line) {
var spans = line.markedSpans;
if (spans) for (var i = 0; i < spans.length; i++) {
var span = spans[i];
if (!(lineNo == from.line && from.ch > span.to ||
span.from == null && lineNo != from.line||
lineNo == to.line && span.from > to.ch) &&
(!filter || filter(span.marker)))
found.push(span.marker.parent || span.marker);
}
++lineNo;
});
return found;
},
getAllMarks: function() {
var markers = [];
this.iter(function(line) {
var sps = line.markedSpans;
if (sps) for (var i = 0; i < sps.length; ++i)
if (sps[i].from != null) markers.push(sps[i].marker);
});
return markers;
},
posFromIndex: function(off) {
var ch, lineNo = this.first;
this.iter(function(line) {
var sz = line.text.length + 1;
if (sz > off) { ch = off; return true; }
off -= sz;
++lineNo;
});
return clipPos(this, Pos(lineNo, ch));
},
indexFromPos: function (coords) {
coords = clipPos(this, coords);
var index = coords.ch;
if (coords.line < this.first || coords.ch < 0) return 0;
this.iter(this.first, coords.line, function (line) {
index += line.text.length + 1;
});
return index;
},
copy: function(copyHistory) {
var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
doc.sel = this.sel;
doc.extend = false;
if (copyHistory) {
doc.history.undoDepth = this.history.undoDepth;
doc.setHistory(this.getHistory());
}
return doc;
},
linkedDoc: function(options) {
if (!options) options = {};
var from = this.first, to = this.first + this.size;
if (options.from != null && options.from > from) from = options.from;
if (options.to != null && options.to < to) to = options.to;
var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
if (options.sharedHist) copy.history = this.history;
(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
copySharedMarkers(copy, findSharedMarkers(this));
return copy;
},
unlinkDoc: function(other) {
if (other instanceof CodeMirror) other = other.doc;
if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
var link = this.linked[i];
if (link.doc != other) continue;
this.linked.splice(i, 1);
other.unlinkDoc(this);
detachSharedMarkers(findSharedMarkers(this));
break;
}
// If the histories were shared, split them again
if (other.history == this.history) {
var splitIds = [other.id];
linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
other.history = new History(null);
other.history.done = copyHistoryArray(this.history.done, splitIds);
other.history.undone = copyHistoryArray(this.history.undone, splitIds);
}
},
iterLinkedDocs: function(f) {linkedDocs(this, f);},
getMode: function() {return this.mode;},
getEditor: function() {return this.cm;}
});
// Public alias.
Doc.prototype.eachLine = Doc.prototype.iter;
// Set up methods on CodeMirror's prototype to redirect to the editor's document.
var dontDelegate = "iter insert remove copy getEditor".split(" ");
for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
CodeMirror.prototype[prop] = (function(method) {
return function() {return method.apply(this.doc, arguments);};
})(Doc.prototype[prop]);
eventMixin(Doc);
// Call f for all linked documents.
function linkedDocs(doc, f, sharedHistOnly) {
function propagate(doc, skip, sharedHist) {
if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
var rel = doc.linked[i];
if (rel.doc == skip) continue;
var shared = sharedHist && rel.sharedHist;
if (sharedHistOnly && !shared) continue;
f(rel.doc, shared);
propagate(rel.doc, doc, shared);
}
}
propagate(doc, null, true);
}
// Attach a document to an editor.
function attachDoc(cm, doc) {
if (doc.cm) throw new Error("This document is already in use.");
cm.doc = doc;
doc.cm = cm;
estimateLineHeights(cm);
loadMode(cm);
if (!cm.options.lineWrapping) findMaxLine(cm);
cm.options.mode = doc.modeOption;
regChange(cm);
}
// LINE UTILITIES
// Find the line object corresponding to the given line number.
function getLine(doc, n) {
n -= doc.first;
if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
for (var chunk = doc; !chunk.lines;) {
for (var i = 0;; ++i) {
var child = chunk.children[i], sz = child.chunkSize();
if (n < sz) { chunk = child; break; }
n -= sz;
}
}
return chunk.lines[n];
}
// Get the part of a document between two positions, as an array of
// strings.
function getBetween(doc, start, end) {
var out = [], n = start.line;
doc.iter(start.line, end.line + 1, function(line) {
var text = line.text;
if (n == end.line) text = text.slice(0, end.ch);
if (n == start.line) text = text.slice(start.ch);
out.push(text);
++n;
});
return out;
}
// Get the lines between from and to, as array of strings.
function getLines(doc, from, to) {
var out = [];
doc.iter(from, to, function(line) { out.push(line.text); });
return out;
}
// Update the height of a line, propagating the height change
// upwards to parent nodes.
function updateLineHeight(line, height) {
var diff = height - line.height;
if (diff) for (var n = line; n; n = n.parent) n.height += diff;
}
// Given a line object, find its line number by walking up through
// its parent links.
function lineNo(line) {
if (line.parent == null) return null;
var cur = line.parent, no = indexOf(cur.lines, line);
for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
for (var i = 0;; ++i) {
if (chunk.children[i] == cur) break;
no += chunk.children[i].chunkSize();
}
}
return no + cur.first;
}
// Find the line at the given vertical position, using the height
// information in the document tree.
function lineAtHeight(chunk, h) {
var n = chunk.first;
outer: do {
for (var i = 0; i < chunk.children.length; ++i) {
var child = chunk.children[i], ch = child.height;
if (h < ch) { chunk = child; continue outer; }
h -= ch;
n += child.chunkSize();
}
return n;
} while (!chunk.lines);
for (var i = 0; i < chunk.lines.length; ++i) {
var line = chunk.lines[i], lh = line.height;
if (h < lh) break;
h -= lh;
}
return n + i;
}
// Find the height above the given line.
function heightAtLine(lineObj) {
lineObj = visualLine(lineObj);
var h = 0, chunk = lineObj.parent;
for (var i = 0; i < chunk.lines.length; ++i) {
var line = chunk.lines[i];
if (line == lineObj) break;
else h += line.height;
}
for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
for (var i = 0; i < p.children.length; ++i) {
var cur = p.children[i];
if (cur == chunk) break;
else h += cur.height;
}
}
return h;
}
// Get the bidi ordering for the given line (and cache it). Returns
// false for lines that are fully left-to-right, and an array of
// BidiSpan objects otherwise.
function getOrder(line) {
var order = line.order;
if (order == null) order = line.order = bidiOrdering(line.text);
return order;
}
// HISTORY
function History(startGen) {
// Arrays of change events and selections. Doing something adds an
// event to done and clears undo. Undoing moves events from done
// to undone, redoing moves them in the other direction.
this.done = []; this.undone = [];
this.undoDepth = Infinity;
// Used to track when changes can be merged into a single undo
// event
this.lastModTime = this.lastSelTime = 0;
this.lastOp = null;
this.lastOrigin = this.lastSelOrigin = null;
// Used by the isClean() method
this.generation = this.maxGeneration = startGen || 1;
}
// Create a history change event from an updateDoc-style change
// object.
function historyChangeFromChange(doc, change) {
var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
return histChange;
}
// Pop all selection events off the end of a history array. Stop at
// a change event.
function clearSelectionEvents(array) {
while (array.length) {
var last = lst(array);
if (last.ranges) array.pop();
else break;
}
}
// Find the top change event in the history. Pop off selection
// events that are in the way.
function lastChangeEvent(hist, force) {
if (force) {
clearSelectionEvents(hist.done);
return lst(hist.done);
} else if (hist.done.length && !lst(hist.done).ranges) {
return lst(hist.done);
} else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
hist.done.pop();
return lst(hist.done);
}
}
// Register a change in the history. Merges changes that are within
// a single operation, ore are close together with an origin that
// allows merging (starting with "+") into a single event.
function addChangeToHistory(doc, change, selAfter, opId) {
var hist = doc.history;
hist.undone.length = 0;
var time = +new Date, cur;
if ((hist.lastOp == opId ||
hist.lastOrigin == change.origin && change.origin &&
((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
change.origin.charAt(0) == "*")) &&
(cur = lastChangeEvent(hist, hist.lastOp == opId))) {
// Merge this change into the last event
var last = lst(cur.changes);
if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
// Optimized case for simple insertion -- don't want to add
// new changesets for every character typed
last.to = changeEnd(change);
} else {
// Add new sub-event
cur.changes.push(historyChangeFromChange(doc, change));
}
} else {
// Can not be merged, start a new event.
var before = lst(hist.done);
if (!before || !before.ranges)
pushSelectionToHistory(doc.sel, hist.done);
cur = {changes: [historyChangeFromChange(doc, change)],
generation: hist.generation};
hist.done.push(cur);
while (hist.done.length > hist.undoDepth) {
hist.done.shift();
if (!hist.done[0].ranges) hist.done.shift();
}
}
hist.done.push(selAfter);
hist.generation = ++hist.maxGeneration;
hist.lastModTime = hist.lastSelTime = time;
hist.lastOp = opId;
hist.lastOrigin = hist.lastSelOrigin = change.origin;
if (!last) signal(doc, "historyAdded");
}
function selectionEventCanBeMerged(doc, origin, prev, sel) {
var ch = origin.charAt(0);
return ch == "*" ||
ch == "+" &&
prev.ranges.length == sel.ranges.length &&
prev.somethingSelected() == sel.somethingSelected() &&
new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
}
// Called whenever the selection changes, sets the new selection as
// the pending selection in the history, and pushes the old pending
// selection into the 'done' array when it was significantly
// different (in number of selected ranges, emptiness, or time).
function addSelectionToHistory(doc, sel, opId, options) {
var hist = doc.history, origin = options && options.origin;
// A new event is started when the previous origin does not match
// the current, or the origins don't allow matching. Origins
// starting with * are always merged, those starting with + are
// merged when similar and close together in time.
if (opId == hist.lastOp ||
(origin && hist.lastSelOrigin == origin &&
(hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
hist.done[hist.done.length - 1] = sel;
else
pushSelectionToHistory(sel, hist.done);
hist.lastSelTime = +new Date;
hist.lastSelOrigin = origin;
hist.lastOp = opId;
if (options && options.clearRedo !== false)
clearSelectionEvents(hist.undone);
}
function pushSelectionToHistory(sel, dest) {
var top = lst(dest);
if (!(top && top.ranges && top.equals(sel)))
dest.push(sel);
}
// Used to store marked span information in the history.
function attachLocalSpans(doc, change, from, to) {
var existing = change["spans_" + doc.id], n = 0;
doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
if (line.markedSpans)
(existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
++n;
});
}
// When un/re-doing restores text containing marked spans, those
// that have been explicitly cleared should not be restored.
function removeClearedSpans(spans) {
if (!spans) return null;
for (var i = 0, out; i < spans.length; ++i) {
if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
else if (out) out.push(spans[i]);
}
return !out ? spans : out.length ? out : null;
}
// Retrieve and filter the old marked spans stored in a change event.
function getOldSpans(doc, change) {
var found = change["spans_" + doc.id];
if (!found) return null;
for (var i = 0, nw = []; i < change.text.length; ++i)
nw.push(removeClearedSpans(found[i]));
return nw;
}
// Used both to provide a JSON-safe object in .getHistory, and, when
// detaching a document, to split the history in two
function copyHistoryArray(events, newGroup, instantiateSel) {
for (var i = 0, copy = []; i < events.length; ++i) {
var event = events[i];
if (event.ranges) {
copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
continue;
}
var changes = event.changes, newChanges = [];
copy.push({changes: newChanges});
for (var j = 0; j < changes.length; ++j) {
var change = changes[j], m;
newChanges.push({from: change.from, to: change.to, text: change.text});
if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
if (indexOf(newGroup, Number(m[1])) > -1) {
lst(newChanges)[prop] = change[prop];
delete change[prop];
}
}
}
}
return copy;
}
// Rebasing/resetting history to deal with externally-sourced changes
function rebaseHistSelSingle(pos, from, to, diff) {
if (to < pos.line) {
pos.line += diff;
} else if (from < pos.line) {
pos.line = from;
pos.ch = 0;
}
}
// Tries to rebase an array of history events given a change in the
// document. If the change touches the same lines as the event, the
// event, and everything 'behind' it, is discarded. If the change is
// before the event, the event's positions are updated. Uses a
// copy-on-write scheme for the positions, to avoid having to
// reallocate them all on every rebase, but also avoid problems with
// shared position objects being unsafely updated.
function rebaseHistArray(array, from, to, diff) {
for (var i = 0; i < array.length; ++i) {
var sub = array[i], ok = true;
if (sub.ranges) {
if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
for (var j = 0; j < sub.ranges.length; j++) {
rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
}
continue;
}
for (var j = 0; j < sub.changes.length; ++j) {
var cur = sub.changes[j];
if (to < cur.from.line) {
cur.from = Pos(cur.from.line + diff, cur.from.ch);
cur.to = Pos(cur.to.line + diff, cur.to.ch);
} else if (from <= cur.to.line) {
ok = false;
break;
}
}
if (!ok) {
array.splice(0, i + 1);
i = 0;
}
}
}
function rebaseHist(hist, change) {
var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
rebaseHistArray(hist.done, from, to, diff);
rebaseHistArray(hist.undone, from, to, diff);
}
// EVENT UTILITIES
// Due to the fact that we still support jurassic IE versions, some
// compatibility wrappers are needed.
var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
};
var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
};
function e_defaultPrevented(e) {
return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
}
var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
function e_target(e) {return e.target || e.srcElement;}
function e_button(e) {
var b = e.which;
if (b == null) {
if (e.button & 1) b = 1;
else if (e.button & 2) b = 3;
else if (e.button & 4) b = 2;
}
if (mac && e.ctrlKey && b == 1) b = 3;
return b;
}
// EVENT HANDLING
// Lightweight event framework. on/off also work on DOM nodes,
// registering native DOM handlers.
var on = CodeMirror.on = function(emitter, type, f) {
if (emitter.addEventListener)
emitter.addEventListener(type, f, false);
else if (emitter.attachEvent)
emitter.attachEvent("on" + type, f);
else {
var map = emitter._handlers || (emitter._handlers = {});
var arr = map[type] || (map[type] = []);
arr.push(f);
}
};
var off = CodeMirror.off = function(emitter, type, f) {
if (emitter.removeEventListener)
emitter.removeEventListener(type, f, false);
else if (emitter.detachEvent)
emitter.detachEvent("on" + type, f);
else {
var arr = emitter._handlers && emitter._handlers[type];
if (!arr) return;
for (var i = 0; i < arr.length; ++i)
if (arr[i] == f) { arr.splice(i, 1); break; }
}
};
var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
var arr = emitter._handlers && emitter._handlers[type];
if (!arr) return;
var args = Array.prototype.slice.call(arguments, 2);
for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
};
// Often, we want to signal events at a point where we are in the
// middle of some work, but don't want the handler to start calling
// other methods on the editor, which might be in an inconsistent
// state or simply not expect any other events to happen.
// signalLater looks whether there are any handlers, and schedules
// them to be executed when the last operation ends, or, if no
// operation is active, when a timeout fires.
var delayedCallbacks, delayedCallbackDepth = 0;
function signalLater(emitter, type /*, values...*/) {
var arr = emitter._handlers && emitter._handlers[type];
if (!arr) return;
var args = Array.prototype.slice.call(arguments, 2);
if (!delayedCallbacks) {
++delayedCallbackDepth;
delayedCallbacks = [];
setTimeout(fireDelayed, 0);
}
function bnd(f) {return function(){f.apply(null, args);};};
for (var i = 0; i < arr.length; ++i)
delayedCallbacks.push(bnd(arr[i]));
}
function fireDelayed() {
--delayedCallbackDepth;
var delayed = delayedCallbacks;
delayedCallbacks = null;
for (var i = 0; i < delayed.length; ++i) delayed[i]();
}
// The DOM events that CodeMirror handles can be overridden by
// registering a (non-DOM) handler on the editor for the event name,
// and preventDefault-ing the event in that handler.
function signalDOMEvent(cm, e, override) {
signal(cm, override || e.type, cm, e);
return e_defaultPrevented(e) || e.codemirrorIgnore;
}
function signalCursorActivity(cm) {
var arr = cm._handlers && cm._handlers.cursorActivity;
if (!arr) return;
var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
set.push(arr[i]);
}
function hasHandler(emitter, type) {
var arr = emitter._handlers && emitter._handlers[type];
return arr && arr.length > 0;
}
// Add on and off methods to a constructor's prototype, to make
// registering events on such objects more convenient.
function eventMixin(ctor) {
ctor.prototype.on = function(type, f) {on(this, type, f);};
ctor.prototype.off = function(type, f) {off(this, type, f);};
}
// MISC UTILITIES
// Number of pixels added to scroller and sizer to hide scrollbar
var scrollerCutOff = 30;
// Returned or thrown by various protocols to signal 'I'm not
// handling this'.
var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
// Reused option objects for setSelection & friends
var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
function Delayed() {this.id = null;}
Delayed.prototype.set = function(ms, f) {
clearTimeout(this.id);
this.id = setTimeout(f, ms);
};
// Counts the column offset in a string, taking tabs into account.
// Used mostly to find indentation.
var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
if (end == null) {
end = string.search(/[^\s\u00a0]/);
if (end == -1) end = string.length;
}
for (var i = startIndex || 0, n = startValue || 0;;) {
var nextTab = string.indexOf("\t", i);
if (nextTab < 0 || nextTab >= end)
return n + (end - i);
n += nextTab - i;
n += tabSize - (n % tabSize);
i = nextTab + 1;
}
};
// The inverse of countColumn -- find the offset that corresponds to
// a particular column.
function findColumn(string, goal, tabSize) {
for (var pos = 0, col = 0;;) {
var nextTab = string.indexOf("\t", pos);
if (nextTab == -1) nextTab = string.length;
var skipped = nextTab - pos;
if (nextTab == string.length || col + skipped >= goal)
return pos + Math.min(skipped, goal - col);
col += nextTab - pos;
col += tabSize - (col % tabSize);
pos = nextTab + 1;
if (col >= goal) return pos;
}
}
var spaceStrs = [""];
function spaceStr(n) {
while (spaceStrs.length <= n)
spaceStrs.push(lst(spaceStrs) + " ");
return spaceStrs[n];
}
function lst(arr) { return arr[arr.length-1]; }
var selectInput = function(node) { node.select(); };
if (ios) // Mobile Safari apparently has a bug where select() is broken.
selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
else if (ie) // Suppress mysterious IE10 errors
selectInput = function(node) { try { node.select(); } catch(_e) {} };
function indexOf(array, elt) {
for (var i = 0; i < array.length; ++i)
if (array[i] == elt) return i;
return -1;
}
if ([].indexOf) indexOf = function(array, elt) { return array.indexOf(elt); };
function map(array, f) {
var out = [];
for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
return out;
}
if ([].map) map = function(array, f) { return array.map(f); };
function createObj(base, props) {
var inst;
if (Object.create) {
inst = Object.create(base);
} else {
var ctor = function() {};
ctor.prototype = base;
inst = new ctor();
}
if (props) copyObj(props, inst);
return inst;
};
function copyObj(obj, target, overwrite) {
if (!target) target = {};
for (var prop in obj)
if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
target[prop] = obj[prop];
return target;
}
function bind(f) {
var args = Array.prototype.slice.call(arguments, 1);
return function(){return f.apply(null, args);};
}
var nonASCIISingleCaseWordChar = /[\u00df\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
return /\w/.test(ch) || ch > "\x80" &&
(ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
};
function isWordChar(ch, helper) {
if (!helper) return isWordCharBasic(ch);
if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
return helper.test(ch);
}
function isEmpty(obj) {
for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
return true;
}
// Extending unicode characters. A series of a non-extending char +
// any number of extending chars is treated as a single unit as far
// as editing and measuring is concerned. This is not fully correct,
// since some scripts/fonts/browsers also treat other configurations
// of code points as a group.
var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
// DOM UTILITIES
function elt(tag, content, className, style) {
var e = document.createElement(tag);
if (className) e.className = className;
if (style) e.style.cssText = style;
if (typeof content == "string") e.appendChild(document.createTextNode(content));
else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
return e;
}
var range;
if (document.createRange) range = function(node, start, end) {
var r = document.createRange();
r.setEnd(node, end);
r.setStart(node, start);
return r;
};
else range = function(node, start, end) {
var r = document.body.createTextRange();
r.moveToElementText(node.parentNode);
r.collapse(true);
r.moveEnd("character", end);
r.moveStart("character", start);
return r;
};
function removeChildren(e) {
for (var count = e.childNodes.length; count > 0; --count)
e.removeChild(e.firstChild);
return e;
}
function removeChildrenAndAdd(parent, e) {
return removeChildren(parent).appendChild(e);
}
function contains(parent, child) {
if (parent.contains)
return parent.contains(child);
while (child = child.parentNode)
if (child == parent) return true;
}
function activeElt() { return document.activeElement; }
// Older versions of IE throws unspecified error when touching
// document.activeElement in some cases (during loading, in iframe)
if (ie_upto10) activeElt = function() {
try { return document.activeElement; }
catch(e) { return document.body; }
};
function classTest(cls) { return new RegExp("\\b" + cls + "\\b\\s*"); }
function rmClass(node, cls) {
var test = classTest(cls);
if (test.test(node.className)) node.className = node.className.replace(test, "");
}
function addClass(node, cls) {
if (!classTest(cls).test(node.className)) node.className += " " + cls;
}
function joinClasses(a, b) {
var as = a.split(" ");
for (var i = 0; i < as.length; i++)
if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
return b;
}
// WINDOW-WIDE EVENTS
// These must be handled carefully, because naively registering a
// handler for each editor will cause the editors to never be
// garbage collected.
function forEachCodeMirror(f) {
if (!document.body.getElementsByClassName) return;
var byClass = document.body.getElementsByClassName("CodeMirror");
for (var i = 0; i < byClass.length; i++) {
var cm = byClass[i].CodeMirror;
if (cm) f(cm);
}
}
var globalsRegistered = false;
function ensureGlobalHandlers() {
if (globalsRegistered) return;
registerGlobalHandlers();
globalsRegistered = true;
}
function registerGlobalHandlers() {
// When the window resizes, we need to refresh active editors.
var resizeTimer;
on(window, "resize", function() {
if (resizeTimer == null) resizeTimer = setTimeout(function() {
resizeTimer = null;
knownScrollbarWidth = null;
forEachCodeMirror(onResize);
}, 100);
});
// When the window loses focus, we want to show the editor as blurred
on(window, "blur", function() {
forEachCodeMirror(onBlur);
});
}
// FEATURE DETECTION
// Detect drag-and-drop
var dragAndDrop = function() {
// There is *some* kind of drag-and-drop support in IE6-8, but I
// couldn't get it to work yet.
if (ie_upto8) return false;
var div = elt('div');
return "draggable" in div || "dragDrop" in div;
}();
var knownScrollbarWidth;
function scrollbarWidth(measure) {
if (knownScrollbarWidth != null) return knownScrollbarWidth;
var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
removeChildrenAndAdd(measure, test);
if (test.offsetWidth)
knownScrollbarWidth = test.offsetHeight - test.clientHeight;
return knownScrollbarWidth || 0;
}
var zwspSupported;
function zeroWidthElement(measure) {
if (zwspSupported == null) {
var test = elt("span", "\u200b");
removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
if (measure.firstChild.offsetHeight != 0)
zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_upto7;
}
if (zwspSupported) return elt("span", "\u200b");
else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
}
// Feature-detect IE's crummy client rect reporting for bidi text
var badBidiRects;
function hasBadBidiRects(measure) {
if (badBidiRects != null) return badBidiRects;
var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
var r0 = range(txt, 0, 1).getBoundingClientRect();
if (r0.left == r0.right) return false;
var r1 = range(txt, 1, 2).getBoundingClientRect();
return badBidiRects = (r1.right - r0.right < 3);
}
// See if "".split is the broken IE version, if so, provide an
// alternative way to split lines.
var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
var pos = 0, result = [], l = string.length;
while (pos <= l) {
var nl = string.indexOf("\n", pos);
if (nl == -1) nl = string.length;
var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
var rt = line.indexOf("\r");
if (rt != -1) {
result.push(line.slice(0, rt));
pos += rt + 1;
} else {
result.push(line);
pos = nl + 1;
}
}
return result;
} : function(string){return string.split(/\r\n?|\n/);};
var hasSelection = window.getSelection ? function(te) {
try { return te.selectionStart != te.selectionEnd; }
catch(e) { return false; }
} : function(te) {
try {var range = te.ownerDocument.selection.createRange();}
catch(e) {}
if (!range || range.parentElement() != te) return false;
return range.compareEndPoints("StartToEnd", range) != 0;
};
var hasCopyEvent = (function() {
var e = elt("div");
if ("oncopy" in e) return true;
e.setAttribute("oncopy", "return;");
return typeof e.oncopy == "function";
})();
// KEY NAMES
var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
CodeMirror.keyNames = keyNames;
(function() {
// Number keys
for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
// Alphabetic keys
for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
// Function keys
for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
})();
// BIDI HELPERS
function iterateBidiSections(order, from, to, f) {
if (!order) return f(from, to, "ltr");
var found = false;
for (var i = 0; i < order.length; ++i) {
var part = order[i];
if (part.from < to && part.to > from || from == to && part.to == from) {
f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
found = true;
}
}
if (!found) f(from, to, "ltr");
}
function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
function lineRight(line) {
var order = getOrder(line);
if (!order) return line.text.length;
return bidiRight(lst(order));
}
function lineStart(cm, lineN) {
var line = getLine(cm.doc, lineN);
var visual = visualLine(line);
if (visual != line) lineN = lineNo(visual);
var order = getOrder(visual);
var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
return Pos(lineN, ch);
}
function lineEnd(cm, lineN) {
var merged, line = getLine(cm.doc, lineN);
while (merged = collapsedSpanAtEnd(line)) {
line = merged.find(1, true).line;
lineN = null;
}
var order = getOrder(line);
var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
return Pos(lineN == null ? lineNo(line) : lineN, ch);
}
function compareBidiLevel(order, a, b) {
var linedir = order[0].level;
if (a == linedir) return true;
if (b == linedir) return false;
return a < b;
}
var bidiOther;
function getBidiPartAt(order, pos) {
bidiOther = null;
for (var i = 0, found; i < order.length; ++i) {
var cur = order[i];
if (cur.from < pos && cur.to > pos) return i;
if ((cur.from == pos || cur.to == pos)) {
if (found == null) {
found = i;
} else if (compareBidiLevel(order, cur.level, order[found].level)) {
if (cur.from != cur.to) bidiOther = found;
return i;
} else {
if (cur.from != cur.to) bidiOther = i;
return found;
}
}
}
return found;
}
function moveInLine(line, pos, dir, byUnit) {
if (!byUnit) return pos + dir;
do pos += dir;
while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
return pos;
}
// This is needed in order to move 'visually' through bi-directional
// text -- i.e., pressing left should make the cursor go left, even
// when in RTL text. The tricky part is the 'jumps', where RTL and
// LTR text touch each other. This often requires the cursor offset
// to move more than one unit, in order to visually move one unit.
function moveVisually(line, start, dir, byUnit) {
var bidi = getOrder(line);
if (!bidi) return moveLogically(line, start, dir, byUnit);
var pos = getBidiPartAt(bidi, start), part = bidi[pos];
var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
for (;;) {
if (target > part.from && target < part.to) return target;
if (target == part.from || target == part.to) {
if (getBidiPartAt(bidi, target) == pos) return target;
part = bidi[pos += dir];
return (dir > 0) == part.level % 2 ? part.to : part.from;
} else {
part = bidi[pos += dir];
if (!part) return null;
if ((dir > 0) == part.level % 2)
target = moveInLine(line, part.to, -1, byUnit);
else
target = moveInLine(line, part.from, 1, byUnit);
}
}
}
function moveLogically(line, start, dir, byUnit) {
var target = start + dir;
if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
return target < 0 || target > line.text.length ? null : target;
}
// Bidirectional ordering algorithm
// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
// that this (partially) implements.
// One-char codes used for character types:
// L (L): Left-to-Right
// R (R): Right-to-Left
// r (AL): Right-to-Left Arabic
// 1 (EN): European Number
// + (ES): European Number Separator
// % (ET): European Number Terminator
// n (AN): Arabic Number
// , (CS): Common Number Separator
// m (NSM): Non-Spacing Mark
// b (BN): Boundary Neutral
// s (B): Paragraph Separator
// t (S): Segment Separator
// w (WS): Whitespace
// N (ON): Other Neutrals
// Returns null if characters are ordered as they appear
// (left-to-right), or an array of sections ({from, to, level}
// objects) in the order in which they occur visually.
var bidiOrdering = (function() {
// Character types for codepoints 0 to 0xff
var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
// Character types for codepoints 0x600 to 0x6ff
var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
function charType(code) {
if (code <= 0xf7) return lowTypes.charAt(code);
else if (0x590 <= code && code <= 0x5f4) return "R";
else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
else if (0x6ee <= code && code <= 0x8ac) return "r";
else if (0x2000 <= code && code <= 0x200b) return "w";
else if (code == 0x200c) return "b";
else return "L";
}
var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
// Browsers seem to always treat the boundaries of block elements as being L.
var outerType = "L";
function BidiSpan(level, from, to) {
this.level = level;
this.from = from; this.to = to;
}
return function(str) {
if (!bidiRE.test(str)) return false;
var len = str.length, types = [];
for (var i = 0, type; i < len; ++i)
types.push(type = charType(str.charCodeAt(i)));
// W1. Examine each non-spacing mark (NSM) in the level run, and
// change the type of the NSM to the type of the previous
// character. If the NSM is at the start of the level run, it will
// get the type of sor.
for (var i = 0, prev = outerType; i < len; ++i) {
var type = types[i];
if (type == "m") types[i] = prev;
else prev = type;
}
// W2. Search backwards from each instance of a European number
// until the first strong type (R, L, AL, or sor) is found. If an
// AL is found, change the type of the European number to Arabic
// number.
// W3. Change all ALs to R.
for (var i = 0, cur = outerType; i < len; ++i) {
var type = types[i];
if (type == "1" && cur == "r") types[i] = "n";
else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
}
// W4. A single European separator between two European numbers
// changes to a European number. A single common separator between
// two numbers of the same type changes to that type.
for (var i = 1, prev = types[0]; i < len - 1; ++i) {
var type = types[i];
if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
else if (type == "," && prev == types[i+1] &&
(prev == "1" || prev == "n")) types[i] = prev;
prev = type;
}
// W5. A sequence of European terminators adjacent to European
// numbers changes to all European numbers.
// W6. Otherwise, separators and terminators change to Other
// Neutral.
for (var i = 0; i < len; ++i) {
var type = types[i];
if (type == ",") types[i] = "N";
else if (type == "%") {
for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
for (var j = i; j < end; ++j) types[j] = replace;
i = end - 1;
}
}
// W7. Search backwards from each instance of a European number
// until the first strong type (R, L, or sor) is found. If an L is
// found, then change the type of the European number to L.
for (var i = 0, cur = outerType; i < len; ++i) {
var type = types[i];
if (cur == "L" && type == "1") types[i] = "L";
else if (isStrong.test(type)) cur = type;
}
// N1. A sequence of neutrals takes the direction of the
// surrounding strong text if the text on both sides has the same
// direction. European and Arabic numbers act as if they were R in
// terms of their influence on neutrals. Start-of-level-run (sor)
// and end-of-level-run (eor) are used at level run boundaries.
// N2. Any remaining neutrals take the embedding direction.
for (var i = 0; i < len; ++i) {
if (isNeutral.test(types[i])) {
for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
var before = (i ? types[i-1] : outerType) == "L";
var after = (end < len ? types[end] : outerType) == "L";
var replace = before || after ? "L" : "R";
for (var j = i; j < end; ++j) types[j] = replace;
i = end - 1;
}
}
// Here we depart from the documented algorithm, in order to avoid
// building up an actual levels array. Since there are only three
// levels (0, 1, 2) in an implementation that doesn't take
// explicit embedding into account, we can build up the order on
// the fly, without following the level-based algorithm.
var order = [], m;
for (var i = 0; i < len;) {
if (countsAsLeft.test(types[i])) {
var start = i;
for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
order.push(new BidiSpan(0, start, i));
} else {
var pos = i, at = order.length;
for (++i; i < len && types[i] != "L"; ++i) {}
for (var j = pos; j < i;) {
if (countsAsNum.test(types[j])) {
if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
var nstart = j;
for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
order.splice(at, 0, new BidiSpan(2, nstart, j));
pos = j;
} else ++j;
}
if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
}
}
if (order[0].level == 1 && (m = str.match(/^\s+/))) {
order[0].from = m[0].length;
order.unshift(new BidiSpan(0, 0, m[0].length));
}
if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
lst(order).to -= m[0].length;
order.push(new BidiSpan(0, len - m[0].length, len));
}
if (order[0].level != lst(order).level)
order.push(new BidiSpan(order[0].level, len, len));
return order;
};
})();
// THE END
CodeMirror.version = "4.1.1";
return CodeMirror;
});
// TODO actually recognize syntax of TypeScript constructs
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("javascript", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var statementIndent = parserConfig.statementIndent;
var jsonldMode = parserConfig.jsonld;
var jsonMode = parserConfig.json || jsonldMode;
var isTS = parserConfig.typescript;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
var operator = kw("operator"), atom = {type: "atom", style: "atom"};
var jsKeywords = {
"if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
"return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C,
"var": kw("var"), "const": kw("var"), "let": kw("var"),
"function": kw("function"), "catch": kw("catch"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "typeof": operator, "instanceof": operator,
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
"this": kw("this"), "module": kw("module"), "class": kw("class"), "super": kw("atom"),
"yield": C, "export": kw("export"), "import": kw("import"), "extends": C
};
// Extend the 'normal' keywords with the TypeScript language extensions
if (isTS) {
var type = {type: "variable", style: "variable-3"};
var tsKeywords = {
// object-like things
"interface": kw("interface"),
"extends": kw("extends"),
"constructor": kw("constructor"),
// scope modifiers
"public": kw("public"),
"private": kw("private"),
"protected": kw("protected"),
"static": kw("static"),
// types
"string": type, "number": type, "bool": type, "any": type
};
for (var attr in tsKeywords) {
jsKeywords[attr] = tsKeywords[attr];
}
}
return jsKeywords;
}();
var isOperatorChar = /[+\-*&%=<>!?|~^]/;
var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
function readRegexp(stream) {
var escaped = false, next, inSet = false;
while ((next = stream.next()) != null) {
if (!escaped) {
if (next == "/" && !inSet) return;
if (next == "[") inSet = true;
else if (inSet && next == "]") inSet = false;
}
escaped = !escaped && next == "\\";
}
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
return ret("number", "number");
} else if (ch == "." && stream.match("..")) {
return ret("spread", "meta");
} else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
return ret(ch);
} else if (ch == "=" && stream.eat(">")) {
return ret("=>", "operator");
} else if (ch == "0" && stream.eat(/x/i)) {
stream.eatWhile(/[\da-f]/i);
return ret("number", "number");
} else if (/\d/.test(ch)) {
stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
return ret("number", "number");
} else if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
} else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
} else if (state.lastType == "operator" || state.lastType == "keyword c" ||
state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) {
readRegexp(stream);
stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
return ret("regexp", "string-2");
} else {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator", stream.current());
}
} else if (ch == "`") {
state.tokenize = tokenQuasi;
return tokenQuasi(stream, state);
} else if (ch == "#") {
stream.skipToEnd();
return ret("error", "error");
} else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator", stream.current());
} else {
stream.eatWhile(/[\w\$_]/);
var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
ret("variable", "variable", word);
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next;
if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
state.tokenize = tokenBase;
return ret("jsonld-keyword", "meta");
}
while ((next = stream.next()) != null) {
if (next == quote && !escaped) break;
escaped = !escaped && next == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenQuasi(stream, state) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && next == "\\";
}
return ret("quasi", "string-2", stream.current());
}
var brackets = "([{}])";
// This is a crude lookahead trick to try and notice that we're
// parsing the argument patterns for a fat-arrow function before we
// actually hit the arrow token. It only works if the arrow is on
// the same line as the arguments and there's no strange noise
// (comments) in between. Fallback is to only notice when we hit the
// arrow, and not declare the arguments as locals for the arrow
// body.
function findFatArrow(stream, state) {
if (state.fatArrowAt) state.fatArrowAt = null;
var arrow = stream.string.indexOf("=>", stream.start);
if (arrow < 0) return;
var depth = 0, sawSomething = false;
for (var pos = arrow - 1; pos >= 0; --pos) {
var ch = stream.string.charAt(pos);
var bracket = brackets.indexOf(ch);
if (bracket >= 0 && bracket < 3) {
if (!depth) { ++pos; break; }
if (--depth == 0) break;
} else if (bracket >= 3 && bracket < 6) {
++depth;
} else if (/[$\w]/.test(ch)) {
sawSomething = true;
} else if (sawSomething && !depth) {
++pos;
break;
}
}
if (sawSomething && !depth) state.fatArrowAt = pos;
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
function JSLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
for (var cx = state.context; cx; cx = cx.prev) {
for (var v = cx.vars; v; v = v.next)
if (v.name == varname) return true;
}
}
function parseJS(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
return style;
}
}
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function register(varname) {
function inList(list) {
for (var v = list; v; v = v.next)
if (v.name == varname) return true;
return false;
}
var state = cx.state;
if (state.context) {
cx.marked = "def";
if (inList(state.localVars)) return;
state.localVars = {name: varname, next: state.localVars};
} else {
if (inList(state.globalVars)) return;
if (parserConfig.globalVars)
state.globalVars = {name: varname, next: state.globalVars};
}
}
// Combinators
var defaultVars = {name: "this", next: {name: "arguments"}};
function pushcontext() {
cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
cx.state.localVars = defaultVars;
}
function popcontext() {
cx.state.localVars = cx.state.context.vars;
cx.state.context = cx.state.context.prev;
}
function pushlex(type, info) {
var result = function() {
var state = cx.state, indent = state.indented;
if (state.lexical.type == "stat") indent = state.lexical.indented;
state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
function exp(type) {
if (type == wanted) return cont();
else if (wanted == ";") return pass();
else return cont(exp);
};
return exp;
}
function statement(type, value) {
if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "{") return cont(pushlex("}"), block, poplex);
if (type == ";") return cont();
if (type == "if") {
if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
cx.state.cc.pop()();
return cont(pushlex("form"), expression, statement, poplex, maybeelse);
}
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
if (type == "variable") return cont(pushlex("stat"), maybelabel);
if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
block, poplex, poplex);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
statement, poplex, popcontext);
if (type == "module") return cont(pushlex("form"), pushcontext, afterModule, popcontext, poplex);
if (type == "class") return cont(pushlex("form"), className, objlit, poplex);
if (type == "export") return cont(pushlex("form"), afterExport, poplex);
if (type == "import") return cont(pushlex("form"), afterImport, poplex);
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function expression(type) {
return expressionInner(type, false);
}
function expressionNoComma(type) {
return expressionInner(type, true);
}
function expressionInner(type, noComma) {
if (cx.state.fatArrowAt == cx.stream.start) {
var body = noComma ? arrowBodyNoComma : arrowBody;
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
}
var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
if (type == "function") return cont(functiondef, maybeop);
if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop);
if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
if (type == "{") return contCommasep(objprop, "}", null, maybeop);
if (type == "quasi") { return pass(quasi, maybeop); }
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeexpressionNoComma(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expressionNoComma);
}
function maybeoperatorComma(type, value) {
if (type == ",") return cont(expression);
return maybeoperatorNoComma(type, value, false);
}
function maybeoperatorNoComma(type, value, noComma) {
var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
var expr = noComma == false ? expression : expressionNoComma;
if (value == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
if (type == "operator") {
if (/\+\+|--/.test(value)) return cont(me);
if (value == "?") return cont(expression, expect(":"), expr);
return cont(expr);
}
if (type == "quasi") { return pass(quasi, me); }
if (type == ";") return;
if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
if (type == ".") return cont(property, me);
if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
}
function quasi(type, value) {
if (type != "quasi") return pass();
if (value.slice(value.length - 2) != "${") return cont(quasi);
return cont(expression, continueQuasi);
}
function continueQuasi(type) {
if (type == "}") {
cx.marked = "string-2";
cx.state.tokenize = tokenQuasi;
return cont(quasi);
}
}
function arrowBody(type) {
findFatArrow(cx.stream, cx.state);
if (type == "{") return pass(statement);
return pass(expression);
}
function arrowBodyNoComma(type) {
findFatArrow(cx.stream, cx.state);
if (type == "{") return pass(statement);
return pass(expressionNoComma);
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperatorComma, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type, value) {
if (type == "variable") {
cx.marked = "property";
if (value == "get" || value == "set") return cont(getterSetter);
} else if (type == "number" || type == "string") {
cx.marked = jsonldMode ? "property" : (type + " property");
} else if (type == "[") {
return cont(expression, expect("]"), afterprop);
}
if (atomicTypes.hasOwnProperty(type)) return cont(afterprop);
}
function getterSetter(type) {
if (type != "variable") return pass(afterprop);
cx.marked = "property";
return cont(functiondef);
}
function afterprop(type) {
if (type == ":") return cont(expressionNoComma);
if (type == "(") return pass(functiondef);
}
function commasep(what, end) {
function proceed(type) {
if (type == ",") {
var lex = cx.state.lexical;
if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
return cont(what, proceed);
}
if (type == end) return cont();
return cont(expect(end));
}
return function(type) {
if (type == end) return cont();
return pass(what, proceed);
};
}
function contCommasep(what, end, info) {
for (var i = 3; i < arguments.length; i++)
cx.cc.push(arguments[i]);
return cont(pushlex(end, info), commasep(what, end), poplex);
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function maybetype(type) {
if (isTS && type == ":") return cont(typedef);
}
function typedef(type) {
if (type == "variable"){cx.marked = "variable-3"; return cont();}
}
function vardef() {
return pass(pattern, maybetype, maybeAssign, vardefCont);
}
function pattern(type, value) {
if (type == "variable") { register(value); return cont(); }
if (type == "[") return contCommasep(pattern, "]");
if (type == "{") return contCommasep(proppattern, "}");
}
function proppattern(type, value) {
if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
register(value);
return cont(maybeAssign);
}
if (type == "variable") cx.marked = "property";
return cont(expect(":"), pattern, maybeAssign);
}
function maybeAssign(_type, value) {
if (value == "=") return cont(expressionNoComma);
}
function vardefCont(type) {
if (type == ",") return cont(vardef);
}
function maybeelse(type, value) {
if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
}
function forspec(type) {
if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
}
function forspec1(type) {
if (type == "var") return cont(vardef, expect(";"), forspec2);
if (type == ";") return cont(forspec2);
if (type == "variable") return cont(formaybeinof);
return pass(expression, expect(";"), forspec2);
}
function formaybeinof(_type, value) {
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
return cont(maybeoperatorComma, forspec2);
}
function forspec2(type, value) {
if (type == ";") return cont(forspec3);
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
return pass(expression, expect(";"), forspec3);
}
function forspec3(type) {
if (type != ")") cont(expression);
}
function functiondef(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
if (type == "variable") {register(value); return cont(functiondef);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext);
}
function funarg(type) {
if (type == "spread") return cont(funarg);
return pass(pattern, maybetype);
}
function className(type, value) {
if (type == "variable") {register(value); return cont(classNameAfter);}
}
function classNameAfter(_type, value) {
if (value == "extends") return cont(expression);
}
function objlit(type) {
if (type == "{") return contCommasep(objprop, "}");
}
function afterModule(type, value) {
if (type == "string") return cont(statement);
if (type == "variable") { register(value); return cont(maybeFrom); }
}
function afterExport(_type, value) {
if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
return pass(statement);
}
function afterImport(type) {
if (type == "string") return cont();
return pass(importSpec, maybeFrom);
}
function importSpec(type, value) {
if (type == "{") return contCommasep(importSpec, "}");
if (type == "variable") register(value);
return cont();
}
function maybeFrom(_type, value) {
if (value == "from") { cx.marked = "keyword"; return cont(expression); }
}
function arrayLiteral(type) {
if (type == "]") return cont();
return pass(expressionNoComma, maybeArrayComprehension);
}
function maybeArrayComprehension(type) {
if (type == "for") return pass(comprehension, expect("]"));
if (type == ",") return cont(commasep(expressionNoComma, "]"));
return pass(commasep(expressionNoComma, "]"));
}
function comprehension(type) {
if (type == "for") return cont(forspec, comprehension);
if (type == "if") return cont(expression, comprehension);
}
// Interface
return {
startState: function(basecolumn) {
var state = {
tokenize: tokenBase,
lastType: "sof",
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
context: parserConfig.localVars && {vars: parserConfig.localVars},
indented: 0
};
if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
state.globalVars = parserConfig.globalVars;
return state;
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
findFatArrow(stream, state);
}
if (state.tokenize != tokenComment && stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
return parseJS(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize == tokenComment) return CodeMirror.Pass;
if (state.tokenize != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
// Kludge to prevent 'maybelse' from blocking lexical scope pops
if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
var c = state.cc[i];
if (c == poplex) lexical = lexical.prev;
else if (c != maybeelse) break;
}
if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "form") return lexical.indented + indentUnit;
else if (type == "stat")
return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? statementIndent || indentUnit : 0);
else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricChars: ":{}",
blockCommentStart: jsonMode ? null : "/*",
blockCommentEnd: jsonMode ? null : "*/",
lineComment: jsonMode ? null : "//",
fold: "brace",
helperType: jsonMode ? "json" : "javascript",
jsonldMode: jsonldMode,
jsonMode: jsonMode
};
});
CodeMirror.registerHelper("wordChars", "javascript", /[\\w$]/);
CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
});
This plugin provides an enhanced text editor component based on [[CodeMirror|http://codemirror.net]]. It provides several advantages over the default browser text editor:
* Code colouring for many languages (see [[the official documentation here|http://codemirror.net/mode/index.html]])
* Auto closing brackets and tags
* Folding brackets, comments, and tags
* Auto-completion
[[Source code|https://github.com/Jermolene/TiddlyWiki5/blob/master/plugins/tiddlywiki/codemirror]]
/* Make the editor resize to fit its content */
.CodeMirror {
height: auto;
border: 1px solid #ddd;
line-height: 1.5;
font-family: "Monaco", monospace;
}
.CodeMirror-scroll {
overflow-x: auto;
overflow-y: hidden;
}
! Setting ~CodeMirror Content Types
You can determine which tiddler content types are edited by the ~CodeMirror widget by creating or modifying special tiddlers whose prefix is comprised of the string `$:/config/EditorTypeMappings/` concatenated with the content type. The text of that tiddler gives the editor type to be used (eg, ''text'', ''bitmap'', ''codemirror'').
The current editor type mappings are shown in [[$:/ControlPanel]] under the "Advanced" tab.
! ~CodeMirror Configuration
You can configure the ~CodeMirror plugin by creating a tiddler called [[$:/config/CodeMirror]] containing a JSON configuration object. The configuration tiddler must have its type field set to `application/json` to take effect.
See http://codemirror.net/ for details of available configuration options.
For example:
```
{
"require": [
"$:/plugins/tiddlywiki/codemirror/mode/javascript/javascript.js",
"$:/plugins/tiddlywiki/codemirror/addon/dialog/dialog.js",
"$:/plugins/tiddlywiki/codemirror/addon/search/searchcursor.js",
"$:/plugins/tiddlywiki/codemirror/addon/edit/matchbrackets.js",
"$:/plugins/tiddlywiki/codemirror/keymap/vim.js",
"$:/plugins/tiddlywiki/codemirror/keymap/emacs.js"
],
"configuration": {
"keyMap": "vim",
"matchBrackets":true,
"showCursorWhenSelecting": true
}
}
```
!! Basic working configuration
# Create a tiddler called `$:/config/CodeMirror`
# The type of the tiddler has to be set to `application/json`
# The text of the tiddler is the following:
```
{
"require": [
"$:/plugins/tiddlywiki/codemirror/mode/javascript/javascript.js",
"$:/plugins/tiddlywiki/codemirror/addon/edit/matchbrackets.js"
],
"configuration": {
"matchBrackets":true,
"showCursorWhenSelecting": true
}
}
```
# You should see line numbers when editing a tiddler
# When editing a tiddler, no matter what the type of the tiddler is set to, you should see matching brackets being highlighted whenever the cursor is next to one of them
# If you edit a tiddler with the type `application/javascript` or `application/json` you should see the code being syntax highlighted
!! Add HTML syntax highlighting
# Create a tiddler `$:/plugins/tiddlywiki/codemirror/mode/xml/xml.js`
## Add a field `module-type` and set it to ''library''
## Set the field `type` to ''application/javascript''
## Set the text field of the tiddler with the javascript code from this link : [[https://raw.githubusercontent.com/codemirror/CodeMirror/master/mode/xml/xml.js]]
# Set the text field of the tiddler `$:/config/CodeMirror` to:
```
{
"require": [
"$:/plugins/tiddlywiki/codemirror/mode/javascript/javascript.js",
"$:/plugins/tiddlywiki/codemirror/mode/xml/xml.js",
"$:/plugins/tiddlywiki/codemirror/addon/edit/matchbrackets.js"
],
"configuration": {
"showCursorWhenSelecting": true,
"matchBrackets":true
}
}
```
# Edit a tiddler with the type `text/html` and write some html code. You should see your code being coloured
!! Add a non-existing language mode
Here's an example of adding a new language mode - in this case, the language C.
# Create a tiddler `$:/plugins/tiddlywiki/codemirror/mode/clike/clike.js`
## Add a field `module-type` and set it to ''library''
## Set the field `type` to ''application/javascript''
## Set the text field of the tiddler with the javascript code from this link : [[https://raw.githubusercontent.com/codemirror/CodeMirror/master/mode/clike/clike.js]]
# Set the text field of the tiddler `$:/config/CodeMirror` to:
```
{
"require": [
"$:/plugins/tiddlywiki/codemirror/mode/javascript/javascript.js",
"$:/plugins/tiddlywiki/codemirror/mode/clike/clike.js"
],
"configuration": {
"showCursorWhenSelecting": true
}
}
```
# Add the correct ~EditorTypeMappings tiddler
## Find the matching MIME type. If you go on the [[CodeMirror documentation for language modes|http://codemirror.net/mode/index.html]] you can see the [[documentation for the c-like mode|http://codemirror.net/mode/clike/index.html]]. In this documentation, at the end you will be told the MIME types defined. Here it's ''text/x-csrc''
## Add the tiddler: `$:/config/EditorTypeMappings/text/x-csrc` and fill the text field with : ''codemirror''
If you edit a tiddler with the type `text/x-csrc` and write some code in C, you should see your text being coloured.
!! Add matching tags
# Add XML and HTML colouring
# Create a tiddler `$:/plugins/tiddlywiki/codemirror/addon/edit/matchtags.js`
## Add a field `module-type` and set it to ''library''
## Set the field `type` to ''application/javascript''
## Set the text field of the tiddler with the javascript code from this link : [[http://codemirror.net/addon/edit/matchtags.js]]
# Set the text field of the tiddler `$:/config/CodeMirror` to:
```
{
"require": [
"$:/plugins/tiddlywiki/codemirror/mode/javascript/javascript.js",
"$:/plugins/tiddlywiki/codemirror/addon/edit/matchtags.js",
"$:/plugins/tiddlywiki/codemirror/mode/xml/xml.js"
],
"configuration": {
"showCursorWhenSelecting": true,
"matchTags": {"bothTags": true},
"extraKeys": {"Ctrl-J": "toMatchingTag"}
}
}
```
Edit a tiddler that has the type :`text/htm` and write this code:
```
<html>
<div id="click here and press CTRL+J">
<ul>
<li>
</li>
</ul>
</div>
</html>
```
If you click on a tag and press CTRL+J, your cursor will select the matching tag. Supposedly, it should highlight the pair when clicking a tag. However, that part doesn't work.
!! Adding closing tags
# Add the xml mode (see "Add XML and HTML colouring")
# Create a tiddler `$:/plugins/tiddlywiki/codemirror/addon/edit/closetags.js`
## Add a field `module-type` and set it to ''library''
## Set the field `type` to ''application/javascript''
## Set the text field of the tiddler with the javascript code from this link : [[http://codemirror.net/addon/edit/closetag.js]]
# Set the text field of the tiddler `$:/config/CodeMirror` to:
```
{
"require": [
"$:/plugins/tiddlywiki/codemirror/mode/javascript/javascript.js",
"$:/plugins/tiddlywiki/codemirror/mode/xml/xml.js",
"$:/plugins/tiddlywiki/codemirror/addon/edit/closetags.js"
],
"configuration": {
"showCursorWhenSelecting": true,
"autoCloseTags":true
}
}
```
If you edit a tiddler with the type`text/html` and write:
```
<html>
```
Then the closing tag ''</html>'' should automatically appear.
!! Add closing brackets
# Create a tiddler `$:/plugins/tiddlywiki/codemirror/addon/edit/closebrackets.js`
## Add a field `module-type` and set it to ''library''
## Set the field `type` to ''application/javascript''
## Set the text field of the tiddler with the javascript code from this link : [[http://codemirror.net/addon/edit/closebrackets.js]]
# Set the text field of the tiddler `$:/config/CodeMirror` to:
```
{
"require": [
"$:/plugins/tiddlywiki/codemirror/mode/javascript/javascript.js",
"$:/plugins/tiddlywiki/codemirror/addon/edit/matchbrackets.js",
"$:/plugins/tiddlywiki/codemirror/addon/edit/closebrackets.js"
],
"configuration": {
"showCursorWhenSelecting": true,
"matchBrackets":true,
"autoCloseBrackets":true
}
}
```
# If you try to edit any tiddler and write `if(` you should see the bracket closing itself automatically (you will get "if()"). It works with (), [], and {}
# If you try and edit a tiddler with the type `application/javascript`, it will auto-close `()`,`[]`,`{}`,`''` and `""`
!! Adding folding tags
# Create a tiddler `$:/plugins/tiddlywiki/codemirror/addon/fold/foldcode.js`
## Add a field `module-type` and set it to ''library''
## Set the field `type` to ''application/javascript''
## Set the text field of the tiddler with the javascript code from this link : [[http://codemirror.net/addon/fold/foldcode.js]]
# Repeat the above process for the following tiddlers, but replace the code with the one from the given link:
## Create a tiddler `$:/plugins/tiddlywiki/codemirror/addon/fold/xml-fold.js`, the code can be found here [[https://raw.githubusercontent.com/codemirror/CodeMirror/master/addon/fold/xml-fold.js]]
## Create a tiddler `$:/plugins/tiddlywiki/codemirror/addon/fold/foldgutter.js`, the code can be found here [[http://codemirror.net/addon/fold/foldgutter.js]]
# Create a tiddler `$:/plugins/tiddlywiki/codemirror/addon/fold/foldgutter.css`
## Add the tag `$:/tags/Stylesheet`
## Set the text field of the tiddler with the css code from this link : [[http://codemirror.net/addon/fold/foldgutter.css]]
# Set the text field of the tiddler `$:/config/CodeMirror` to:
```
{
"require": [
"$:/plugins/tiddlywiki/codemirror/mode/javascript/javascript.js",
"$:/plugins/tiddlywiki/codemirror/mode/xml/xml.js",
"$:/plugins/tiddlywiki/codemirror/addon/fold/foldcode.js",
"$:/plugins/tiddlywiki/codemirror/addon/fold/xml-fold.js",
"$:/plugins/tiddlywiki/codemirror/addon/fold/foldgutter.js"
],
"configuration": {
"showCursorWhenSelecting": true,
"matchTags": {"bothTags": true},
"foldGutter": true,
"gutters": ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
}
}
```
Now if you type the below code in a tiddler with the type `text/html`:
```
<html>
<div>
<ul>
</ul>
</div>
</html>
```
You should see little arrows just next to the line numbers. Clicking on it will have the effect to fold the code (or unfold it).
\rules only filteredtranscludeinline transcludeinline
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="format-detection" content="telephone=no">
<link id="faviconLink" rel="shortcut icon" href="favicon.ico">
<!--~~ Raw markup ~~-->
{{$:/ractivejs/templates/exporters/StaticRiver/Content/head}}
</head>
<body class="tc-body">
<style >
{{$:/ractivejs/templates/exporters/StaticRiver/Content/css}}
</style>
{{$:/ractivejs/templates/exporters/StaticRiver/Content/html}}
{{$:/ractivejs/templates/exporters/StaticRiver/Content/tmpt}}
{{$:/ractivejs/templates/exporters/StaticRiver/Content/js}}
</body>
</html>
\define make_python(proj)
<$set name="exportFiltercss" value="[tag[$proj$]type[text/css]]">
<$set name="exportFilterjs" value="[tag[$proj$]type[application/javascript]]">
<$set name="exportFiltertmpt" value="[tag[$proj$]type[text/python]]">
<$set name="exportFilterhtml" value="[tag[$proj$]type[text/html]]">
<$set name="exportFilterhead" value="[tag[$proj$]tag[$:/bj/iframe/raw]]">
{{$:/python/templates/exporters/StaticRiver}}
</$set>
</$set>
</$set>
</$set>
</$set>
\end
//Macro to output tiddlers matching a filter to JSON
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
/*
Information about this macro
*/
exports.name = "bitolsasjsons";
exports.params = [
{name: "filter"}
];
/*
Run the macro
*/
exports.run = function(filter) {
var tiddlers = this.wiki.filterTiddlers(filter),
data = {};
for(var t=0;t<tiddlers.length; t++) {
var tiddler = this.wiki.getTiddler(tiddlers[t]);
if(tiddler) {
data[tiddler.fields.title] = tiddler;
}
}
return JSON.stringify(data,null,$tw.config.preferences.jsonSpaces);
};
})();
\rules only filteredtranscludeinline transcludeinline
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="format-detection" content="telephone=no">
<link id="faviconLink" rel="shortcut icon" href="favicon.ico">
<!--~~ Raw markup ~~-->
{{$:/ractivejs/templates/exporters/StaticRiver/Content/head}}
</head>
<body class="tc-body">
<style >
{{$:/ractivejs/templates/exporters/StaticRiver/Content/css}}
</style>
<script>
var bitols = {{$:/ractivejs/templates/exporters/StaticRiver/Content/bitols}}
</script>
{{$:/ractivejs/templates/exporters/StaticRiver/Content/html}}
{{$:/ractivejs/templates/exporters/StaticRiver/Content/tmpt}}
{{$:/ractivejs/templates/exporters/StaticRiver/Content/js}}
</body>
</html>
\define renderContent()
{{{ $(exportFilter)$ ||$:/ractivejs/templates/static-tiddler}}}
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<<renderContent>>
</$importvariables>
\define renderContent()
<$text text=<<bitolsasjsons filter:"""$(exportBitolsFilter)$""">>/>
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<<renderContent>>
</$importvariables>
\define renderContent()
{{{$(exportFiltercss)$||$:/core/templates/plain-text-tiddler}}}
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<<renderContent>>
</$importvariables>
\define renderContent()
{{{$(exportFilterhead)$||$:/core/templates/plain-text-tiddler}}}
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<<renderContent>>
</$importvariables>
\define renderContent()
{{{$(exportFilterhtml)$||$:/core/templates/html-tiddler}}}
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<<renderContent>>
</$importvariables>
\define renderContent()
{{{ $(exportFilterjs)$ ||$:/ractivejs/templates/scriptwidget}}}
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<<renderContent>>
</$importvariables>
\define renderContent()
{{{ $(exportFiltertmpt)$ ||$:/ractivejs/templates/scriptwidget}}}
\end
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<<renderContent>>
</$importvariables>
<$macrocall $name="script" source=<<currentTiddler>> esc="true"/>
<a name=<<currentTiddler>>>
<$transclude tiddler="$:/core/ui/ViewTemplate/body"/>
</a>
\define renderfield(title)
<tr class="tc-view-field"><td class="tc-view-field-name">''$title$'':</td><td class="tc-view-field-value">//{{$:/language/Docs/Fields/$title$}}//</td></tr>
\end
<table class="tc-view-field-table"><tbody><$list filter="[fields[]sort[title]]" variable="listItem"><$macrocall $name="renderfield" title=<<listItem>>/></$list>
</tbody></table>
\define swatchStyle()
background-color: $(swatchColour)$;
\end
\define swatch(colour)
<$set name="swatchColour" value={{##$colour$}}>
<div class="tc-swatch" style=<<swatchStyle>>/>
</$set>
\end
<div class="tc-swatches-horiz">
<<swatch foreground>>
<<swatch background>>
<<swatch muted-foreground>>
<<swatch primary>>
<<swatch page-background>>
<<swatch tab-background>>
<<swatch tiddler-info-background>>
</div>
\define lingo-base() $:/language/ControlPanel/Tools/Download/
<$button class="tc-btn-big-green">
<$action-sendmessage $message="tm-download-file" $param="$:/core/save/all" filename="index.html"/>
<<lingo Full/Caption>> {{$:/core/images/save-button}}
</$button>
{{$:/language/ControlPanel/Basics/Language/Prompt}} <$select tiddler="$:/language">
<$list filter="[[$:/languages/en-GB]] [plugin-type[language]sort[description]]">
<option value=<<currentTiddler>>><$view field="description"><$view field="name"><$view field="title"/></$view></$view></option>
</$list>
</$select>
<$select tiddler="$:/language">
<$list filter="[[$:/languages/en-GB]] [plugin-type[language]sort[title]]">
<option value=<<currentTiddler>>><$view field="description"><$view field="name"><$view field="title"/></$view></$view></option>
</$list>
</$select>
\define lingo-base() $:/language/ControlPanel/Theme/
<<lingo Prompt>> <$select tiddler="$:/theme">
<$list filter="[plugin-type[theme]sort[title]]">
<option value=<<currentTiddler>>><$view field="name"><$view field="title"/></$view></option>
</$list>
</$select>
\define describeModuleType(type)
{{$:/language/Docs/ModuleTypes/$type$}}
\end
<$list filter="[moduletypes[]]">
!! <$macrocall $name="currentTiddler" $type="text/plain" $output="text/plain"/>
<$macrocall $name="describeModuleType" type=<<currentTiddler>>/>
<ul><$list filter="[all[current]modules[]]"><li><$link><<currentTiddler>></$link>
</li>
</$list>
</ul>
</$list>
\define lingo-base() $:/language/ControlPanel/Palette/Editor/
\define describePaletteColour(colour)
<$transclude tiddler="$:/language/Docs/PaletteColours/$colour$"><$text text="$colour$"/></$transclude>
\end
<$set name="currentTiddler" value={{$:/palette}}>
<<lingo Prompt>> <$link to={{$:/palette}}><$macrocall $name="currentTiddler" $output="text/plain"/></$link>
<$list filter="[all[current]is[shadow]is[tiddler]]" variable="listItem">
<<lingo Prompt/Modified>>
<$button message="tm-delete-tiddler" param={{$:/palette}}><<lingo Reset/Caption>></$button>
</$list>
<$list filter="[all[current]is[shadow]!is[tiddler]]" variable="listItem">
<<lingo Clone/Prompt>>
</$list>
<$button message="tm-new-tiddler" param={{$:/palette}}><<lingo Clone/Caption>></$button>
<table>
<tbody>
<$list filter="[all[current]indexes[]]" variable="colourName">
<tr>
<td>
''<$macrocall $name="describePaletteColour" colour=<<colourName>>/>''<br/>
<$macrocall $name="colourName" $output="text/plain"/>
</td>
<td>
<$edit-text index=<<colourName>> tag="input"/>
<br>
<$edit-text index=<<colourName>> type="color" tag="input"/>
</td>
</tr>
</$list>
</tbody>
</table>
</$set>
<$set name="currentTiddler" value={{$:/palette}}>
<$transclude tiddler="$:/snippets/currpalettepreview"/>
</$set>
\define lingo-base() $:/language/ControlPanel/Palette/
<div class="tc-prompt">
<<lingo Prompt>> <$view tiddler={{$:/palette}} field="name"/>
</div>
<$linkcatcher to="$:/palette">
<div class="tc-chooser"><$list filter="[all[shadows+tiddlers]tag[$:/tags/Palette]sort[description]]"><div class="tc-chooser-item"><$link to={{!!title}}><div><$reveal state="$:/palette" type="match" text={{!!title}}>•</$reveal><$reveal state="$:/palette" type="nomatch" text={{!!title}}> </$reveal> ''<$view field="name" format="text"/>'' - <$view field="description" format="text"/></div><$transclude tiddler="$:/snippets/currpalettepreview"/></$link></div>
</$list>
</div>
</$linkcatcher>
\define lingo-base() $:/language/ControlPanel/Theme/
<<lingo Prompt>> <$view tiddler={{$:/theme}} field="name"/>
<$linkcatcher to="$:/theme">
<$list filter="[plugin-type[theme]sort[title]]"><div><$reveal state="$:/theme" type="match" text={{!!title}}>•</$reveal><$reveal state="$:/theme" type="nomatch" text={{!!title}}> </$reveal> <$link to={{!!title}}>''<$view field="name" format="text"/>'' <$view field="description" format="text"/></$link></div>
</$list>
</$linkcatcher>
\define lingo-base() $:/language/ControlPanel/StoryView/
<<lingo Prompt>> <$select tiddler="$:/view">
<$list filter="[storyviews[]]">
<option><$view field="title"/></option>
</$list>
</$select>
$:/core/ui/AdvancedSearch/System
$:/themes/tiddlywiki/vanilla/themetweaks
$:/core/ui/ControlPanel/Advanced
$:/core/ui/ControlPanel/Plugins/Installed/Plugins
$:/core/ui/ControlPanel/Saving
$:/core/ui/SideBar/Recent
\define lingo-base() $:/language/TagManager/
\define iconEditorTab(type)
<$list filter="[all[shadows+tiddlers]is[image]] [all[shadows+tiddlers]tag[$:/tags/Image]] -[type[application/pdf]] +[sort[title]] +[$type$is[system]]">
<$link to={{!!title}}>
<$transclude/> <$view field="title"/>
</$link>
</$list>
\end
\define iconEditor(title)
<div class="tc-drop-down-wrapper">
<$button popup=<<qualify "$:/state/popup/icon/$title$">> class="tc-btn-invisible tc-btn-dropdown">{{$:/core/images/down-arrow}}</$button>
<$reveal state=<<qualify "$:/state/popup/icon/$title$">> type="popup" position="belowleft" text="" default="">
<div class="tc-drop-down">
<$linkcatcher to="$title$!!icon">
<<iconEditorTab type:"!">>
<hr/>
<<iconEditorTab type:"">>
</$linkcatcher>
</div>
</$reveal>
</div>
\end
\define qualifyTitle(title)
$title$$(currentTiddler)$
\end
\define toggleButton(state)
<$reveal state="$state$" type="match" text="closed" default="closed">
<$button set="$state$" setTo="open" class="tc-btn-invisible tc-btn-dropdown" selectedClass="tc-selected">
{{$:/core/images/info-button}}
</$button>
</$reveal>
<$reveal state="$state$" type="match" text="open" default="closed">
<$button set="$state$" setTo="closed" class="tc-btn-invisible tc-btn-dropdown" selectedClass="tc-selected">
{{$:/core/images/info-button}}
</$button>
</$reveal>
\end
<table class="tc-tag-manager-table">
<tbody>
<tr>
<th><<lingo Colour/Heading>></th>
<th class="tc-tag-manager-tag"><<lingo Tag/Heading>></th>
<th><<lingo Count/Heading>></th>
<th><<lingo Icon/Heading>></th>
<th><<lingo Info/Heading>></th>
</tr>
<$list filter="[tags[]!is[system]sort[title]]">
<tr>
<td><$edit-text field="color" tag="input" type="color"/></td>
<td><$transclude tiddler="$:/core/ui/TagTemplate"/></td>
<td><$count filter="[all[current]tagging[]]"/></td>
<td>
<$macrocall $name="iconEditor" title={{!!title}}/>
</td>
<td>
<$macrocall $name="toggleButton" state=<<qualifyTitle "$:/state/tag-manager/">> />
</td>
</tr>
<tr>
<td></td>
<td colspan="4">
<$reveal state=<<qualifyTitle "$:/state/tag-manager/">> type="match" text="open" default="">
<table>
<tbody>
<tr><td><<lingo Colour/Heading>></td><td><$edit-text field="color" tag="input" type="text" size="9"/></td></tr>
<tr><td><<lingo Icon/Heading>></td><td><$edit-text field="icon" tag="input" size="45"/></td></tr>
</tbody>
</table>
</$reveal>
</td>
</tr>
</$list>
<tr>
<td></td>
<td>
{{$:/core/ui/UntaggedTemplate}}
</td>
<td>
<small class="tc-menu-list-count"><$count filter="[untagged[]!is[system]] -[tags[]]"/></small>
</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
{
"tiddlers": {
"$:/info/browser": {
"title": "$:/info/browser",
"text": "yes"
},
"$:/info/node": {
"title": "$:/info/node",
"text": "no"
}
}
}
\define custom-background-datauri()
<$set name="background" value={{$:/themes/tiddlywiki/vanilla/settings/backgroundimage}}>
<$list filter="[<background>is[image]]">
`background: url(`
<$list filter="[<background>!has[_canonical_uri]]">
<$macrocall $name="datauri" title={{$:/themes/tiddlywiki/vanilla/settings/backgroundimage}}/>
</$list>
<$list filter="[<background>has[_canonical_uri]]">
<$view tiddler={{$:/themes/tiddlywiki/vanilla/settings/backgroundimage}} field="_canonical_uri"/>
</$list>
`) center center;`
`background-attachment: `{{$:/themes/tiddlywiki/vanilla/settings/backgroundimageattachment}}`;
-webkit-background-size:` {{$:/themes/tiddlywiki/vanilla/settings/backgroundimagesize}}`;
-moz-background-size:` {{$:/themes/tiddlywiki/vanilla/settings/backgroundimagesize}}`;
-o-background-size:` {{$:/themes/tiddlywiki/vanilla/settings/backgroundimagesize}}`;
background-size:` {{$:/themes/tiddlywiki/vanilla/settings/backgroundimagesize}}`;`
</$list>
</$set>
\end
\define if-fluid-fixed(text,hiddenSidebarText)
<$reveal state="$:/themes/tiddlywiki/vanilla/options/sidebarlayout" type="match" text="fluid-fixed">
$text$
<$reveal state="$:/state/sidebar" type="nomatch" text="yes" default="yes">
$hiddenSidebarText$
</$reveal>
</$reveal>
\end
\rules only filteredtranscludeinline transcludeinline macrodef macrocallinline macrocallblock
/*
** Start with the normalize CSS reset, and then belay some of its effects
*/
{{$:/themes/tiddlywiki/vanilla/reset}}
*, input[type="search"] {
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
html button {
line-height: 1.2;
color: <<colour button-foreground>>;
background: <<colour button-background>>;
border-color: <<colour button-border>>;
}
/*
** Basic element styles
*/
html {
font-family: {{$:/themes/tiddlywiki/vanilla/settings/fontfamily}};
text-rendering: optimizeLegibility; /* Enables kerning and ligatures etc. */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
html:-webkit-full-screen {
background-color: <<colour page-background>>;
}
body.tc-body {
font-size: {{$:/themes/tiddlywiki/vanilla/metrics/fontsize}};
line-height: {{$:/themes/tiddlywiki/vanilla/metrics/lineheight}};
color: <<colour foreground>>;
background-color: <<colour page-background>>;
fill: <<colour foreground>>;
word-wrap: break-word;
<<custom-background-datauri>>
}
h1, h2, h3, h4, h5, h6 {
line-height: 1.2;
font-weight: 300;
}
pre {
display: block;
padding: 14px;
margin-top: 1em;
margin-bottom: 1em;
word-break: normal;
word-wrap: break-word;
white-space: pre;
white-space: pre-wrap;
background-color: <<colour pre-background>>;
border: 1px solid <<colour pre-border>>;
padding: 0 3px 2px;
border-radius: 3px;
font-family: {{$:/themes/tiddlywiki/vanilla/settings/codefontfamily}};
}
code {
color: <<colour code-foreground>>;
background-color: <<colour code-background>>;
border: 1px solid <<colour code-border>>;
white-space: pre-wrap;
padding: 0 3px 2px;
border-radius: 3px;
font-family: {{$:/themes/tiddlywiki/vanilla/settings/codefontfamily}};
}
blockquote {
border-left: 5px solid <<colour blockquote-bar>>;
margin-left: 25px;
padding-left: 10px;
}
dl dt {
font-weight: bold;
margin-top: 6px;
}
textarea,
input[type=text],
input[type=search],
input[type=""],
input:not([type]) {
color: <<colour foreground>>;
background: <<colour background>>;
}
.tc-muted {
color: <<colour muted-foreground>>;
}
svg.tc-image-button {
padding: 0px 1px 1px 0px;
}
kbd {
display: inline-block;
padding: 3px 5px;
font-size: 0.8em;
line-height: 1.2;
color: <<colour foreground>>;
vertical-align: middle;
background-color: <<colour background>>;
border: solid 1px <<colour muted-foreground>>;
border-bottom-color: <<colour muted-foreground>>;
border-radius: 3px;
box-shadow: inset 0 -1px 0 <<colour muted-foreground>>;
}
/*
Markdown likes putting code elements inside pre elements
*/
pre > code {
padding: 0;
border: none;
background-color: inherit;
color: inherit;
}
table {
border: 1px solid <<colour table-border>>;
width: auto;
max-width: 100%;
caption-side: bottom;
margin-top: 1em;
margin-bottom: 1em;
}
table th, table td {
padding: 0 7px 0 7px;
border-top: 1px solid <<colour table-border>>;
border-left: 1px solid <<colour table-border>>;
}
table thead tr td, table th {
background-color: <<colour table-header-background>>;
font-weight: bold;
}
table tfoot tr td {
background-color: <<colour table-footer-background>>;
}
.tc-csv-table {
white-space: nowrap;
}
.tc-tiddler-frame img,
.tc-tiddler-frame svg,
.tc-tiddler-frame canvas,
.tc-tiddler-frame embed,
.tc-tiddler-frame iframe {
max-width: 100%;
}
.tc-tiddler-body > embed,
.tc-tiddler-body > iframe {
width: 100%;
height: 600px;
}
/*
** Links
*/
button.tc-tiddlylink,
a.tc-tiddlylink {
text-decoration: none;
font-weight: normal;
color: <<colour tiddler-link-foreground>>;
-webkit-user-select: inherit; /* Otherwise the draggable attribute makes links impossible to select */
}
.tc-sidebar-lists a.tc-tiddlylink {
color: <<colour sidebar-tiddler-link-foreground>>;
}
.tc-sidebar-lists a.tc-tiddlylink:hover {
color: <<colour sidebar-tiddler-link-foreground-hover>>;
}
button.tc-tiddlylink:hover,
a.tc-tiddlylink:hover {
text-decoration: underline;
}
a.tc-tiddlylink-resolves {
}
a.tc-tiddlylink-shadow {
font-weight: bold;
}
a.tc-tiddlylink-shadow.tc-tiddlylink-resolves {
font-weight: normal;
}
a.tc-tiddlylink-missing {
font-style: italic;
}
a.tc-tiddlylink-external {
text-decoration: underline;
color: <<colour external-link-foreground>>;
background-color: <<colour external-link-background>>;
}
a.tc-tiddlylink-external:visited {
color: <<colour external-link-foreground-visited>>;
background-color: <<colour external-link-background-visited>>;
}
a.tc-tiddlylink-external:hover {
color: <<colour external-link-foreground-hover>>;
background-color: <<colour external-link-background-hover>>;
}
/*
** Drag and drop styles
*/
.tc-tiddler-dragger {
position: relative;
z-index: -10000;
}
.tc-tiddler-dragger-inner {
position: absolute;
display: inline-block;
padding: 8px 20px;
font-size: 16.9px;
font-weight: bold;
line-height: 20px;
color: <<colour dragger-foreground>>;
text-shadow: 0 1px 0 rgba(0, 0, 0, 1);
white-space: nowrap;
vertical-align: baseline;
background-color: <<colour dragger-background>>;
border-radius: 20px;
}
.tc-tiddler-dragger-cover {
position: absolute;
background-color: <<colour page-background>>;
}
.tc-dropzone {
position: relative;
}
.tc-dropzone.tc-dragover:before {
z-index: 10000;
display: block;
position: fixed;
top: 0;
left: 0;
right: 0;
background: <<colour dropzone-background>>;
text-align: center;
content: "<<lingo DropMessage>>";
}
/*
** Plugin reload warning
*/
.tc-plugin-reload-warning {
z-index: 1000;
display: block;
position: fixed;
top: 0;
left: 0;
right: 0;
background: <<colour alert-background>>;
text-align: center;
}
/*
** Buttons
*/
button svg, button img {
vertical-align: middle;
}
.tc-btn-invisible {
padding: 0;
margin: 0;
background: none;
border: none;
}
.tc-btn-boxed {
font-size: 0.6em;
padding: 0.2em;
margin: 1px;
background: none;
border: 1px solid <<colour tiddler-controls-foreground>>;
border-radius: 0.25em;
}
html body.tc-body .tc-btn-boxed svg {
font-size: 1.6666em;
}
.tc-btn-boxed:hover {
background: <<colour muted-foreground>>;
color: <<colour background>>;
}
html body.tc-body .tc-btn-boxed:hover svg {
fill: <<colour background>>;
}
.tc-btn-rounded {
font-size: 0.5em;
line-height: 2;
padding: 0em 0.3em 0.2em 0.4em;
margin: 1px;
border: 1px solid <<colour muted-foreground>>;
background: <<colour muted-foreground>>;
color: <<colour background>>;
border-radius: 2em;
}
html body.tc-body .tc-btn-rounded svg {
font-size: 1.6666em;
fill: <<colour background>>;
}
.tc-btn-rounded:hover {
border: 1px solid <<colour muted-foreground>>;
background: <<colour background>>;
color: <<colour muted-foreground>>;
}
html body.tc-body .tc-btn-rounded:hover svg {
fill: <<colour muted-foreground>>;
}
.tc-btn-icon svg {
height: 1em;
width: 1em;
fill: <<colour muted-foreground>>;
}
.tc-btn-text {
padding: 0;
margin: 0;
}
.tc-btn-big-green {
display: inline-block;
padding: 8px;
margin: 4px 8px 4px 8px;
background: <<colour download-background>>;
color: <<colour download-foreground>>;
fill: <<colour download-foreground>>;
border: none;
font-size: 1.2em;
line-height: 1.4em;
text-decoration: none;
}
.tc-btn-big-green svg,
.tc-btn-big-green img {
height: 2em;
width: 2em;
vertical-align: middle;
fill: <<colour download-foreground>>;
}
.tc-sidebar-lists input {
color: <<colour foreground>>;
}
.tc-sidebar-lists button {
color: <<colour sidebar-button-foreground>>;
fill: <<colour sidebar-button-foreground>>;
}
.tc-sidebar-lists button.tc-btn-mini {
color: <<colour sidebar-muted-foreground>>;
}
.tc-sidebar-lists button.tc-btn-mini:hover {
color: <<colour sidebar-muted-foreground-hover>>;
}
button svg.tc-image-button, button .tc-image-button img {
height: 1em;
width: 1em;
}
.tc-unfold-banner {
position: absolute;
padding: 0;
margin: 0;
background: none;
border: none;
width: 100%;
width: calc(100% + 2px);
margin-left: -43px;
text-align: center;
border-top: 2px solid <<colour tiddler-info-background>>;
margin-top: 4px;
}
.tc-unfold-banner:hover {
background: <<colour tiddler-info-background>>;
border-top: 2px solid <<colour tiddler-info-border>>;
}
.tc-unfold-banner svg, .tc-fold-banner svg {
height: 0.75em;
fill: <<colour tiddler-controls-foreground>>;
}
.tc-unfold-banner:hover svg, .tc-fold-banner:hover svg {
fill: <<colour tiddler-controls-foreground-hover>>;
}
.tc-fold-banner {
position: absolute;
padding: 0;
margin: 0;
background: none;
border: none;
width: 23px;
text-align: center;
margin-left: -35px;
top: 6px;
bottom: 6px;
}
.tc-fold-banner:hover {
background: <<colour tiddler-info-background>>;
}
@media (max-width: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint}}) {
.tc-unfold-banner {
position: static;
width: calc(100% + 59px);
}
.tc-fold-banner {
width: 16px;
margin-left: -16px;
font-size: 0.75em;
}
}
/*
** Tags and missing tiddlers
*/
.tc-tag-list-item {
position: relative;
display: inline-block;
margin-right: 7px;
}
.tc-tags-wrapper {
margin: 4px 0 14px 0;
}
.tc-missing-tiddler-label {
font-style: italic;
font-weight: normal;
display: inline-block;
font-size: 11.844px;
line-height: 14px;
white-space: nowrap;
vertical-align: baseline;
}
button.tc-tag-label, span.tc-tag-label {
display: inline-block;
padding: 0.16em 0.7em;
font-size: 0.9em;
font-weight: 300;
line-height: 1.2em;
color: <<colour tag-foreground>>;
white-space: nowrap;
vertical-align: baseline;
background-color: <<colour tag-background>>;
border-radius: 1em;
}
.tc-untagged-separator {
width: 10em;
left: 0;
margin-left: 0;
border: 0;
height: 1px;
background: <<colour tab-divider>>;
}
button.tc-untagged-label {
background-color: <<colour untagged-background>>;
}
.tc-tag-label svg, .tc-tag-label img {
height: 1em;
width: 1em;
fill: <<colour tag-foreground>>;
}
.tc-tag-manager-table .tc-tag-label {
white-space: normal;
}
.tc-tag-manager-tag {
width: 100%;
}
/*
** Page layout
*/
.tc-topbar {
position: fixed;
z-index: 1200;
}
.tc-topbar-left {
left: 29px;
top: 5px;
}
.tc-topbar-right {
top: 5px;
right: 29px;
}
.tc-topbar button {
padding: 8px;
}
.tc-topbar svg {
fill: <<colour muted-foreground>>;
}
.tc-topbar button:hover svg {
fill: <<colour foreground>>;
}
.tc-sidebar-header {
color: <<colour sidebar-foreground>>;
fill: <<colour sidebar-foreground>>;
}
.tc-sidebar-header .tc-title a.tc-tiddlylink-resolves {
font-weight: 300;
}
.tc-sidebar-header .tc-sidebar-lists p {
margin-top: 3px;
margin-bottom: 3px;
}
.tc-sidebar-header .tc-missing-tiddler-label {
color: <<colour sidebar-foreground>>;
}
.tc-advanced-search input {
width: 60%;
}
.tc-search a svg {
width: 1.2em;
height: 1.2em;
vertical-align: middle;
}
.tc-page-controls {
margin-top: 14px;
font-size: 1.5em;
}
.tc-page-controls button {
margin-right: 0.5em;
}
.tc-page-controls a.tc-tiddlylink:hover {
text-decoration: none;
}
.tc-page-controls img {
width: 1em;
}
.tc-page-controls svg {
fill: <<colour sidebar-controls-foreground>>;
}
.tc-page-controls button:hover svg, .tc-page-controls a:hover svg {
fill: <<colour sidebar-controls-foreground-hover>>;
}
.tc-menu-list-item {
white-space: nowrap;
}
.tc-menu-list-count {
font-weight: bold;
}
.tc-menu-list-subitem {
padding-left: 7px;
}
.tc-story-river {
position: relative;
}
@media (max-width: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint}}) {
.tc-sidebar-header {
padding: 14px;
min-height: 32px;
margin-top: {{$:/themes/tiddlywiki/vanilla/metrics/storytop}};
}
.tc-story-river {
position: relative;
padding: 0;
}
}
@media (min-width: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint}}) {
.tc-message-box {
margin: 21px -21px 21px -21px;
}
.tc-sidebar-scrollable {
position: fixed;
top: {{$:/themes/tiddlywiki/vanilla/metrics/storytop}};
left: {{$:/themes/tiddlywiki/vanilla/metrics/storyright}};
bottom: 0;
right: 0;
overflow-y: auto;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
margin: 0 0 0 -42px;
padding: 71px 0 28px 42px;
}
.tc-story-river {
position: relative;
left: {{$:/themes/tiddlywiki/vanilla/metrics/storyleft}};
top: {{$:/themes/tiddlywiki/vanilla/metrics/storytop}};
width: {{$:/themes/tiddlywiki/vanilla/metrics/storywidth}};
padding: 42px 42px 42px 42px;
}
<<if-no-sidebar "
.tc-story-river {
width: auto;
}
">>
}
@media print {
body.tc-body {
background-color: transparent;
}
.tc-sidebar-header, .tc-topbar {
display: none;
}
.tc-story-river {
margin: 0;
padding: 0;
}
.tc-story-river .tc-tiddler-frame {
margin: 0;
border: none;
padding: 28px;
}
}
/*
** Tiddler styles
*/
.tc-tiddler-frame {
position: relative;
margin-bottom: 28px;
background-color: <<colour tiddler-background>>;
border: 1px solid <<colour tiddler-border>>;
}
{{$:/themes/tiddlywiki/vanilla/sticky}}
.tc-tiddler-info {
padding: 14px 42px 14px 42px;
background-color: <<colour tiddler-info-background>>;
border-top: 1px solid <<colour tiddler-info-border>>;
border-bottom: 1px solid <<colour tiddler-info-border>>;
}
.tc-tiddler-info p {
margin-top: 3px;
margin-bottom: 3px;
}
.tc-tiddler-info .tc-tab-buttons button.tc-tab-selected {
background-color: <<colour tiddler-info-tab-background>>;
border-bottom: 1px solid <<colour tiddler-info-tab-background>>;
}
.tc-view-field-table {
width: 100%;
}
.tc-view-field-name {
width: 1%; /* Makes this column be as narrow as possible */
text-align: right;
font-style: italic;
font-weight: 200;
}
.tc-view-field-value {
}
@media (max-width: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint}}) {
.tc-tiddler-frame {
padding: 14px 14px 14px 14px;
}
.tc-tiddler-info {
margin: 0 -14px 0 -14px;
}
}
@media (min-width: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint}}) {
.tc-tiddler-frame {
padding: 28px 42px 42px 42px;
width: {{$:/themes/tiddlywiki/vanilla/metrics/tiddlerwidth}};
border-radius: 2px;
}
<<if-no-sidebar "
.tc-tiddler-frame {
width: 100%;
}
">>
.tc-tiddler-info {
margin: 0 -42px 0 -42px;
}
}
.tc-site-title,
.tc-titlebar {
font-weight: 300;
font-size: 2.35em;
line-height: 1.2em;
color: <<colour tiddler-title-foreground>>;
margin: 0;
}
.tc-site-title {
color: <<colour site-title-foreground>>;
}
.tc-tiddler-title-icon {
vertical-align: middle;
}
.tc-system-title-prefix {
color: <<colour muted-foreground>>;
}
.tc-titlebar h2 {
font-size: 1em;
display: inline;
}
.tc-titlebar img {
height: 1em;
}
.tc-subtitle {
font-size: 0.9em;
color: <<colour tiddler-subtitle-foreground>>;
font-weight: 300;
}
.tc-tiddler-missing .tc-title {
font-style: italic;
font-weight: normal;
}
.tc-tiddler-frame .tc-tiddler-controls {
float: right;
}
.tc-tiddler-controls .tc-drop-down {
font-size: 0.6em;
}
.tc-tiddler-controls .tc-drop-down .tc-drop-down {
font-size: 1em;
}
.tc-tiddler-controls > span > button {
vertical-align: baseline;
margin-left:5px;
}
.tc-tiddler-controls button svg, .tc-tiddler-controls button img,
.tc-search button svg, .tc-search a svg {
height: 0.75em;
fill: <<colour tiddler-controls-foreground>>;
}
.tc-tiddler-controls button.tc-selected svg,
.tc-page-controls button.tc-selected svg {
fill: <<colour tiddler-controls-foreground-selected>>;
}
.tc-tiddler-controls button.tc-btn-invisible:hover svg,
.tc-search button:hover svg, .tc-search a:hover svg {
fill: <<colour tiddler-controls-foreground-hover>>;
}
@media print {
.tc-tiddler-controls {
display: none;
}
}
.tc-tiddler-help { /* Help prompts within tiddler template */
color: <<colour muted-foreground>>;
margin-top: 14px;
}
.tc-tiddler-help a.tc-tiddlylink {
color: <<colour very-muted-foreground>>;
}
.tc-tiddler-frame input.tc-edit-texteditor, .tc-tiddler-frame textarea.tc-edit-texteditor {
width: 100%;
padding: 3px 3px 3px 3px;
border: 1px solid <<colour tiddler-editor-border>>;
line-height: 1.3em;
-webkit-appearance: none;
margin: 4px 0 4px 0;
}
.tc-tiddler-frame .tc-binary-warning {
width: 100%;
height: 5em;
text-align: center;
padding: 3em 3em 6em 3em;
background: <<colour alert-background>>;
border: 1px solid <<colour alert-border>>;
}
.tc-tiddler-frame input.tc-edit-texteditor {
background-color: <<colour tiddler-editor-background>>;
}
canvas.tc-edit-bitmapeditor {
border: 6px solid <<colour tiddler-editor-border-image>>;
cursor: crosshair;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
margin-top: 6px;
margin-bottom: 6px;
}
.tc-edit-bitmapeditor-width {
display: block;
}
.tc-edit-bitmapeditor-height {
display: block;
}
.tc-tiddler-body {
clear: both;
}
.tc-tiddler-frame .tc-tiddler-body {
font-size: {{$:/themes/tiddlywiki/vanilla/metrics/bodyfontsize}};
line-height: {{$:/themes/tiddlywiki/vanilla/metrics/bodylineheight}};
}
.tc-titlebar, .tc-tiddler-edit-title {
overflow: hidden; /* https://github.com/Jermolene/TiddlyWiki5/issues/282 */
}
html body.tc-body.tc-single-tiddler-window {
margin: 1em;
background: <<colour tiddler-background>>;
}
.tc-single-tiddler-window img,
.tc-single-tiddler-window svg,
.tc-single-tiddler-window canvas,
.tc-single-tiddler-window embed,
.tc-single-tiddler-window iframe {
max-width: 100%;
}
/*
** Adjustments for fluid-fixed mode
*/
@media (min-width: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint}}) {
<<if-fluid-fixed text:"""
.tc-story-river {
padding-right: 0;
position: relative;
width: auto;
left: 0;
margin-left: {{$:/themes/tiddlywiki/vanilla/metrics/storyleft}};
margin-right: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarwidth}};
}
.tc-tiddler-frame {
width: 100%;
}
.tc-sidebar-scrollable {
left: auto;
bottom: 0;
right: 0;
width: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarwidth}};
}
body.tc-body .tc-storyview-zoomin-tiddler {
width: 100%;
width: calc(100% - 42px);
}
""" hiddenSidebarText:"""
.tc-story-river {
padding-right: 3em;
margin-right: 0;
}
body.tc-body .tc-storyview-zoomin-tiddler {
width: 100%;
width: calc(100% - 84px);
}
""">>
}
/*
** Toolbar buttons
*/
.tc-page-controls svg.tc-image-new-button {
fill: <<colour toolbar-new-button>>;
}
.tc-page-controls svg.tc-image-options-button {
fill: <<colour toolbar-options-button>>;
}
.tc-page-controls svg.tc-image-save-button {
fill: <<colour toolbar-save-button>>;
}
.tc-tiddler-controls button svg.tc-image-info-button {
fill: <<colour toolbar-info-button>>;
}
.tc-tiddler-controls button svg.tc-image-edit-button {
fill: <<colour toolbar-edit-button>>;
}
.tc-tiddler-controls button svg.tc-image-close-button {
fill: <<colour toolbar-close-button>>;
}
.tc-tiddler-controls button svg.tc-image-delete-button {
fill: <<colour toolbar-delete-button>>;
}
.tc-tiddler-controls button svg.tc-image-cancel-button {
fill: <<colour toolbar-cancel-button>>;
}
.tc-tiddler-controls button svg.tc-image-done-button {
fill: <<colour toolbar-done-button>>;
}
/*
** Tiddler edit mode
*/
.tc-tiddler-edit-frame em.tc-edit {
color: <<colour muted-foreground>>;
font-style: normal;
}
.tc-edit-type-dropdown a.tc-tiddlylink-missing {
font-style: normal;
}
.tc-edit-tags {
border: 1px solid <<colour tiddler-editor-border>>;
padding: 4px 8px 4px 8px;
}
.tc-edit-add-tag {
display: inline-block;
}
.tc-edit-add-tag .tc-add-tag-name input {
width: 50%;
}
.tc-edit-tags .tc-tag-label {
display: inline-block;
}
.tc-edit-tags-list {
margin: 14px 0 14px 0;
}
.tc-remove-tag-button {
padding-left: 4px;
}
.tc-tiddler-preview {
overflow: auto;
}
.tc-tiddler-preview-preview {
float: right;
width: 48%;
border: 1px solid <<colour tiddler-editor-border>>;
margin: 4px 3px 3px 3px;
padding: 3px 3px 3px 3px;
}
.tc-tiddler-preview-edit {
width: 48%;
}
.tc-edit-fields {
width: 100%;
}
.tc-edit-fields table, .tc-edit-fields tr, .tc-edit-fields td {
border: none;
padding: 4px;
}
.tc-edit-fields > tbody > .tc-edit-field:nth-child(odd) {
background-color: <<colour tiddler-editor-fields-odd>>;
}
.tc-edit-fields > tbody > .tc-edit-field:nth-child(even) {
background-color: <<colour tiddler-editor-fields-even>>;
}
.tc-edit-field-name {
text-align: right;
}
.tc-edit-field-value input {
width: 100%;
}
.tc-edit-field-remove {
}
.tc-edit-field-remove svg {
height: 1em;
width: 1em;
fill: <<colour muted-foreground>>;
vertical-align: middle;
}
.tc-edit-field-add-name {
display: inline-block;
width: 15%;
}
.tc-edit-field-add-value {
display: inline-block;
width: 40%;
}
.tc-edit-field-add-button {
display: inline-block;
width: 10%;
}
/*
** Storyview Classes
*/
.tc-storyview-zoomin-tiddler {
position: absolute;
display: block;
width: 100%;
}
@media (min-width: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint}}) {
.tc-storyview-zoomin-tiddler {
width: calc(100% - 84px);
}
}
/*
** Dropdowns
*/
.tc-btn-dropdown {
text-align: left;
}
.tc-btn-dropdown svg, .tc-btn-dropdown img {
height: 1em;
width: 1em;
fill: <<colour muted-foreground>>;
}
.tc-drop-down-wrapper {
position: relative;
}
.tc-drop-down {
min-width: 380px;
border: 1px solid <<colour dropdown-border>>;
background-color: <<colour dropdown-background>>;
padding: 7px 0 7px 0;
margin: 4px 0 0 0;
white-space: nowrap;
text-shadow: none;
line-height: 1.4;
}
.tc-drop-down .tc-drop-down {
margin-left: 14px;
}
.tc-drop-down button svg, .tc-drop-down a svg {
fill: <<colour foreground>>;
}
.tc-drop-down button.tc-btn-invisible:hover svg {
fill: <<colour foreground>>;
}
.tc-drop-down p {
padding: 0 14px 0 14px;
}
.tc-drop-down svg {
width: 1em;
height: 1em;
}
.tc-drop-down img {
width: 1em;
}
.tc-drop-down-language-chooser img {
width: 2em;
vertical-align: baseline;
}
.tc-drop-down a, .tc-drop-down button {
display: block;
padding: 0 14px 0 14px;
width: 100%;
text-align: left;
color: <<colour foreground>>;
line-height: 1.4;
}
.tc-drop-down .tc-prompt {
padding: 0 14px;
}
.tc-drop-down .tc-chooser {
border: none;
}
.tc-drop-down .tc-chooser .tc-swatches-horiz {
font-size: 0.4em;
padding-left: 1.2em;
}
.tc-drop-down .tc-file-input-wrapper {
width: 100%;
}
.tc-drop-down .tc-file-input-wrapper button {
color: <<colour foreground>>;
}
.tc-drop-down a:hover, .tc-drop-down button:hover, .tc-drop-down .tc-file-input-wrapper:hover button {
color: <<colour tiddler-link-background>>;
background-color: <<colour tiddler-link-foreground>>;
text-decoration: none;
}
.tc-drop-down .tc-tab-buttons button {
background-color: <<colour dropdown-tab-background>>;
}
.tc-drop-down .tc-tab-buttons button.tc-tab-selected {
background-color: <<colour dropdown-tab-background-selected>>;
border-bottom: 1px solid <<colour dropdown-tab-background-selected>>;
}
.tc-drop-down-bullet {
display: inline-block;
width: 0.5em;
}
.tc-drop-down .tc-tab-contents a {
padding: 0 0.5em 0 0.5em;
}
.tc-block-dropdown-wrapper {
position: relative;
}
.tc-block-dropdown {
position: absolute;
min-width: 220px;
border: 1px solid <<colour dropdown-border>>;
background-color: <<colour dropdown-background>>;
padding: 7px 0;
margin: 4px 0 0 0;
white-space: nowrap;
z-index: 1000;
text-shadow: none;
}
.tc-block-dropdown.tc-search-drop-down {
margin-left: -12px;
}
.tc-block-dropdown a {
display: block;
padding: 4px 14px 4px 14px;
}
.tc-block-dropdown.tc-search-drop-down a {
display: block;
padding: 0px 10px 0px 10px;
}
.tc-drop-down .tc-dropdown-item,
.tc-block-dropdown .tc-dropdown-item {
padding: 4px 14px 4px 7px;
color: <<colour muted-foreground>>;
}
.tc-block-dropdown a:hover {
color: <<colour tiddler-link-background>>;
background-color: <<colour tiddler-link-foreground>>;
text-decoration: none;
}
.tc-search-results {
padding: 0 7px 0 7px;
}
/*
** Modals
*/
.tc-modal-wrapper {
position: fixed;
overflow: auto;
overflow-y: scroll;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.tc-modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1000;
background-color: <<colour modal-backdrop>>;
}
.tc-modal {
z-index: 1100;
background-color: <<colour modal-background>>;
border: 1px solid <<colour modal-border>>;
}
@media (max-width: 55em) {
.tc-modal {
position: fixed;
top: 1em;
left: 1em;
right: 1em;
}
.tc-modal-body {
overflow-y: auto;
max-height: 400px;
max-height: 60vh;
}
}
@media (min-width: 55em) {
.tc-modal {
position: fixed;
top: 2em;
left: 25%;
width: 50%;
}
.tc-modal-body {
overflow-y: auto;
max-height: 400px;
max-height: 60vh;
}
}
.tc-modal-header {
padding: 9px 15px;
border-bottom: 1px solid <<colour modal-header-border>>;
}
.tc-modal-header h3 {
margin: 0;
line-height: 30px;
}
.tc-modal-header img, .tc-modal-header svg {
width: 1em;
height: 1em;
}
.tc-modal-body {
padding: 15px;
}
.tc-modal-footer {
padding: 14px 15px 15px;
margin-bottom: 0;
text-align: right;
background-color: <<colour modal-footer-background>>;
border-top: 1px solid <<colour modal-footer-border>>;
}
/*
** Notifications
*/
.tc-notification {
position: fixed;
top: 14px;
right: 42px;
z-index: 1300;
max-width: 280px;
padding: 0 14px 0 14px;
background-color: <<colour notification-background>>;
border: 1px solid <<colour notification-border>>;
}
/*
** Tabs
*/
.tc-tab-set.tc-vertical {
display: -webkit-flex;
display: flex;
}
.tc-tab-buttons {
font-size: 0.85em;
padding-top: 1em;
margin-bottom: -2px;
}
.tc-tab-buttons.tc-vertical {
z-index: 100;
display: block;
padding-top: 14px;
vertical-align: top;
text-align: right;
margin-bottom: inherit;
margin-right: -1px;
max-width: 33%;
-webkit-flex: 0 0 auto;
flex: 0 0 auto;
}
.tc-tab-buttons button.tc-tab-selected {
color: <<colour tab-foreground-selected>>;
background-color: <<colour tab-background-selected>>;
border-left: 1px solid <<colour tab-border-selected>>;
border-top: 1px solid <<colour tab-border-selected>>;
border-right: 1px solid <<colour tab-border-selected>>;
}
.tc-tab-buttons button {
color: <<colour tab-foreground>>;
padding: 3px 5px 3px 5px;
margin-right: 0.3em;
font-weight: 300;
border: none;
background: inherit;
background-color: <<colour tab-background>>;
border-left: 1px solid <<colour tab-border>>;
border-top: 1px solid <<colour tab-border>>;
border-right: 1px solid <<colour tab-border>>;
border-top-left-radius: 2px;
border-top-right-radius: 2px;
}
.tc-tab-buttons.tc-vertical button {
display: block;
width: 100%;
margin-top: 3px;
margin-right: 0;
text-align: right;
background-color: <<colour tab-background>>;
border-left: 1px solid <<colour tab-border>>;
border-bottom: 1px solid <<colour tab-border>>;
border-right: none;
border-top-left-radius: 2px;
border-bottom-left-radius: 2px;
}
.tc-tab-buttons.tc-vertical button.tc-tab-selected {
background-color: <<colour tab-background-selected>>;
border-right: 1px solid <<colour tab-background-selected>>;
}
.tc-tab-divider {
border-top: 1px solid <<colour tab-divider>>;
}
.tc-tab-divider.tc-vertical {
display: none;
}
.tc-tab-content {
margin-top: 14px;
}
.tc-tab-content.tc-vertical {
display: inline-block;
vertical-align: top;
padding-top: 0;
padding-left: 14px;
border-left: 1px solid <<colour tab-border>>;
-webkit-flex: 1 0 70%;
flex: 1 0 70%;
}
.tc-sidebar-lists .tc-tab-buttons {
margin-bottom: -1px;
}
.tc-sidebar-lists .tc-tab-buttons button.tc-tab-selected {
background-color: <<colour sidebar-tab-background-selected>>;
color: <<colour sidebar-tab-foreground-selected>>;
border-left: 1px solid <<colour sidebar-tab-border-selected>>;
border-top: 1px solid <<colour sidebar-tab-border-selected>>;
border-right: 1px solid <<colour sidebar-tab-border-selected>>;
}
.tc-sidebar-lists .tc-tab-buttons button {
display: inline;
width: auto;
background-color: <<colour sidebar-tab-background>>;
color: <<colour sidebar-tab-foreground>>;
border-left: 1px solid <<colour sidebar-tab-border>>;
border-top: 1px solid <<colour sidebar-tab-border>>;
border-right: 1px solid <<colour sidebar-tab-border>>;
}
.tc-sidebar-lists .tc-tab-divider {
border-top: 1px solid <<colour sidebar-tab-divider>>;
}
.tc-more-sidebar .tc-tab-buttons button {
display: block;
width: 100%;
background-color: <<colour sidebar-tab-background>>;
border-top: none;
border-left: none;
border-bottom: none;
border-right: 1px solid #ccc;
margin-bottom: inherit;
}
.tc-more-sidebar .tc-tab-buttons button.tc-tab-selected {
background-color: <<colour sidebar-tab-background-selected>>;
border: none;
}
/*
** Alerts
*/
.tc-alerts {
position: fixed;
top: 0;
left: 0;
max-width: 500px;
z-index: 20000;
}
.tc-alert {
position: relative;
margin: 28px;
padding: 14px 14px 14px 14px;
border: 2px solid <<colour alert-border>>;
background-color: <<colour alert-background>>;
}
.tc-alert-toolbar {
position: absolute;
top: 14px;
right: 14px;
}
.tc-alert-toolbar svg {
fill: <<colour alert-muted-foreground>>;
}
.tc-alert-subtitle {
color: <<colour alert-muted-foreground>>;
font-weight: bold;
}
.tc-alert-highlight {
color: <<colour alert-highlight>>;
}
@media (min-width: {{$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint}}) {
.tc-static-alert {
position: relative;
}
.tc-static-alert-inner {
position: absolute;
z-index: 100;
}
}
.tc-static-alert-inner {
padding: 0 2px 2px 42px;
color: <<colour static-alert-foreground>>;
}
/*
** Control panel
*/
.tc-control-panel td {
padding: 4px;
}
.tc-control-panel table, .tc-control-panel table input, .tc-control-panel table textarea {
width: 100%;
}
.tc-plugin-info {
display: block;
border: 1px solid <<colour muted-foreground>>;
background-colour: <<colour background>>;
margin: 0.5em 0 0.5em 0;
padding: 4px;
}
.tc-plugin-info-disabled {
background: -webkit-repeating-linear-gradient(45deg, #ff0, #ff0 10px, #eee 10px, #eee 20px);
background: repeating-linear-gradient(45deg, #ff0, #ff0 10px, #eee 10px, #eee 20px);
}
.tc-plugin-info-disabled:hover {
background: -webkit-repeating-linear-gradient(45deg, #aa0, #aa0 10px, #888 10px, #888 20px);
background: repeating-linear-gradient(45deg, #aa0, #aa0 10px, #888 10px, #888 20px);
}
a.tc-tiddlylink.tc-plugin-info:hover {
text-decoration: none;
background-color: <<colour primary>>;
color: <<colour background>>;
fill: <<colour foreground>>;
}
a.tc-tiddlylink.tc-plugin-info:hover .tc-plugin-info > .tc-plugin-info-chunk > svg {
fill: <<colour foreground>>;
}
.tc-plugin-info-chunk {
display: inline-block;
vertical-align: middle;
}
.tc-plugin-info-chunk h1 {
font-size: 1em;
margin: 2px 0 2px 0;
}
.tc-plugin-info-chunk h2 {
font-size: 0.8em;
margin: 2px 0 2px 0;
}
.tc-plugin-info-chunk div {
font-size: 0.7em;
margin: 2px 0 2px 0;
}
.tc-plugin-info:hover > .tc-plugin-info-chunk > img, .tc-plugin-info:hover > .tc-plugin-info-chunk > svg {
width: 2em;
height: 2em;
fill: <<colour foreground>>;
}
.tc-plugin-info > .tc-plugin-info-chunk > img, .tc-plugin-info > .tc-plugin-info-chunk > svg {
width: 2em;
height: 2em;
fill: <<colour muted-foreground>>;
}
.tc-plugin-info.tc-small-icon > .tc-plugin-info-chunk > img, .tc-plugin-info.tc-small-icon > .tc-plugin-info-chunk > svg {
width: 1em;
height: 1em;
}
.tc-plugin-info-dropdown {
border: 1px solid <<colour muted-foreground>>;
margin-top: -8px;
}
.tc-plugin-info-dropdown-message {
background: <<colour message-background>>;
padding: 0.5em 1em 0.5em 1em;
font-weight: bold;
font-size: 0.8em;
}
.tc-plugin-info-dropdown-body {
padding: 1em 1em 1em 1em;
}
/*
** Message boxes
*/
.tc-message-box {
border: 1px solid <<colour message-border>>;
background: <<colour message-background>>;
padding: 0px 21px 0px 21px;
font-size: 12px;
line-height: 18px;
color: <<colour message-foreground>>;
}
/*
** Pictures
*/
.tc-bordered-image {
border: 1px solid <<colour muted-foreground>>;
padding: 5px;
margin: 5px;
}
/*
** Floats
*/
.tc-float-right {
float: right;
}
/*
** Chooser
*/
.tc-chooser {
border: 1px solid <<colour table-border>>;
}
.tc-chooser-item {
border: 8px;
padding: 2px 4px;
}
.tc-chooser-item a.tc-tiddlylink {
display: block;
text-decoration: none;
color: <<colour tiddler-link-foreground>>;
background-color: <<colour tiddler-link-background>>;
}
.tc-chooser-item a.tc-tiddlylink:hover {
text-decoration: none;
color: <<colour tiddler-link-background>>;
background-color: <<colour tiddler-link-foreground>>;
}
/*
** Palette swatches
*/
.tc-swatches-horiz {
}
.tc-swatches-horiz .tc-swatch {
display: inline-block;
}
.tc-swatch {
width: 2em;
height: 2em;
margin: 0.4em;
border: 1px solid #888;
}
/*
** Table of contents
*/
.tc-sidebar-lists .tc-table-of-contents {
white-space: nowrap;
}
.tc-table-of-contents button {
color: <<colour sidebar-foreground>>;
}
.tc-table-of-contents svg {
width: 0.7em;
height: 0.7em;
vertical-align: middle;
fill: <<colour sidebar-foreground>>;
}
.tc-table-of-contents ol {
list-style-type: none;
padding-left: 0;
}
.tc-table-of-contents ol ol {
padding-left: 1em;
}
.tc-table-of-contents li {
font-size: 1.0em;
font-weight: bold;
}
.tc-table-of-contents li a {
font-weight: bold;
}
.tc-table-of-contents li li {
font-size: 0.95em;
font-weight: normal;
line-height: 1.4;
}
.tc-table-of-contents li li a {
font-weight: normal;
}
.tc-table-of-contents li li li {
font-size: 0.95em;
font-weight: 200;
line-height: 1.5;
}
.tc-table-of-contents li li li a {
font-weight: bold;
}
.tc-table-of-contents li li li li {
font-size: 0.95em;
font-weight: 200;
}
.tc-tabbed-table-of-contents {
display: -webkit-flex;
display: flex;
}
.tc-tabbed-table-of-contents .tc-table-of-contents {
z-index: 100;
display: inline-block;
padding-left: 1em;
max-width: 50%;
-webkit-flex: 0 0 auto;
flex: 0 0 auto;
background: <<colour tab-background>>;
border-left: 1px solid <<colour tab-border>>;
border-top: 1px solid <<colour tab-border>>;
border-bottom: 1px solid <<colour tab-border>>;
}
.tc-tabbed-table-of-contents .tc-table-of-contents .toc-item > a,
.tc-tabbed-table-of-contents .tc-table-of-contents .toc-item-selected > a {
display: block;
padding: 0.12em 1em 0.12em 0.25em;
}
.tc-tabbed-table-of-contents .tc-table-of-contents .toc-item > a {
border-top: 1px solid <<colour tab-background>>;
border-left: 1px solid <<colour tab-background>>;
border-bottom: 1px solid <<colour tab-background>>;
}
.tc-tabbed-table-of-contents .tc-table-of-contents .toc-item > a:hover {
text-decoration: none;
border-top: 1px solid <<colour tab-border>>;
border-left: 1px solid <<colour tab-border>>;
border-bottom: 1px solid <<colour tab-border>>;
background: <<colour tab-border>>;
}
.tc-tabbed-table-of-contents .tc-table-of-contents .toc-item-selected > a {
border-top: 1px solid <<colour tab-border>>;
border-left: 1px solid <<colour tab-border>>;
border-bottom: 1px solid <<colour tab-border>>;
background: <<colour background>>;
margin-right: -1px;
}
.tc-tabbed-table-of-contents .tc-table-of-contents .toc-item-selected > a:hover {
text-decoration: none;
}
.tc-tabbed-table-of-contents .tc-tabbed-table-of-contents-content {
display: inline-block;
vertical-align: top;
padding-left: 1.5em;
padding-right: 1.5em;
border: 1px solid <<colour tab-border>>;
-webkit-flex: 1 0 50%;
flex: 1 0 50%;
}
/*
** Dirty indicator
*/
body.tc-dirty span.tc-dirty-indicator, body.tc-dirty span.tc-dirty-indicator svg {
fill: <<colour dirty-indicator>>;
color: <<colour dirty-indicator>>;
}
/*
** File inputs
*/
.tc-file-input-wrapper {
position: relative;
overflow: hidden;
display: inline-block;
vertical-align: middle;
}
.tc-file-input-wrapper input[type=file] {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
font-size: 999px;
max-width: 100%;
max-height: 100%;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: pointer;
display: inline-block;
}
/*
** Thumbnail macros
*/
.tc-thumbnail-wrapper {
position: relative;
display: inline-block;
margin: 6px;
vertical-align: top;
}
.tc-thumbnail-right-wrapper {
float:right;
margin: 0.5em 0 0.5em 0.5em;
}
.tc-thumbnail-image {
text-align: center;
overflow: hidden;
border-radius: 3px;
}
.tc-thumbnail-image svg,
.tc-thumbnail-image img {
filter: alpha(opacity=1);
opacity: 1;
min-width: 100%;
min-height: 100%;
max-width: 100%;
}
.tc-thumbnail-wrapper:hover .tc-thumbnail-image svg,
.tc-thumbnail-wrapper:hover .tc-thumbnail-image img {
filter: alpha(opacity=0.8);
opacity: 0.8;
}
.tc-thumbnail-background {
position: absolute;
border-radius: 3px;
}
.tc-thumbnail-icon svg,
.tc-thumbnail-icon img {
width: 3em;
height: 3em;
<<filter "drop-shadow(2px 2px 4px rgba(0,0,0,0.3))">>
}
.tc-thumbnail-wrapper:hover .tc-thumbnail-icon svg,
.tc-thumbnail-wrapper:hover .tc-thumbnail-icon img {
fill: #fff;
<<filter "drop-shadow(3px 3px 4px rgba(0,0,0,0.6))">>
}
.tc-thumbnail-icon {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: -webkit-flex;
-webkit-align-items: center;
-webkit-justify-content: center;
display: flex;
align-items: center;
justify-content: center;
}
.tc-thumbnail-caption {
position: absolute;
background-color: #777;
color: #fff;
text-align: center;
bottom: 0;
width: 100%;
filter: alpha(opacity=0.9);
opacity: 0.9;
line-height: 1.4;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
}
.tc-thumbnail-wrapper:hover .tc-thumbnail-caption {
filter: alpha(opacity=1);
opacity: 1;
}
/*
** Errors
*/
.tc-error {
background: #f00;
color: #fff;
}
/*! normalize.css v3.0.0 | MIT License | git.io/normalize */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS text size adjust after orientation change, without disabling
* user zoom.
*/
html {
font-family: sans-serif; /* 1 */
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/**
* Remove default margin.
*/
body {
margin: 0;
}
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined in IE 8/9.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
audio,
canvas,
progress,
video {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address `[hidden]` styling not present in IE 8/9.
* Hide the `template` element in IE, Safari, and Firefox < 22.
*/
[hidden],
template {
display: none;
}
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
a {
background: transparent;
}
/**
* Improve readability when focused and also mouse hovered in all browsers.
*/
a:active,
a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9, Safari 5, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome.
*/
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari 5 and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari 5, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9.
*/
img {
border: 0;
}
/**
* Correct overflow displayed oddly in IE 9.
*/
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari 5.
*/
figure {
margin: 1em 40px;
}
/**
* Address differences between Firefox and other browsers.
*/
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
/**
* Contain overflow in all browsers.
*/
pre {
overflow: auto;
}
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome.
*/
button,
input,
optgroup,
select,
textarea {
color: inherit; /* 1 */
font: inherit; /* 2 */
margin: 0; /* 3 */
}
/**
* Address `overflow` set to `hidden` in IE 8/9/10.
*/
button {
overflow: visible;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8+, and Opera
* Correct `select` style inheritance in Firefox.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* Remove inner padding and border in Firefox 4+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
input {
line-height: normal;
}
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
* (include `-moz` to future-proof).
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box; /* 2 */
box-sizing: content-box;
}
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0; /* 1 */
padding: 0; /* 2 */
}
/**
* Remove default vertical scrollbar in IE 8/9.
*/
textarea {
overflow: auto;
}
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
optgroup {
font-weight: bold;
}
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
Monaco, Consolas, "Lucida Console", "DejaVu Sans Mono", monospace
"Helvetica Neue", Helvetica, Arial, "Lucida Grande", "DejaVu Sans", sans-serif
<$reveal state="$:/themes/tiddlywiki/vanilla/options/stickytitles" type="match" text="yes">
``
.tc-tiddler-title {
position: -webkit-sticky;
position: -moz-sticky;
position: -o-sticky;
position: -ms-sticky;
position: sticky;
top: 0px;
background: ``<<colour tiddler-background>>``;
z-index: 500;
}
``
</$reveal>
\define backgroundimage-dropdown()
<div class="tc-drop-down-wrapper">
<$button popup=<<qualify "$:/state/popup/themetweaks/backgroundimage">> class="tc-btn-invisible tc-btn-dropdown">{{$:/core/images/down-arrow}}</$button>
<$reveal state=<<qualify "$:/state/popup/themetweaks/backgroundimage">> type="popup" position="belowleft" text="" default="">
<div class="tc-drop-down">
<$linkcatcher to="$:/themes/tiddlywiki/vanilla/settings/backgroundimage">
<$link to="">
(none)
</$link>
<hr>
<$list filter="[all[shadows+tiddlers]is[image]] -[type[application/pdf]] +[sort[title]]">
<$link to={{!!title}}>
<$transclude/> <$view field="title"/>
</$link>
</$list>
</$linkcatcher>
</div>
</$reveal>
</div>
\end
\define backgroundimageattachment-dropdown()
<$select tiddler="$:/themes/tiddlywiki/vanilla/settings/backgroundimageattachment" default="scroll">
<option value="scroll">Scroll with tiddlers</option>
<option value="fixed">Fixed to window</option>
</$select>
\end
\define backgroundimagesize-dropdown()
<$select tiddler="$:/themes/tiddlywiki/vanilla/settings/backgroundimagesize" default="scroll">
<option value="auto">Auto</option>
<option value="cover">Cover</option>
<option value="contain">Contain</option>
</$select>
\end
You can tweak certain aspects of the ''Vanilla'' theme.
! Options
|[[Sidebar layout|$:/themes/tiddlywiki/vanilla/options/sidebarlayout]] |<$select tiddler="$:/themes/tiddlywiki/vanilla/options/sidebarlayout"><option value="fixed-fluid">Fixed story, fluid sidebar</option><option value="fluid-fixed">Fluid story, fixed sidebar</option></$select> |
|[[Sticky titles|$:/themes/tiddlywiki/vanilla/options/stickytitles]]<br>//Causes tiddler titles to "stick" to the top of the browser window. Caution: Does not work at all with Chrome, and causes some layout issues in Firefox// |<$select tiddler="$:/themes/tiddlywiki/vanilla/options/stickytitles"><option value="no">No</option><option value="yes">Yes</option></$select> |
! Settings
|[[Font family|$:/themes/tiddlywiki/vanilla/settings/fontfamily]] |<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/settings/fontfamily" default="" tag="input"/> | |
|[[Code font family|$:/themes/tiddlywiki/vanilla/settings/codefontfamily]] |<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/settings/codefontfamily" default="" tag="input"/> | |
|[[Page background image|$:/themes/tiddlywiki/vanilla/settings/backgroundimage]] |<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/settings/backgroundimage" default="" tag="input"/> |<<backgroundimage-dropdown>> |
|[[Page background image attachment |$:/themes/tiddlywiki/vanilla/settings/backgroundimageattachment]] |<<backgroundimageattachment-dropdown>> | |
|[[Page background image size |$:/themes/tiddlywiki/vanilla/settings/backgroundimagesize]] |<<backgroundimagesize-dropdown>> | |
! Sizes
|[[Font size|$:/themes/tiddlywiki/vanilla/metrics/fontsize]] |<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/fontsize" default="" tag="input"/> |
|[[Line height|$:/themes/tiddlywiki/vanilla/metrics/lineheight]] |<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/lineheight" default="" tag="input"/> |
|[[Font size for tiddler body|$:/themes/tiddlywiki/vanilla/metrics/bodyfontsize]] |<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/bodyfontsize" default="" tag="input"/> |
|[[Line height for tiddler body|$:/themes/tiddlywiki/vanilla/metrics/bodylineheight]] |<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/bodylineheight" default="" tag="input"/> |
|[[Story left position|$:/themes/tiddlywiki/vanilla/metrics/storyleft]]<br>//how far the left margin of the story river<br>(tiddler area) is from the left of the page// |^<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/storyleft" default="" tag="input"/> |
|[[Story top position|$:/themes/tiddlywiki/vanilla/metrics/storytop]]<br>//how far the top margin of the story river<br>is from the top of the page// |^<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/storytop" default="" tag="input"/> |
|[[Story right|$:/themes/tiddlywiki/vanilla/metrics/storyright]]<br>//how far the left margin of the sidebar <br>is from the left of the page// |^<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/storyright" default="" tag="input"/> |
|[[Story width|$:/themes/tiddlywiki/vanilla/metrics/storywidth]]<br>//the overall width of the story river// |^<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/storywidth" default="" tag="input"/> |
|[[Tiddler width|$:/themes/tiddlywiki/vanilla/metrics/tiddlerwidth]]<br>//within the story river//<br> |^<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/tiddlerwidth" default="" tag="input"/> |
|[[Sidebar breakpoint|$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint]]<br>//the minimum page width at which the story<br>river and sidebar will appear side by side// |^<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/sidebarbreakpoint" default="" tag="input"/> |
|[[Sidebar width|$:/themes/tiddlywiki/vanilla/metrics/sidebarwidth]]<br>//the width of the sidebar in fluid-fixed layout// |^<$edit-text tiddler="$:/themes/tiddlywiki/vanilla/metrics/sidebarwidth" default="" tag="input"/> |
<style>
.iframeframe {
border: 2px solid;
width: 100%;
resize: vertical;
overflow: auto;
}
.iframeframe iframe{
margin:0;
border:0;
padding:0;
width: 100%;
height: 100%;
}
</style>
<$link><$view field=title/></$link>
<$button><$action-setfield reset="reset"/>Go!</$button>
<hr>
{{}}
<div style="text-align: center ; "><h1>Python Playground - by BJ</h1> modify the testcode and press the Go! button</div>
\define lingo-base() $:/language/ControlPanel/Basics/
Welcome to ~TiddlyWiki and the ~TiddlyWiki community
Before you start storing important information in ~TiddlyWiki it is important to make sure that you can reliably save changes. See http://tiddlywiki.com/#GettingStarted for details
!! Set up this ~TiddlyWiki
<div class="tc-control-panel">
|<$link to="$:/SiteTitle"><<lingo Title/Prompt>></$link> |<$edit-text tiddler="$:/SiteTitle" default="" tag="input"/> |
|<$link to="$:/SiteSubtitle"><<lingo Subtitle/Prompt>></$link> |<$edit-text tiddler="$:/SiteSubtitle" default="" tag="input"/> |
|<$link to="$:/DefaultTiddlers"><<lingo DefaultTiddlers/Prompt>></$link> |<<lingo DefaultTiddlers/TopHint>><br> <$edit-text tag="textarea" tiddler="$:/DefaultTiddlers"/><br>//<<lingo DefaultTiddlers/BottomHint>>// |
</div>
See the [[control panel|$:/ControlPanel]] for more options.
<$importvariables filter="[[$:/core/ui/PageMacros]] [all[shadows+tiddlers]tag[$:/tags/Macro]!has[draft.of]]">
<<make_python pythontest>>
</$importvariables>
{
"1": [
[
"project pythontest",
""
]
],
"2": [
[
"pythontest code",
"",
""
]
]
}
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
var code = document.getElementById("pythoncode").textContent;
Sk.configure({output:outf});
Sk.importMainWithBody("<stdin>",false,code);
input = 1739
brk = "f"
print "is ", input, " prime"
for n in range(2, input):
if input%n == 0:
print "no, try ", n
brk = "t"
break
if (brk =="f"): print "yes"
<<jtinker pythonnjson pythontest>>
<script>
(function(){var COMPILED=!0,goog=goog||{};goog.global=this;goog.exportPath_=function(a,b,c){a=a.split(".");c=c||goog.global;a[0]in c||!c.execScript||c.execScript("var "+a[0]);for(var d;a.length&&(d=a.shift());)a.length||void 0===b?c=c[d]?c[d]:c[d]={}:c[d]=b};goog.define=function(a,b){var c=b;COMPILED||goog.global.CLOSURE_DEFINES&&Object.prototype.hasOwnProperty.call(goog.global.CLOSURE_DEFINES,a)&&(c=goog.global.CLOSURE_DEFINES[a]);goog.exportPath_(a,c)};goog.DEBUG=!1;goog.LOCALE="en";goog.TRUSTED_SITE=!0;
goog.provide=function(a){if(!COMPILED){if(goog.isProvided_(a))throw Error('Namespace "'+a+'" already declared.');delete goog.implicitNamespaces_[a];for(var b=a;(b=b.substring(0,b.lastIndexOf(".")))&&!goog.getObjectByName(b);)goog.implicitNamespaces_[b]=!0}goog.exportPath_(a)};goog.setTestOnly=function(a){if(COMPILED&&!goog.DEBUG)throw a=a||"",Error("Importing test-only code into non-debug environment"+a?": "+a:".");};
COMPILED||(goog.isProvided_=function(a){return!goog.implicitNamespaces_[a]&&!!goog.getObjectByName(a)},goog.implicitNamespaces_={});goog.getObjectByName=function(a,b){for(var c=a.split("."),d=b||goog.global,e;e=c.shift();)if(goog.isDefAndNotNull(d[e]))d=d[e];else return null;return d};goog.globalize=function(a,b){var c=b||goog.global,d;for(d in a)c[d]=a[d]};
goog.addDependency=function(a,b,c){if(goog.DEPENDENCIES_ENABLED){var d;a=a.replace(/\\/g,"/");for(var e=goog.dependencies_,f=0;d=b[f];f++)e.nameToPath[d]=a,a in e.pathToNames||(e.pathToNames[a]={}),e.pathToNames[a][d]=!0;for(d=0;b=c[d];d++)a in e.requires||(e.requires[a]={}),e.requires[a][b]=!0}};goog.ENABLE_DEBUG_LOADER=!0;
goog.require=function(a){if(!COMPILED&&!goog.isProvided_(a)){if(goog.ENABLE_DEBUG_LOADER){var b=goog.getPathFromDeps_(a);if(b){goog.included_[b]=!0;goog.writeScripts_();return}}a="goog.require could not find: "+a;goog.global.console&&goog.global.console.error(a);throw Error(a);}};goog.basePath="";goog.nullFunction=function(){};goog.identityFunction=function(a,b){return a};goog.abstractMethod=function(){throw Error("unimplemented abstract method");};
goog.addSingletonGetter=function(a){a.getInstance=function(){if(a.instance_)return a.instance_;goog.DEBUG&&(goog.instantiatedSingletons_[goog.instantiatedSingletons_.length]=a);return a.instance_=new a}};goog.instantiatedSingletons_=[];goog.DEPENDENCIES_ENABLED=!COMPILED&&goog.ENABLE_DEBUG_LOADER;
goog.DEPENDENCIES_ENABLED&&(goog.included_={},goog.dependencies_={pathToNames:{},nameToPath:{},requires:{},visited:{},written:{}},goog.inHtmlDocument_=function(){var a=goog.global.document;return"undefined"!=typeof a&&"write"in a},goog.findBasePath_=function(){if(goog.global.CLOSURE_BASE_PATH)goog.basePath=goog.global.CLOSURE_BASE_PATH;else if(goog.inHtmlDocument_())for(var a=goog.global.document.getElementsByTagName("script"),b=a.length-1;0<=b;--b){var c=a[b].src,d=c.lastIndexOf("?"),d=-1==d?c.length:
d;if("base.js"==c.substr(d-7,7)){goog.basePath=c.substr(0,d-7);break}}},goog.importScript_=function(a){var b=goog.global.CLOSURE_IMPORT_SCRIPT||goog.writeScriptTag_;!goog.dependencies_.written[a]&&b(a)&&(goog.dependencies_.written[a]=!0)},goog.writeScriptTag_=function(a){if(goog.inHtmlDocument_()){var b=goog.global.document;if("complete"==b.readyState){if(/\bdeps.js$/.test(a))return!1;throw Error('Cannot write "'+a+'" after document load');}b.write('<script type="text/javascript" src="'+a+'">\x3c/script>');
return!0}return!1},goog.writeScripts_=function(){function a(e){if(!(e in d.written)){if(!(e in d.visited)&&(d.visited[e]=!0,e in d.requires))for(var g in d.requires[e])if(!goog.isProvided_(g))if(g in d.nameToPath)a(d.nameToPath[g]);else throw Error("Undefined nameToPath for "+g);e in c||(c[e]=!0,b.push(e))}}var b=[],c={},d=goog.dependencies_,e;for(e in goog.included_)d.written[e]||a(e);for(e=0;e<b.length;e++)if(b[e])goog.importScript_(goog.basePath+b[e]);else throw Error("Undefined script input");
},goog.getPathFromDeps_=function(a){return a in goog.dependencies_.nameToPath?goog.dependencies_.nameToPath[a]:null},goog.findBasePath_(),goog.global.CLOSURE_NO_DEPS||goog.importScript_(goog.basePath+"deps.js"));
goog.typeOf=function(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null";
else if("function"==b&&"undefined"==typeof a.call)return"object";return b};goog.isDef=function(a){return void 0!==a};goog.isNull=function(a){return null===a};goog.isDefAndNotNull=function(a){return null!=a};goog.isArray=function(a){return"array"==goog.typeOf(a)};goog.isArrayLike=function(a){var b=goog.typeOf(a);return"array"==b||"object"==b&&"number"==typeof a.length};goog.isDateLike=function(a){return goog.isObject(a)&&"function"==typeof a.getFullYear};goog.isString=function(a){return"string"==typeof a};
goog.isBoolean=function(a){return"boolean"==typeof a};goog.isNumber=function(a){return"number"==typeof a};goog.isFunction=function(a){return"function"==goog.typeOf(a)};goog.isObject=function(a){var b=typeof a;return"object"==b&&null!=a||"function"==b};goog.getUid=function(a){return a[goog.UID_PROPERTY_]||(a[goog.UID_PROPERTY_]=++goog.uidCounter_)};goog.removeUid=function(a){"removeAttribute"in a&&a.removeAttribute(goog.UID_PROPERTY_);try{delete a[goog.UID_PROPERTY_]}catch(b){}};
goog.UID_PROPERTY_="closure_uid_"+(1E9*Math.random()>>>0);goog.uidCounter_=0;goog.getHashCode=goog.getUid;goog.removeHashCode=goog.removeUid;goog.cloneObject=function(a){var b=goog.typeOf(a);if("object"==b||"array"==b){if(a.clone)return a.clone();var b="array"==b?[]:{},c;for(c in a)b[c]=goog.cloneObject(a[c]);return b}return a};goog.bindNative_=function(a,b,c){return a.call.apply(a.bind,arguments)};
goog.bindJs_=function(a,b,c){if(!a)throw Error();if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var c=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(c,d);return a.apply(b,c)}}return function(){return a.apply(b,arguments)}};goog.bind=function(a,b,c){Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?goog.bind=goog.bindNative_:goog.bind=goog.bindJs_;return goog.bind.apply(null,arguments)};
goog.partial=function(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var b=Array.prototype.slice.call(arguments);b.unshift.apply(b,c);return a.apply(this,b)}};goog.mixin=function(a,b){for(var c in b)a[c]=b[c]};goog.now=goog.TRUSTED_SITE&&Date.now||function(){return+new Date};
goog.globalEval=function(a){if(goog.global.execScript)goog.global.execScript(a,"JavaScript");else if(goog.global.eval)if(null==goog.evalWorksForGlobals_&&(goog.global.eval("var _et_ = 1;"),"undefined"!=typeof goog.global._et_?(delete goog.global._et_,goog.evalWorksForGlobals_=!0):goog.evalWorksForGlobals_=!1),goog.evalWorksForGlobals_)goog.global.eval(a);else{var b=goog.global.document,c=b.createElement("script");c.type="text/javascript";c.defer=!1;c.appendChild(b.createTextNode(a));b.body.appendChild(c);
b.body.removeChild(c)}else throw Error("goog.globalEval not available");};goog.evalWorksForGlobals_=null;goog.getCssName=function(a,b){var c=function(a){return goog.cssNameMapping_[a]||a},d=function(a){a=a.split("-");for(var b=[],d=0;d<a.length;d++)b.push(c(a[d]));return b.join("-")},d=goog.cssNameMapping_?"BY_WHOLE"==goog.cssNameMappingStyle_?c:d:function(a){return a};return b?a+"-"+d(b):d(a)};goog.setCssNameMapping=function(a,b){goog.cssNameMapping_=a;goog.cssNameMappingStyle_=b};
!COMPILED&&goog.global.CLOSURE_CSS_NAME_MAPPING&&(goog.cssNameMapping_=goog.global.CLOSURE_CSS_NAME_MAPPING);goog.getMsg=function(a,b){var c=b||{},d;for(d in c){var e=(""+c[d]).replace(/\$/g,"$$$$");a=a.replace(RegExp("\\{\\$"+d+"\\}","gi"),e)}return a};goog.getMsgWithFallback=function(a,b){return a};goog.exportSymbol=function(a,b,c){goog.exportPath_(a,b,c)};goog.exportProperty=function(a,b,c){a[b]=c};
goog.inherits=function(a,b){function c(){}c.prototype=b.prototype;a.superClass_=b.prototype;a.prototype=new c;a.prototype.constructor=a};
goog.base=function(a,b,c){var d=arguments.callee.caller;if(goog.DEBUG&&!d)throw Error("arguments.caller not defined. goog.base() expects not to be running in strict mode. See http://www.ecma-international.org/ecma-262/5.1/#sec-C");if(d.superClass_)return d.superClass_.constructor.apply(a,Array.prototype.slice.call(arguments,1));for(var e=Array.prototype.slice.call(arguments,2),f=!1,g=a.constructor;g;g=g.superClass_&&g.superClass_.constructor)if(g.prototype[b]===d)f=!0;else if(f)return g.prototype[b].apply(a,
e);if(a[b]===d)return a.constructor.prototype[b].apply(a,e);throw Error("goog.base called from a method of one name to a method of a different name");};goog.scope=function(a){a.call(goog.global)};goog.string={};goog.string.Unicode={NBSP:"\u00a0"};goog.string.startsWith=function(a,b){return 0==a.lastIndexOf(b,0)};goog.string.endsWith=function(a,b){var c=a.length-b.length;return 0<=c&&a.indexOf(b,c)==c};goog.string.caseInsensitiveStartsWith=function(a,b){return 0==goog.string.caseInsensitiveCompare(b,a.substr(0,b.length))};goog.string.caseInsensitiveEndsWith=function(a,b){return 0==goog.string.caseInsensitiveCompare(b,a.substr(a.length-b.length,b.length))};
goog.string.caseInsensitiveEquals=function(a,b){return a.toLowerCase()==b.toLowerCase()};goog.string.subs=function(a,b){for(var c=a.split("%s"),d="",e=Array.prototype.slice.call(arguments,1);e.length&&1<c.length;)d+=c.shift()+e.shift();return d+c.join("%s")};goog.string.collapseWhitespace=function(a){return a.replace(/[\s\xa0]+/g," ").replace(/^\s+|\s+$/g,"")};goog.string.isEmpty=function(a){return/^[\s\xa0]*$/.test(a)};goog.string.isEmptySafe=function(a){return goog.string.isEmpty(goog.string.makeSafe(a))};
goog.string.isBreakingWhitespace=function(a){return!/[^\t\n\r ]/.test(a)};goog.string.isAlpha=function(a){return!/[^a-zA-Z]/.test(a)};goog.string.isNumeric=function(a){return!/[^0-9]/.test(a)};goog.string.isAlphaNumeric=function(a){return!/[^a-zA-Z0-9]/.test(a)};goog.string.isSpace=function(a){return" "==a};goog.string.isUnicodeChar=function(a){return 1==a.length&&" "<=a&&"~">=a||"\u0080"<=a&&"\ufffd">=a};goog.string.stripNewlines=function(a){return a.replace(/(\r\n|\r|\n)+/g," ")};
goog.string.canonicalizeNewlines=function(a){return a.replace(/(\r\n|\r|\n)/g,"\n")};goog.string.normalizeWhitespace=function(a){return a.replace(/\xa0|\s/g," ")};goog.string.normalizeSpaces=function(a){return a.replace(/\xa0|[ \t]+/g," ")};goog.string.collapseBreakingSpaces=function(a){return a.replace(/[\t\r\n ]+/g," ").replace(/^[\t\r\n ]+|[\t\r\n ]+$/g,"")};goog.string.trim=function(a){return a.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")};
goog.string.trimLeft=function(a){return a.replace(/^[\s\xa0]+/,"")};goog.string.trimRight=function(a){return a.replace(/[\s\xa0]+$/,"")};goog.string.caseInsensitiveCompare=function(a,b){var c=String(a).toLowerCase(),d=String(b).toLowerCase();return c<d?-1:c==d?0:1};goog.string.numerateCompareRegExp_=/(\.\d+)|(\d+)|(\D+)/g;
goog.string.numerateCompare=function(a,b){if(a==b)return 0;if(!a)return-1;if(!b)return 1;for(var c=a.toLowerCase().match(goog.string.numerateCompareRegExp_),d=b.toLowerCase().match(goog.string.numerateCompareRegExp_),e=Math.min(c.length,d.length),f=0;f<e;f++){var g=c[f],h=d[f];if(g!=h)return c=parseInt(g,10),!isNaN(c)&&(d=parseInt(h,10),!isNaN(d)&&c-d)?c-d:g<h?-1:1}return c.length!=d.length?c.length-d.length:a<b?-1:1};goog.string.urlEncode=function(a){return encodeURIComponent(String(a))};
goog.string.urlDecode=function(a){return decodeURIComponent(a.replace(/\+/g," "))};goog.string.newLineToBr=function(a,b){return a.replace(/(\r\n|\r|\n)/g,b?"<br />":"<br>")};
goog.string.htmlEscape=function(a,b){if(b)return a.replace(goog.string.amperRe_,"&").replace(goog.string.ltRe_,"<").replace(goog.string.gtRe_,">").replace(goog.string.quotRe_,""");if(!goog.string.allRe_.test(a))return a;-1!=a.indexOf("&")&&(a=a.replace(goog.string.amperRe_,"&"));-1!=a.indexOf("<")&&(a=a.replace(goog.string.ltRe_,"<"));-1!=a.indexOf(">")&&(a=a.replace(goog.string.gtRe_,">"));-1!=a.indexOf('"')&&(a=a.replace(goog.string.quotRe_,"""));return a};
goog.string.amperRe_=/&/g;goog.string.ltRe_=/</g;goog.string.gtRe_=/>/g;goog.string.quotRe_=/\"/g;goog.string.allRe_=/[&<>\"]/;goog.string.unescapeEntities=function(a){return goog.string.contains(a,"&")?"document"in goog.global?goog.string.unescapeEntitiesUsingDom_(a):goog.string.unescapePureXmlEntities_(a):a};
goog.string.unescapeEntitiesUsingDom_=function(a){var b={"&":"&","<":"<",">":">",""":'"'},c=document.createElement("div");return a.replace(goog.string.HTML_ENTITY_PATTERN_,function(a,e){var f=b[a];if(f)return f;if("#"==e.charAt(0)){var g=Number("0"+e.substr(1));isNaN(g)||(f=String.fromCharCode(g))}f||(c.innerHTML=a+" ",f=c.firstChild.nodeValue.slice(0,-1));return b[a]=f})};
goog.string.unescapePureXmlEntities_=function(a){return a.replace(/&([^;]+);/g,function(a,c){switch(c){case "amp":return"&";case "lt":return"<";case "gt":return">";case "quot":return'"';default:if("#"==c.charAt(0)){var d=Number("0"+c.substr(1));if(!isNaN(d))return String.fromCharCode(d)}return a}})};goog.string.HTML_ENTITY_PATTERN_=/&([^;\s<&]+);?/g;goog.string.whitespaceEscape=function(a,b){return goog.string.newLineToBr(a.replace(/ /g,"  "),b)};
goog.string.stripQuotes=function(a,b){for(var c=b.length,d=0;d<c;d++){var e=1==c?b:b.charAt(d);if(a.charAt(0)==e&&a.charAt(a.length-1)==e)return a.substring(1,a.length-1)}return a};goog.string.truncate=function(a,b,c){c&&(a=goog.string.unescapeEntities(a));a.length>b&&(a=a.substring(0,b-3)+"...");c&&(a=goog.string.htmlEscape(a));return a};
goog.string.truncateMiddle=function(a,b,c,d){c&&(a=goog.string.unescapeEntities(a));if(d&&a.length>b){d>b&&(d=b);var e=a.length-d;a=a.substring(0,b-d)+"..."+a.substring(e)}else a.length>b&&(d=Math.floor(b/2),e=a.length-d,a=a.substring(0,d+b%2)+"..."+a.substring(e));c&&(a=goog.string.htmlEscape(a));return a};goog.string.specialEscapeChars_={"\x00":"\\0","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\x0B",'"':'\\"',"\\":"\\\\"};goog.string.jsEscapeCache_={"'":"\\'"};
goog.string.quote=function(a){a=String(a);if(a.quote)return a.quote();for(var b=['"'],c=0;c<a.length;c++){var d=a.charAt(c),e=d.charCodeAt(0);b[c+1]=goog.string.specialEscapeChars_[d]||(31<e&&127>e?d:goog.string.escapeChar(d))}b.push('"');return b.join("")};goog.string.escapeString=function(a){for(var b=[],c=0;c<a.length;c++)b[c]=goog.string.escapeChar(a.charAt(c));return b.join("")};
goog.string.escapeChar=function(a){if(a in goog.string.jsEscapeCache_)return goog.string.jsEscapeCache_[a];if(a in goog.string.specialEscapeChars_)return goog.string.jsEscapeCache_[a]=goog.string.specialEscapeChars_[a];var b=a,c=a.charCodeAt(0);if(31<c&&127>c)b=a;else{if(256>c){if(b="\\x",16>c||256<c)b+="0"}else b="\\u",4096>c&&(b+="0");b+=c.toString(16).toUpperCase()}return goog.string.jsEscapeCache_[a]=b};goog.string.toMap=function(a){for(var b={},c=0;c<a.length;c++)b[a.charAt(c)]=!0;return b};
goog.string.contains=function(a,b){return-1!=a.indexOf(b)};goog.string.countOf=function(a,b){return a&&b?a.split(b).length-1:0};goog.string.removeAt=function(a,b,c){var d=a;0<=b&&(b<a.length&&0<c)&&(d=a.substr(0,b)+a.substr(b+c,a.length-b-c));return d};goog.string.remove=function(a,b){var c=RegExp(goog.string.regExpEscape(b),"");return a.replace(c,"")};goog.string.removeAll=function(a,b){var c=RegExp(goog.string.regExpEscape(b),"g");return a.replace(c,"")};
goog.string.regExpEscape=function(a){return String(a).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08")};goog.string.repeat=function(a,b){return Array(b+1).join(a)};goog.string.padNumber=function(a,b,c){a=goog.isDef(c)?a.toFixed(c):String(a);c=a.indexOf(".");-1==c&&(c=a.length);return goog.string.repeat("0",Math.max(0,b-c))+a};goog.string.makeSafe=function(a){return null==a?"":String(a)};goog.string.buildString=function(a){return Array.prototype.join.call(arguments,"")};
goog.string.getRandomString=function(){return Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^goog.now()).toString(36)};
goog.string.compareVersions=function(a,b){for(var c=0,d=goog.string.trim(String(a)).split("."),e=goog.string.trim(String(b)).split("."),f=Math.max(d.length,e.length),g=0;0==c&&g<f;g++){var h=d[g]||"",k=e[g]||"",l=RegExp("(\\d*)(\\D*)","g"),m=RegExp("(\\d*)(\\D*)","g");do{var q=l.exec(h)||["","",""],n=m.exec(k)||["","",""];if(0==q[0].length&&0==n[0].length)break;var c=0==q[1].length?0:parseInt(q[1],10),r=0==n[1].length?0:parseInt(n[1],10),c=goog.string.compareElements_(c,r)||goog.string.compareElements_(0==
q[2].length,0==n[2].length)||goog.string.compareElements_(q[2],n[2])}while(0==c)}return c};goog.string.compareElements_=function(a,b){return a<b?-1:a>b?1:0};goog.string.HASHCODE_MAX_=4294967296;goog.string.hashCode=function(a){for(var b=0,c=0;c<a.length;++c)b=31*b+a.charCodeAt(c),b%=goog.string.HASHCODE_MAX_;return b};goog.string.uniqueStringCounter_=2147483648*Math.random()|0;goog.string.createUniqueString=function(){return"goog_"+goog.string.uniqueStringCounter_++};
goog.string.toNumber=function(a){var b=Number(a);return 0==b&&goog.string.isEmpty(a)?NaN:b};goog.string.isLowerCamelCase=function(a){return/^[a-z]+([A-Z][a-z]*)*$/.test(a)};goog.string.isUpperCamelCase=function(a){return/^([A-Z][a-z]*)+$/.test(a)};goog.string.toCamelCase=function(a){return String(a).replace(/\-([a-z])/g,function(a,c){return c.toUpperCase()})};goog.string.toSelectorCase=function(a){return String(a).replace(/([A-Z])/g,"-$1").toLowerCase()};
goog.string.toTitleCase=function(a,b){var c=goog.isString(b)?goog.string.regExpEscape(b):"\\s";return a.replace(RegExp("(^"+(c?"|["+c+"]+":"")+")([a-z])","g"),function(a,b,c){return b+c.toUpperCase()})};goog.string.parseInt=function(a){isFinite(a)&&(a=String(a));return goog.isString(a)?/^\s*-?0x/i.test(a)?parseInt(a,16):parseInt(a,10):NaN};goog.string.splitLimit=function(a,b,c){a=a.split(b);for(var d=[];0<c&&a.length;)d.push(a.shift()),c--;a.length&&d.push(a.join(b));return d};goog.debug={};goog.debug.Error=function(a){Error.captureStackTrace?Error.captureStackTrace(this,goog.debug.Error):this.stack=Error().stack||"";a&&(this.message=String(a))};goog.inherits(goog.debug.Error,Error);goog.debug.Error.prototype.name="CustomError";goog.asserts={};goog.asserts.ENABLE_ASSERTS=goog.DEBUG;goog.asserts.AssertionError=function(a,b){b.unshift(a);goog.debug.Error.call(this,goog.string.subs.apply(null,b));b.shift();this.messagePattern=a};goog.inherits(goog.asserts.AssertionError,goog.debug.Error);goog.asserts.AssertionError.prototype.name="AssertionError";goog.asserts.doAssertFailure_=function(a,b,c,d){var e="Assertion failed";if(c)var e=e+(": "+c),f=d;else a&&(e+=": "+a,f=b);throw new goog.asserts.AssertionError(""+e,f||[]);};
goog.asserts.assert=function(a,b,c){goog.asserts.ENABLE_ASSERTS&&!a&&goog.asserts.doAssertFailure_("",null,b,Array.prototype.slice.call(arguments,2));return a};goog.asserts.fail=function(a,b){if(goog.asserts.ENABLE_ASSERTS)throw new goog.asserts.AssertionError("Failure"+(a?": "+a:""),Array.prototype.slice.call(arguments,1));};
goog.asserts.assertNumber=function(a,b,c){goog.asserts.ENABLE_ASSERTS&&!goog.isNumber(a)&&goog.asserts.doAssertFailure_("Expected number but got %s: %s.",[goog.typeOf(a),a],b,Array.prototype.slice.call(arguments,2));return a};goog.asserts.assertString=function(a,b,c){goog.asserts.ENABLE_ASSERTS&&!goog.isString(a)&&goog.asserts.doAssertFailure_("Expected string but got %s: %s.",[goog.typeOf(a),a],b,Array.prototype.slice.call(arguments,2));return a};
goog.asserts.assertFunction=function(a,b,c){goog.asserts.ENABLE_ASSERTS&&!goog.isFunction(a)&&goog.asserts.doAssertFailure_("Expected function but got %s: %s.",[goog.typeOf(a),a],b,Array.prototype.slice.call(arguments,2));return a};goog.asserts.assertObject=function(a,b,c){goog.asserts.ENABLE_ASSERTS&&!goog.isObject(a)&&goog.asserts.doAssertFailure_("Expected object but got %s: %s.",[goog.typeOf(a),a],b,Array.prototype.slice.call(arguments,2));return a};
goog.asserts.assertArray=function(a,b,c){goog.asserts.ENABLE_ASSERTS&&!goog.isArray(a)&&goog.asserts.doAssertFailure_("Expected array but got %s: %s.",[goog.typeOf(a),a],b,Array.prototype.slice.call(arguments,2));return a};goog.asserts.assertBoolean=function(a,b,c){goog.asserts.ENABLE_ASSERTS&&!goog.isBoolean(a)&&goog.asserts.doAssertFailure_("Expected boolean but got %s: %s.",[goog.typeOf(a),a],b,Array.prototype.slice.call(arguments,2));return a};
goog.asserts.assertInstanceof=function(a,b,c,d){!goog.asserts.ENABLE_ASSERTS||a instanceof b||goog.asserts.doAssertFailure_("instanceof check failed.",null,c,Array.prototype.slice.call(arguments,3));return a};goog.asserts.assertObjectPrototypeIsIntact=function(){for(var a in Object.prototype)goog.asserts.fail(a+" should not be enumerable in Object.prototype.")};(function(a){var b,c,d;(function(){var a={},f={};b=function(b,c,d){a[b]={deps:c,callback:d}};d=c=function(b){function h(a){if("."!==a.charAt(0))return a;a=a.split("/");for(var c=b.split("/").slice(0,-1),d=0,e=a.length;d<e;d++){var f=a[d];".."===f?c.pop():"."!==f&&c.push(f)}return c.join("/")}d._eak_seen=a;if(f[b])return f[b];f[b]={};if(!a[b])throw Error("Could not find module "+b);for(var k=a[b],l=k.deps,k=k.callback,m=[],q,n=0,r=l.length;n<r;n++)"exports"===l[n]?m.push(q={}):m.push(c(h(l[n])));l=
k.apply(this,m);return f[b]=q||l}})();b("promise/all",["./utils","exports"],function(a,b){var c=a.isArray,d=a.isFunction;b.all=function(a){if(!c(a))throw new TypeError("You must pass an array to all.");return new this(function(b,c){function e(a){return function(c){f[a]=c;0===--g&&b(f)}}var f=[],g=a.length,p;0===g&&b([]);for(var s=0;s<a.length;s++)(p=a[s])&&d(p.then)?p.then(e(s),c):(f[s]=p,0===--g&&b(f))})}});b("promise/asap",["exports"],function(a){function b(){return function(){process.nextTick(d)}}
function c(){return function(){k.setTimeout(d,1)}}function d(){for(var a=0;a<l.length;a++){var b=l[a];(0,b[0])(b[1])}l=[]}var k="undefined"!==typeof global?global:void 0===this?window:this,l=[],m;m="undefined"!==typeof process&&"[object process]"==={}.toString.call(process)?b():c();a.asap=function(a,b){1===l.push([a,b])&&m()}});b("promise/config",["exports"],function(a){var b={instrument:!1};a.config=b;a.configure=function(a,c){if(2===arguments.length)b[a]=c;else return b[a]}});b("promise/polyfill",
["./promise","./utils","exports"],function(b,c,d){var h=b.Promise,k=c.isFunction;d.polyfill=function(){var b;b="undefined"!==typeof global?global:"undefined"!==typeof window&&window.document?window:a;"Promise"in b&&"resolve"in b.Promise&&"reject"in b.Promise&&"all"in b.Promise&&"race"in b.Promise&&function(){var a;new b.Promise(function(b){a=b});return k(a)}()||(b.Promise=h)}});b("promise/promise","./config ./utils ./all ./race ./resolve ./reject ./asap exports".split(" "),function(a,b,c,d,k,l,m,
q){function n(a){if(!E(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof n))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[];r(a,this)}function r(a,b){function c(a){y(b,a)}function d(a){v(b,a)}try{a(c,d)}catch(e){d(e)}}function p(a,b,c,d){var e=E(c),f,g,h,k;if(e)try{f=c(d),h=!0}catch(l){k=!0,g=l}else f=d,h=
!0;x(b,f)||(e&&h?y(b,f):k?v(b,g):a===z?y(b,f):a===A&&v(b,f))}function s(a,b,c,d){a=a._subscribers;var e=a.length;a[e]=b;a[e+z]=c;a[e+A]=d}function B(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],p(b,c,d,f);a._subscribers=null}function x(a,b){var c=null,d;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(K(b)&&(c=b.then,E(c)))return c.call(b,function(c){if(d)return!0;d=!0;b!==c?y(a,c):C(a,c)},function(b){if(d)return!0;d=
!0;v(a,b)}),!0}catch(e){if(d)return!0;v(a,e);return!0}return!1}function y(a,b){a===b?C(a,b):x(a,b)||C(a,b)}function C(a,b){a._state===D&&(a._state=u,a._detail=b,t.async(J,a))}function v(a,b){a._state===D&&(a._state=u,a._detail=b,t.async(w,a))}function J(a){B(a,a._state=z)}function w(a){B(a,a._state=A)}var t=a.config,K=b.objectOrFunction,E=b.isFunction;a=c.all;d=d.race;k=k.resolve;l=l.reject;t.async=m.asap;var D=void 0,u=0,z=1,A=2;n.prototype={constructor:n,_state:void 0,_detail:void 0,_subscribers:void 0,
then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){p(c._state,d,e[c._state-1],c._detail)})}else s(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}};n.all=a;n.race=d;n.resolve=k;n.reject=l;q.Promise=n});b("promise/race",["./utils","exports"],function(a,b){var c=a.isArray;b.race=function(a){if(!c(a))throw new TypeError("You must pass an array to race.");return new this(function(b,c){for(var d,e=0;e<a.length;e++)(d=
a[e])&&"function"===typeof d.then?d.then(b,c):b(d)})}});b("promise/reject",["exports"],function(a){a.reject=function(a){return new this(function(b,c){c(a)})}});b("promise/resolve",["exports"],function(a){a.resolve=function(a){return a&&"object"===typeof a&&a.constructor===this?a:new this(function(b){b(a)})}});b("promise/utils",["exports"],function(a){function b(a){return"function"===typeof a}var c=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=function(a){return b(a)||"object"===
typeof a&&null!==a};a.isFunction=b;a.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)};a.now=c});c("promise/polyfill").polyfill()})(this);var Sk=Sk||{};
Sk.configure=function(a){Sk.output=a.output||Sk.output;goog.asserts.assert("function"===typeof Sk.output);Sk.debugout=a.debugout||Sk.debugout;goog.asserts.assert("function"===typeof Sk.debugout);Sk.uncaughtException=a.uncaughtException||Sk.uncaughtException;goog.asserts.assert("function"===typeof Sk.uncaughtException);Sk.read=a.read||Sk.read;goog.asserts.assert("function"===typeof Sk.read);Sk.timeoutMsg=a.timeoutMsg||Sk.timeoutMsg;goog.asserts.assert("function"===typeof Sk.timeoutMsg);goog.exportSymbol("Sk.timeoutMsg",
Sk.timeoutMsg);Sk.sysargv=a.sysargv||Sk.sysargv;goog.asserts.assert(goog.isArrayLike(Sk.sysargv));Sk.python3=a.python3||Sk.python3;goog.asserts.assert("boolean"===typeof Sk.python3);Sk.imageProxy=a.imageProxy||"http://localhost:8080/320x";goog.asserts.assert("string"===typeof Sk.imageProxy);Sk.inputfun=a.inputfun||Sk.inputfun;goog.asserts.assert("function"===typeof Sk.inputfun);Sk.retainGlobals=a.retainglobals||!1;goog.asserts.assert("boolean"===typeof Sk.retainGlobals);Sk.debugging=a.debugging||
!1;goog.asserts.assert("boolean"===typeof Sk.debugging);Sk.breakpoints=a.breakpoints||function(){return!0};goog.asserts.assert("function"===typeof Sk.breakpoints);"execLimit"in a&&(Sk.execLimit=a.execLimit);"yieldLimit"in a&&(Sk.yieldLimit=a.yieldLimit);a.syspath&&(Sk.syspath=a.syspath,goog.asserts.assert(goog.isArrayLike(Sk.syspath)),Sk.realsyspath=void 0,Sk.sysmodules=new Sk.builtin.dict([]));Sk.misceval.softspace_=!1};goog.exportSymbol("Sk.configure",Sk.configure);
Sk.uncaughtException=function(a){throw a;};goog.exportSymbol("Sk.uncaughtException",Sk.uncaughtException);Sk.timeoutMsg=function(){return"Program exceeded run time limit."};goog.exportSymbol("Sk.timeoutMsg",Sk.timeoutMsg);Sk.execLimit=Number.POSITIVE_INFINITY;Sk.yieldLimit=Number.POSITIVE_INFINITY;Sk.output=function(a){};Sk.read=function(a){throw"Sk.read has not been implemented";};Sk.sysargv=[];Sk.getSysArgv=function(){return Sk.sysargv};goog.exportSymbol("Sk.getSysArgv",Sk.getSysArgv);
Sk.syspath=[];Sk.inBrowser=void 0!==goog.global.document;Sk.debugout=function(a){};(function(){void 0!==goog.global.write?Sk.output=goog.global.write:void 0!==goog.global.console&&void 0!==goog.global.console.log?Sk.output=function(a){goog.global.console.log(a)}:void 0!==goog.global.print&&(Sk.output=goog.global.print);void 0!==goog.global.print&&(Sk.debugout=goog.global.print)})();
Sk.inBrowser||(goog.global.CLOSURE_IMPORT_SCRIPT=function(a){goog.global.eval(goog.global.read("support/closure-library/closure/goog/"+a));return!0});Sk.python3=!1;Sk.inputfun=function(a){return window.prompt(a)};goog.exportSymbol("Sk.python3",Sk.python3);goog.exportSymbol("Sk.inputfun",Sk.inputfun);void 0===Sk.builtin&&(Sk.builtin={});
Sk.dunderToSkulpt={__eq__:"ob$eq",__ne__:"ob$ne",__lt__:"ob$lt",__le__:"ob$le",__gt__:"ob$gt",__ge__:"ob$ge",__hash__:"tp$hash",__abs__:"nb$abs",__neg__:"nb$negative",__pos__:"nb$positive",__int__:"nb$int_",__long__:"nb$lng",__float__:"nb$float_",__add__:"nb$add",__radd__:"nb$reflected_add",__sub__:"nb$subtract",__rsub__:"nb$reflected_subtract",__mul__:"nb$multiply",__rmul__:"nb$reflected_multiply",__div__:"nb$divide",__rdiv__:"nb$reflected_divide",__floordiv__:"nb$floor_divide",__rfloordiv__:"nb$reflected_floor_divide",
__mod__:"nb$remainder",__rmod__:"nb$reflected_remainder",__divmod__:"nb$divmod",__rdivmod__:"nb$reflected_divmod",__pow__:"nb$power",__rpow__:"nb$reflected_power",__contains__:"sq$contains",__len__:"sq$length"};
Sk.builtin.type=function(a,b,c){var d,e;if(void 0===b&&void 0===c)return a.ob$type;if("dict"!==c.tp$name)throw new Sk.builtin.TypeError("type() argument 3 must be dict, not "+Sk.abstr.typeName(c));if(!Sk.builtin.checkString(a))throw new Sk.builtin.TypeError("type() argument 1 must be str, not "+Sk.abstr.typeName(a));if("tuple"!==b.tp$name)throw new Sk.builtin.TypeError("type() argument 2 must be tuple, not "+Sk.abstr.typeName(b));d=function(a,b,c,e,f){var g,h=this;if(!(this instanceof d))return new d(a,
b,c,e,f);e=e||[];h.$d=new Sk.builtin.dict([]);void 0!==d.prototype.tp$base&&(d.prototype.tp$base.sk$klass?d.prototype.tp$base.call(this,a,b,c,e.slice(),f):(g=e.slice(),g.unshift(d,this),Sk.abstr.superConstructor.apply(void 0,g)));g=Sk.builtin.type.typeLookup(h.ob$type,"__init__");return void 0!==g?(e.unshift(h),a=Sk.misceval.applyOrSuspend(g,a,b,c,e),function v(a){return a instanceof Sk.misceval.Suspension?f?new Sk.misceval.Suspension(v,a):Sk.misceval.retryOptionalSuspensionOrThrow(a):h}(a)):h};var f=
Sk.ffi.remapToJs(a);e=!1;0===b.v.length&&Sk.python3&&(e=!0,Sk.abstr.setUpInheritance(f,d,Sk.builtin.object));var g,h,k,l=[];h=b.tp$iter();for(g=h.tp$iternext();void 0!==g;g=h.tp$iternext())if(void 0===k&&(k=g),g.prototype instanceof Sk.builtin.object||g===Sk.builtin.object){for(;g.sk$klass&&g.prototype.tp$base;)g=g.prototype.tp$base;!g.sk$klass&&0>l.indexOf(g)&&l.push(g);e=!0}if(1<l.length)throw new Sk.builtin.TypeError("Multiple inheritance with more than one builtin type is unsupported");void 0!==
k&&(goog.inherits(d,k),k.prototype instanceof Sk.builtin.object||k===Sk.builtin.object)&&(d.prototype.tp$base=k);d.prototype.tp$name=f;d.prototype.ob$type=Sk.builtin.type.makeIntoTypeObj(f,d);e||(d.prototype.tp$getattr=Sk.builtin.object.prototype.GenericGetAttr,d.prototype.tp$setattr=Sk.builtin.object.prototype.GenericSetAttr);var m=new Sk.builtin.str("__module__");void 0===c.mp$lookup(m)&&c.mp$ass_subscript(m,Sk.globals.__name__);h=c.tp$iter();for(g=h.tp$iternext();void 0!==g;g=h.tp$iternext())e=
c.mp$subscript(g),void 0===e&&(e=null),d.prototype[g.v]=e,d[g.v]=e;d.__class__=d;d.__name__=a;d.sk$klass=!0;d.prototype.tp$descr_get=function(){goog.asserts.fail("in type tp$descr_get")};d.prototype.$r=function(){var a,b;a=this.tp$getattr("__repr__");if(void 0!==a&&a.im_func!==Sk.builtin.object.prototype.__repr__)return Sk.misceval.apply(a,void 0,void 0,void 0,[]);if(void 0!==d.prototype.tp$base&&d.prototype.tp$base!==Sk.builtin.object&&void 0!==d.prototype.tp$base.prototype.$r)return d.prototype.tp$base.prototype.$r.call(this);
b=c.mp$subscript(m);a="";b&&(a=b.v+".");return new Sk.builtin.str("<"+a+f+" object>")};d.prototype.tp$str=function(){var a=this.tp$getattr("__str__");return void 0!==a&&a.im_func!==Sk.builtin.object.prototype.__str__?Sk.misceval.apply(a,void 0,void 0,void 0,[]):void 0!==d.prototype.tp$base&&d.prototype.tp$base!==Sk.builtin.object&&void 0!==d.prototype.tp$base.prototype.tp$str?d.prototype.tp$base.prototype.tp$str.call(this):this.$r()};d.prototype.tp$length=function(){var a;a=this.tp$getattr("__len__");
if(void 0!==a)return Sk.misceval.apply(a,void 0,void 0,void 0,[]);a=Sk.abstr.typeName(this);throw new Sk.builtin.AttributeError(a+" instance has no attribute '__len__'");};d.prototype.tp$call=function(a,b){var c=this.tp$getattr("__call__");if(c)return Sk.misceval.apply(c,void 0,void 0,b,a);throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(this)+"' object is not callable");};d.prototype.tp$iter=function(){var a;a=this.tp$getattr("__iter__");var b=Sk.abstr.typeName(this);if(a)return a=Sk.misceval.callsim(a);
throw new Sk.builtin.TypeError("'"+b+"' object is not iterable");};d.prototype.tp$iternext=function(){var a=this.tp$getattr("next"),b;if(a){try{b=Sk.misceval.callsim(a)}catch(c){if(c instanceof Sk.builtin.StopIteration)b=void 0;else throw c;}return b}};d.prototype.tp$getitem=function(a,b){var c=this.tp$getattr("__getitem__");if(void 0!==c)return c=Sk.misceval.applyOrSuspend(c,void 0,void 0,void 0,[a]),b?c:Sk.misceval.retryOptionalSuspensionOrThrow(c);throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(this)+
"' object does not support indexing");};d.prototype.tp$setitem=function(a,b,c){var d=this.tp$getattr("__setitem__");if(void 0!==d)return a=Sk.misceval.applyOrSuspend(d,void 0,void 0,void 0,[a,b]),c?a:Sk.misceval.retryOptionalSuspensionOrThrow(a);throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(this)+"' object does not support item assignment");};b&&(d.$d=new Sk.builtin.dict([]),d.$d.mp$ass_subscript(Sk.builtin.type.basesStr_,b),a=Sk.builtin.type.buildMRO(d),d.$d.mp$ass_subscript(Sk.builtin.type.mroStr_,
a),d.tp$mro=a);d.tp$setattr=Sk.builtin.type.prototype.tp$setattr;a=function(a,b,c){d.prototype[a]=function(){var a=Array.prototype.slice.call(arguments);a.unshift(c,this);return Sk.misceval.callsim.apply(void 0,a)}};for(var q in Sk.dunderToSkulpt)b=Sk.dunderToSkulpt[q],d[q]&&a(b,q,d[q]);return d};Sk.builtin.type.makeTypeObj=function(a,b){Sk.builtin.type.makeIntoTypeObj(a,b);return b};
Sk.builtin.type.makeIntoTypeObj=function(a,b){goog.asserts.assert(void 0!==a);goog.asserts.assert(void 0!==b);b.ob$type=Sk.builtin.type;b.tp$name=a;b.$r=function(){var a,d=b.__module__,e="";d&&(e=d.v+".");a="class";d||(b.sk$klass||Sk.python3)||(a="type");return new Sk.builtin.str("<"+a+" '"+e+b.tp$name+"'>")};b.tp$str=void 0;b.tp$getattr=Sk.builtin.type.prototype.tp$getattr;b.tp$setattr=Sk.builtin.object.prototype.GenericSetAttr;b.tp$richcompare=Sk.builtin.type.prototype.tp$richcompare;b.sk$type=
!0;return b};Sk.builtin.type.ob$type=Sk.builtin.type;Sk.builtin.type.tp$name="type";Sk.builtin.type.$r=function(){return Sk.python3?new Sk.builtin.str("<class 'type'>"):new Sk.builtin.str("<type 'type'>")};Sk.builtin.type.prototype.tp$getattr=function(a){var b,c;if(this.$d&&(b=this.$d.mp$lookup(new Sk.builtin.str(a)),void 0!==b))return b;a=Sk.builtin.type.typeLookup(this,a);void 0!==a&&(null!==a&&void 0!==a.ob$type)&&(c=a.ob$type.tp$descr_get);if(c)return c.call(a,null,this);if(void 0!==a)return a};
Sk.builtin.type.prototype.tp$setattr=function(a,b){this[a]=b};Sk.builtin.type.typeLookup=function(a,b){var c=a.tp$mro,d=new Sk.builtin.str(b),e,f,g;if(c)for(g=0;g<c.v.length;++g){e=c.v[g];if(e.hasOwnProperty(b))return e[b];f=e.$d.mp$lookup(d);if(void 0!==f)return f;if(e.prototype&&void 0!==e.prototype[b])return e.prototype[b]}else if(a.prototype)return a.prototype[b]};
Sk.builtin.type.mroMerge_=function(a){for(var b,c,d,e,f,g,h=[];;){for(c=0;c<a.length&&(b=a[c],0===b.length);++c);if(c===a.length)return h;d=[];for(c=0;c<a.length;++c)if(b=a[c],0!==b.length){g=b[0];f=0;a:for(;f<a.length;++f)for(e=a[f],b=1;b<e.length;++b)if(e[b]===g)break a;f===a.length&&d.push(g)}if(0===d.length)throw new Sk.builtin.TypeError("Inconsistent precedences in type hierarchy");d=d[0];h.push(d);for(c=0;c<a.length;++c)b=a[c],0<b.length&&b[0]===d&&b.splice(0,1)}};
Sk.builtin.type.buildMRO_=function(a){var b,c=[[a]],d=a.$d.mp$subscript(Sk.builtin.type.basesStr_);for(a=0;a<d.v.length;++a)c.push(Sk.builtin.type.buildMRO_(d.v[a]));b=[];for(a=0;a<d.v.length;++a)b.push(d.v[a]);c.push(b);return Sk.builtin.type.mroMerge_(c)};Sk.builtin.type.buildMRO=function(a){return new Sk.builtin.tuple(Sk.builtin.type.buildMRO_(a))};
Sk.builtin.type.prototype.tp$richcompare=function(a,b){var c,d;if(a.ob$type==Sk.builtin.type&&this.$r&&a.$r)return d=this.$r(),c=a.$r(),d.tp$richcompare(c,b)};Sk.abstr={};Sk.abstr.typeName=function(a){return void 0!==a.tp$name?a.tp$name:"<invalid type>"};Sk.abstr.binop_type_error=function(a,b,c){a=Sk.abstr.typeName(a);b=Sk.abstr.typeName(b);throw new Sk.builtin.TypeError("unsupported operand type(s) for "+c+": '"+a+"' and '"+b+"'");};Sk.abstr.unop_type_error=function(a,b){var c=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("bad operand type for unary "+{UAdd:"+",USub:"-",Invert:"~"}[b]+": '"+c+"'");};
Sk.abstr.boNameToSlotFuncLhs_=function(a,b){if(null!==a)switch(b){case "Add":return a.nb$add?a.nb$add:a.__add__;case "Sub":return a.nb$subtract?a.nb$subtract:a.__sub__;case "Mult":return a.nb$multiply?a.nb$multiply:a.__mul__;case "Div":return a.nb$divide?a.nb$divide:a.__div__;case "FloorDiv":return a.nb$floor_divide?a.nb$floor_divide:a.__floordiv__;case "Mod":return a.nb$remainder?a.nb$remainder:a.__mod__;case "DivMod":return a.nb$divmod?a.nb$divmod:a.__divmod__;case "Pow":return a.nb$power?a.nb$power:
a.__pow__;case "LShift":return a.nb$lshift?a.nb$lshift:a.__lshift__;case "RShift":return a.nb$rshift?a.nb$rshift:a.__rshift__;case "BitAnd":return a.nb$and?a.nb$and:a.__and__;case "BitXor":return a.nb$xor?a.nb$xor:a.__xor__;case "BitOr":return a.nb$or?a.nb$or:a.__or__}};
Sk.abstr.boNameToSlotFuncRhs_=function(a,b){if(null!==a)switch(b){case "Add":return a.nb$reflected_add?a.nb$reflected_add:a.__radd__;case "Sub":return a.nb$reflected_subtract?a.nb$reflected_subtract:a.__rsub__;case "Mult":return a.nb$reflected_multiply?a.nb$reflected_multiply:a.__rmul__;case "Div":return a.nb$reflected_divide?a.nb$reflected_divide:a.__rdiv__;case "FloorDiv":return a.nb$reflected_floor_divide?a.nb$reflected_floor_divide:a.__rfloordiv__;case "Mod":return a.nb$reflected_remainder?a.nb$reflected_remainder:
a.__rmod__;case "DivMod":return a.nb$reflected_divmod?a.nb$reflected_divmod:a.__rdivmod__;case "Pow":return a.nb$reflected_power?a.nb$reflected_power:a.__rpow__;case "LShift":return a.nb$reflected_lshift?a.nb$reflected_lshift:a.__rlshift__;case "RShift":return a.nb$reflected_rshift?a.nb$reflected_rshift:a.__rrshift__;case "BitAnd":return a.nb$reflected_and?a.nb$reflected_and:a.__rand__;case "BitXor":return a.nb$reflected_xor?a.nb$reflected_xor:a.__rxor__;case "BitOr":return a.nb$reflected_or?a.nb$reflected_or:
a.__ror__}};
Sk.abstr.iboNameToSlotFunc_=function(a,b){switch(b){case "Add":return a.nb$inplace_add?a.nb$inplace_add:a.__iadd__;case "Sub":return a.nb$inplace_subtract?a.nb$inplace_subtract:a.__isub__;case "Mult":return a.nb$inplace_multiply?a.nb$inplace_multiply:a.__imul__;case "Div":return a.nb$inplace_divide?a.nb$inplace_divide:a.__idiv__;case "FloorDiv":return a.nb$inplace_floor_divide?a.nb$inplace_floor_divide:a.__ifloordiv__;case "Mod":return a.nb$inplace_remainder;case "Pow":return a.nb$inplace_power;case "LShift":return a.nb$inplace_lshift?
a.nb$inplace_lshift:a.__ilshift__;case "RShift":return a.nb$inplace_rshift?a.nb$inplace_rshift:a.__irshift__;case "BitAnd":return a.nb$inplace_and;case "BitOr":return a.nb$inplace_or;case "BitXor":return a.nb$inplace_xor?a.nb$inplace_xor:a.__ixor__}};Sk.abstr.uoNameToSlotFunc_=function(a,b){if(null!==a)switch(b){case "USub":return a.nb$negative?a.nb$negative:a.__neg__;case "UAdd":return a.nb$positive?a.nb$positive:a.__pos__;case "Invert":return a.nb$invert?a.nb$invert:a.__invert__}};
Sk.abstr.binary_op_=function(a,b,c){var d,e=b.constructor.prototype instanceof a.constructor;if(e&&(d=Sk.abstr.boNameToSlotFuncRhs_(b,c),void 0!==d&&(d=d.call?d.call(b,a):Sk.misceval.callsim(d,b,a),void 0!==d&&d!==Sk.builtin.NotImplemented.NotImplemented$)))return d;d=Sk.abstr.boNameToSlotFuncLhs_(a,c);if(void 0!==d&&(d=d.call?d.call(a,b):Sk.misceval.callsim(d,a,b),void 0!==d&&d!==Sk.builtin.NotImplemented.NotImplemented$)||!e&&(d=Sk.abstr.boNameToSlotFuncRhs_(b,c),void 0!==d&&(d=d.call?d.call(b,
a):Sk.misceval.callsim(d,b,a),void 0!==d&&d!==Sk.builtin.NotImplemented.NotImplemented$)))return d;Sk.abstr.binop_type_error(a,b,c)};
Sk.abstr.binary_iop_=function(a,b,c){var d;d=Sk.abstr.iboNameToSlotFunc_(a,c);if(void 0!==d&&(d=d.call?d.call(a,b):Sk.misceval.callsim(d,a,b),void 0!==d&&d!==Sk.builtin.NotImplemented.NotImplemented$))return d;d=Sk.abstr.iboNameToSlotFunc_(b,c);if(void 0!==d&&(d=d.call?d.call(b,a):Sk.misceval.callsim(d,b,a),void 0!==d&&d!==Sk.builtin.NotImplemented.NotImplemented$))return d;Sk.abstr.binop_type_error(a,b,c)};
Sk.abstr.unary_op_=function(a,b){var c;c=Sk.abstr.uoNameToSlotFunc_(a,b);if(void 0!==c&&(c=c.call?c.call(a):Sk.misceval.callsim(c,a),void 0!==c))return c;Sk.abstr.unop_type_error(a,b)};
Sk.abstr.numOpAndPromote=function(a,b,c){if(null!==a&&null!==b){if("number"===typeof a&&"number"===typeof b)return c=c(a,b),(c>Sk.builtin.int_.threshold$||c<-Sk.builtin.int_.threshold$)&&Math.floor(c)===c?[Sk.builtin.lng.fromInt$(a),Sk.builtin.lng.fromInt$(b)]:c;if(void 0===a||void 0===b)throw new Sk.builtin.NameError("Undefined variable in expression");if(a.constructor===Sk.builtin.lng)return[a,b];if(a.constructor!==Sk.builtin.int_&&a.constructor!==Sk.builtin.float_||b.constructor!==Sk.builtin.complex){if(a.constructor===
Sk.builtin.int_||a.constructor===Sk.builtin.float_)return[a,b];if("number"===typeof a)return a=Sk.builtin.assk$(a),[a,b]}else return a=new Sk.builtin.complex(a),[a,b]}};
Sk.abstr.boNumPromote_={Add:function(a,b){return a+b},Sub:function(a,b){return a-b},Mult:function(a,b){return a*b},Mod:function(a,b){var c;if(0===b)throw new Sk.builtin.ZeroDivisionError("division or modulo by zero");c=a%b;return 0>c*b?c+b:c},Div:function(a,b){if(0===b)throw new Sk.builtin.ZeroDivisionError("division or modulo by zero");return a/b},FloorDiv:function(a,b){if(0===b)throw new Sk.builtin.ZeroDivisionError("division or modulo by zero");return Math.floor(a/b)},Pow:Math.pow,BitAnd:function(a,
b){var c=a&b;0>c&&(c+=4294967296);return c},BitOr:function(a,b){var c=a|b;0>c&&(c+=4294967296);return c},BitXor:function(a,b){var c=a^b;0>c&&(c+=4294967296);return c},LShift:function(a,b){var c;if(0>b)throw new Sk.builtin.ValueError("negative shift count");c=a<<b;return c>a?c:a*Math.pow(2,b)},RShift:function(a,b){var c;if(0>b)throw new Sk.builtin.ValueError("negative shift count");c=a>>b;0<a&&0>c&&(c&=Math.pow(2,32-b)-1);return c}};
Sk.abstr.numberBinOp=function(a,b,c){var d;d=Sk.abstr.boNumPromote_[c];if(void 0!==d){d=Sk.abstr.numOpAndPromote(a,b,d);if("number"===typeof d)return d;if(void 0!==d&&d.constructor===Sk.builtin.int_||void 0!==d&&d.constructor===Sk.builtin.float_||void 0!==d&&d.constructor===Sk.builtin.lng)return d;void 0!==d&&(a=d[0],b=d[1])}return Sk.abstr.binary_op_(a,b,c)};goog.exportSymbol("Sk.abstr.numberBinOp",Sk.abstr.numberBinOp);
Sk.abstr.numberInplaceBinOp=function(a,b,c){var d;d=Sk.abstr.boNumPromote_[c];if(void 0!==d){d=Sk.abstr.numOpAndPromote(a,b,d);if("number"===typeof d)return d;if(void 0!==d&&d.constructor===Sk.builtin.int_||void 0!==d&&d.constructor===Sk.builtin.float_||void 0!==d&&d.constructor===Sk.builtin.lng)return d;void 0!==d&&(a=d[0],b=d[1])}return Sk.abstr.binary_iop_(a,b,c)};goog.exportSymbol("Sk.abstr.numberInplaceBinOp",Sk.abstr.numberInplaceBinOp);
Sk.abstr.numberUnaryOp=function(a,b){var c;if("Not"===b)return Sk.misceval.isTrue(a)?Sk.builtin.bool.false$:Sk.builtin.bool.true$;if(a instanceof Sk.builtin.bool){c=Sk.builtin.asnum$(a);if("USub"===b)return new Sk.builtin.int_(-c);if("UAdd"===b)return new Sk.builtin.int_(c);if("Invert"===b)return new Sk.builtin.int_(~c)}else{if("USub"===b&&a.nb$negative)return a.nb$negative();if("UAdd"===b&&a.nb$positive)return a.nb$positive();if("Invert"===b&&a.nb$invert)return a.nb$invert()}return Sk.abstr.unary_op_(a,
b)};goog.exportSymbol("Sk.abstr.numberUnaryOp",Sk.abstr.numberUnaryOp);Sk.abstr.fixSeqIndex_=function(a,b){b=Sk.builtin.asnum$(b);0>b&&a.sq$length&&(b+=a.sq$length());return b};
Sk.abstr.sequenceContains=function(a,b){var c,d;if(a.sq$contains)return a.sq$contains(b);c=Sk.abstr.lookupSpecial(a,"__contains__");if(null!=c)return Sk.misceval.isTrue(Sk.misceval.callsim(c,a,b));if(!Sk.builtin.checkIterable(a))throw c=Sk.abstr.typeName(a),new Sk.builtin.TypeError("argument of type '"+c+"' is not iterable");c=Sk.abstr.iter(a);for(d=c.tp$iternext();void 0!==d;d=c.tp$iternext())if(Sk.misceval.richCompareBool(d,b,"Eq"))return!0;return!1};
Sk.abstr.sequenceConcat=function(a,b){var c;if(a.sq$concat)return a.sq$concat(b);c=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("'"+c+"' object can't be concatenated");};
Sk.abstr.sequenceGetIndexOf=function(a,b){var c,d,e;if(a.index)return Sk.misceval.callsim(a.index,a,b);if(Sk.builtin.checkIterable(a)){e=0;d=Sk.abstr.iter(a);for(c=d.tp$iternext();void 0!==c;c=d.tp$iternext()){if(Sk.misceval.richCompareBool(b,c,"Eq"))return new Sk.builtin.int_(e);e+=1}throw new Sk.builtin.ValueError("sequence.index(x): x not in sequence");}c=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("argument of type '"+c+"' is not iterable");};
Sk.abstr.sequenceGetCountOf=function(a,b){var c,d,e;if(a.count)return Sk.misceval.callsim(a.count,a,b);if(Sk.builtin.checkIterable(a)){e=0;d=Sk.abstr.iter(a);for(c=d.tp$iternext();void 0!==c;c=d.tp$iternext())Sk.misceval.richCompareBool(b,c,"Eq")&&(e+=1);return new Sk.builtin.int_(e)}c=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("argument of type '"+c+"' is not iterable");};
Sk.abstr.sequenceGetItem=function(a,b,c){if(a.mp$subscript)return a.mp$subscript(b);a=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("'"+a+"' object is unsubscriptable");};Sk.abstr.sequenceSetItem=function(a,b,c,d){if(a.mp$ass_subscript)return a.mp$ass_subscript(b,c);a=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("'"+a+"' object does not support item assignment");};
Sk.abstr.sequenceDelItem=function(a,b){var c;if(a.sq$del_item)b=Sk.abstr.fixSeqIndex_(a,b),a.sq$del_item(b);else throw c=Sk.abstr.typeName(a),new Sk.builtin.TypeError("'"+c+"' object does not support item deletion");};Sk.abstr.sequenceRepeat=function(a,b,c){c=Sk.builtin.asnum$(c);if(void 0===Sk.misceval.asIndex(c))throw a=Sk.abstr.typeName(c),new Sk.builtin.TypeError("can't multiply sequence by non-int of type '"+a+"'");return a.call(b,c)};
Sk.abstr.sequenceGetSlice=function(a,b,c){if(a.sq$slice)return b=Sk.abstr.fixSeqIndex_(a,b),c=Sk.abstr.fixSeqIndex_(a,c),a.sq$slice(b,c);if(a.mp$subscript)return a.mp$subscript(new Sk.builtin.slice(b,c));a=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("'"+a+"' object is unsliceable");};
Sk.abstr.sequenceDelSlice=function(a,b,c){if(a.sq$del_slice)b=Sk.abstr.fixSeqIndex_(a,b),c=Sk.abstr.fixSeqIndex_(a,c),a.sq$del_slice(b,c);else throw a=Sk.abstr.typeName(a),new Sk.builtin.TypeError("'"+a+"' doesn't support slice deletion");};
Sk.abstr.sequenceSetSlice=function(a,b,c,d){if(a.sq$ass_slice)b=Sk.abstr.fixSeqIndex_(a,b),c=Sk.abstr.fixSeqIndex_(a,c),a.sq$ass_slice(b,c,d);else if(a.mp$ass_subscript)a.mp$ass_subscript(new Sk.builtin.slice(b,c),d);else throw a=Sk.abstr.typeName(a),new Sk.builtin.TypeError("'"+a+"' object doesn't support slice assignment");};
Sk.abstr.sequenceUnpack=function(a,b){var c=[],d,e;if(!Sk.builtin.checkIterable(a))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(a)+"' object is not iterable");d=Sk.abstr.iter(a);for(e=d.tp$iternext();void 0!==e&&c.length<b;e=d.tp$iternext())c.push(e);if(c.length<b)throw new Sk.builtin.ValueError("need more than "+c.length+" values to unpack");if(void 0!==e)throw new Sk.builtin.ValueError("too many values to unpack");return c};
Sk.abstr.objectFormat=function(a,b){var c;null==b&&(b="");c=Sk.abstr.lookupSpecial(a,"__format__");if(null==c)throw new Sk.builtin.TypeError("Type "+Sk.abstr.typeName(a)+"doesn't define __format__");c=Sk.misceval.callsim(c,a,b);if(!Sk.builtin.checkString(c))throw new Sk.builtin.TypeError("__format__ must return a str, not "+Sk.abstr.typeName(c));return c};
Sk.abstr.objectAdd=function(a,b){var c,d;if(a.nb$add)return a.nb$add(b);d=Sk.abstr.typeName(a);c=Sk.abstr.typeName(b);throw new Sk.builtin.TypeError("unsupported operand type(s) for +: '"+d+"' and '"+c+"'");};Sk.abstr.objectNegative=function(a){var b=Sk.builtin.asnum$(a);a instanceof Sk.builtin.bool&&(a=new Sk.builtin.int_(b));if(a.nb$negative)return a.nb$negative();a=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("bad operand type for unary -: '"+a+"'");};
Sk.abstr.objectPositive=function(a){var b=Sk.abstr.typeName(a),c=Sk.builtin.asnum$(a);a instanceof Sk.builtin.bool&&(a=new Sk.builtin.int_(c));if(a.nb$negative)return a.nb$positive();throw new Sk.builtin.TypeError("bad operand type for unary +: '"+b+"'");};
Sk.abstr.objectDelItem=function(a,b){var c;if(null!==a){if(a.mp$del_subscript){a.mp$del_subscript(b);return}if(a.sq$ass_item){c=Sk.misceval.asIndex(b);if(void 0===c)throw c=Sk.abstr.typeName(b),new Sk.builtin.TypeError("sequence index must be integer, not '"+c+"'");Sk.abstr.sequenceDelItem(a,c);return}}c=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("'"+c+"' object does not support item deletion");};goog.exportSymbol("Sk.abstr.objectDelItem",Sk.abstr.objectDelItem);
Sk.abstr.objectGetItem=function(a,b,c){if(null!==a){if(a.tp$getitem)return a.tp$getitem(b,c);if(a.mp$subscript)return a.mp$subscript(b,c);if(Sk.misceval.isIndex(b)&&a.sq$item)return Sk.abstr.sequenceGetItem(a,Sk.misceval.asIndex(b),c)}a=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("'"+a+"' does not support indexing");};goog.exportSymbol("Sk.abstr.objectGetItem",Sk.abstr.objectGetItem);
Sk.abstr.objectSetItem=function(a,b,c,d){if(null!==a){if(a.tp$setitem)return a.tp$setitem(b,c,d);if(a.mp$ass_subscript)return a.mp$ass_subscript(b,c,d);if(Sk.misceval.isIndex(b)&&a.sq$ass_item)return Sk.abstr.sequenceSetItem(a,Sk.misceval.asIndex(b),c,d)}a=Sk.abstr.typeName(a);throw new Sk.builtin.TypeError("'"+a+"' does not support item assignment");};goog.exportSymbol("Sk.abstr.objectSetItem",Sk.abstr.objectSetItem);
Sk.abstr.gattr=function(a,b,c){var d,e,f=Sk.abstr.typeName(a);if(null===a)throw new Sk.builtin.AttributeError("'"+f+"' object has no attribute '"+b+"'");void 0!==a.tp$getattr&&(e=a.tp$getattr("__getattribute__"));void 0!==e&&(d=Sk.misceval.callsimOrSuspend(e,new Sk.builtin.str(b)));d=Sk.misceval.chain(d,function(c){var d;void 0===c&&void 0!==a.tp$getattr&&(c=a.tp$getattr(b),void 0===c&&(d=a.tp$getattr("__getattr__"),void 0!==d&&(c=Sk.misceval.callsimOrSuspend(d,new Sk.builtin.str(b)))));return c},
function(a){if(void 0===a)throw new Sk.builtin.AttributeError("'"+f+"' object has no attribute '"+b+"'");return a});return c?d:Sk.misceval.retryOptionalSuspensionOrThrow(d)};goog.exportSymbol("Sk.abstr.gattr",Sk.abstr.gattr);
Sk.abstr.sattr=function(a,b,c,d){var e=Sk.abstr.typeName(a),f;if(null===a)throw new Sk.builtin.AttributeError("'"+e+"' object has no attribute '"+b+"'");if(void 0!==a.tp$getattr&&(f=a.tp$getattr("__setattr__"),void 0!==f))return a=Sk.misceval.callsimOrSuspend(f,new Sk.builtin.str(b),c),d?a:Sk.misceval.retryOptionalSuspensionOrThrow(a);if(void 0!==a.tp$setattr)a.tp$setattr(b,c);else throw new Sk.builtin.AttributeError("'"+e+"' object has no attribute '"+b+"'");};
goog.exportSymbol("Sk.abstr.sattr",Sk.abstr.sattr);Sk.abstr.iternext=function(a,b){return a.tp$iternext(b)};goog.exportSymbol("Sk.abstr.iternext",Sk.abstr.iternext);
Sk.abstr.iter=function(a){var b,c,d=function(a){this.idx=0;this.myobj=a;this.getitem=Sk.abstr.lookupSpecial(a,"__getitem__");this.tp$iternext=function(){var a;try{a=Sk.misceval.callsim(this.getitem,this.myobj,Sk.ffi.remapToPy(this.idx))}catch(b){if(b instanceof Sk.builtin.IndexError)return;throw b;}this.idx++;return a}};if(a.tp$getattr&&(b=Sk.abstr.lookupSpecial(a,"__iter__")))return Sk.misceval.callsim(b,a);if(a.tp$iter)try{if(c=a.tp$iter(),c.tp$iternext)return c}catch(e){}if(Sk.abstr.lookupSpecial(a,
"__getitem__"))return new d(a);throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(a)+"' object is not iterable");};goog.exportSymbol("Sk.abstr.iter",Sk.abstr.iter);Sk.abstr.lookupSpecial=function(a,b){var c;if(a.ob$type)c=a.ob$type;else return null;return Sk.builtin.type.typeLookup(c,b)};goog.exportSymbol("Sk.abstr.lookupSpecial",Sk.abstr.lookupSpecial);Sk.abstr.markUnhashable=function(a){a=a.prototype;a.__hash__=Sk.builtin.none.none$;a.tp$hash=Sk.builtin.none.none$};
Sk.abstr.setUpInheritance=function(a,b,c){goog.inherits(b,c);b.prototype.tp$base=c;b.prototype.tp$name=a;b.prototype.ob$type=Sk.builtin.type.makeIntoTypeObj(a,b)};Sk.abstr.superConstructor=function(a,b,c){var d=Array.prototype.slice.call(arguments,2);a.prototype.tp$base.apply(b,d)};Sk.builtin.object=function(){return this instanceof Sk.builtin.object?this:new Sk.builtin.object};
Sk.builtin.object.prototype.GenericGetAttr=function(a){var b,c,d,e,f=new Sk.builtin.str(a);goog.asserts.assert("string"===typeof a);d=this.ob$type;goog.asserts.assert(void 0!==d,"object has no ob$type!");if(e=this.$d||this.constructor.$d){if(e.mp$lookup)b=e.mp$lookup(f);else if(e.mp$subscript)try{b=e.mp$subscript(f)}catch(g){b=void 0}else"object"===typeof e&&(b=e[a]);if(void 0!==b)return b}a=Sk.builtin.type.typeLookup(d,a);void 0!==a&&(null!==a&&void 0!==a.ob$type)&&(c=a.ob$type.tp$descr_get);if(c)return c.call(a,
this,this.ob$type);if(void 0!==a)return a};goog.exportSymbol("Sk.builtin.object.prototype.GenericGetAttr",Sk.builtin.object.prototype.GenericGetAttr);Sk.builtin.object.prototype.GenericPythonGetAttr=function(a,b){return Sk.builtin.object.prototype.GenericGetAttr.call(a,b.v)};goog.exportSymbol("Sk.builtin.object.prototype.GenericPythonGetAttr",Sk.builtin.object.prototype.GenericPythonGetAttr);
Sk.builtin.object.prototype.GenericSetAttr=function(a,b){var c=Sk.abstr.typeName(this),d,e;goog.asserts.assert("string"===typeof a);e=this.$d||this.constructor.$d;if(e.mp$ass_subscript){d=new Sk.builtin.str(a);if(this instanceof Sk.builtin.object&&!this.ob$type.sk$klass&&void 0===e.mp$lookup(d))throw new Sk.builtin.AttributeError("'"+c+"' object has no attribute '"+a+"'");e.mp$ass_subscript(new Sk.builtin.str(a),b)}else"object"===typeof e&&(e[a]=b)};
goog.exportSymbol("Sk.builtin.object.prototype.GenericSetAttr",Sk.builtin.object.prototype.GenericSetAttr);Sk.builtin.object.prototype.GenericPythonSetAttr=function(a,b,c){return Sk.builtin.object.prototype.GenericSetAttr.call(a,b.v,c)};goog.exportSymbol("Sk.builtin.object.prototype.GenericPythonSetAttr",Sk.builtin.object.prototype.GenericPythonSetAttr);Sk.builtin.object.prototype.HashNotImplemented=function(){throw new Sk.builtin.TypeError("unhashable type: '"+Sk.abstr.typeName(this)+"'");};
Sk.builtin.object.prototype.tp$getattr=Sk.builtin.object.prototype.GenericGetAttr;Sk.builtin.object.prototype.tp$setattr=Sk.builtin.object.prototype.GenericSetAttr;Sk.builtin.object.prototype.__getattr__=Sk.builtin.object.prototype.GenericPythonGetAttr;Sk.builtin.object.prototype.__setattr__=Sk.builtin.object.prototype.GenericPythonSetAttr;Sk.builtin.object.prototype.tp$name="object";Sk.builtin.object.prototype.ob$type=Sk.builtin.type.makeIntoTypeObj("object",Sk.builtin.object);
Sk.builtin.object.prototype.ob$type.sk$klass=void 0;Sk.builtin.object.prototype.__repr__=function(a){Sk.builtin.pyCheckArgs("__repr__",arguments,0,0,!1,!0);return a.$r()};Sk.builtin.object.prototype.__str__=function(a){Sk.builtin.pyCheckArgs("__str__",arguments,0,0,!1,!0);return a.$r()};Sk.builtin.object.prototype.__hash__=function(a){Sk.builtin.pyCheckArgs("__hash__",arguments,0,0,!1,!0);return a.tp$hash()};
Sk.builtin.object.prototype.__eq__=function(a,b){Sk.builtin.pyCheckArgs("__eq__",arguments,1,1,!1,!0);return a.ob$eq(b)};Sk.builtin.object.prototype.__ne__=function(a,b){Sk.builtin.pyCheckArgs("__ne__",arguments,1,1,!1,!0);return a.ob$ne(b)};Sk.builtin.object.prototype.__lt__=function(a,b){Sk.builtin.pyCheckArgs("__lt__",arguments,1,1,!1,!0);return a.ob$lt(b)};Sk.builtin.object.prototype.__le__=function(a,b){Sk.builtin.pyCheckArgs("__le__",arguments,1,1,!1,!0);return a.ob$le(b)};
Sk.builtin.object.prototype.__gt__=function(a,b){Sk.builtin.pyCheckArgs("__gt__",arguments,1,1,!1,!0);return a.ob$gt(b)};Sk.builtin.object.prototype.__ge__=function(a,b){Sk.builtin.pyCheckArgs("__ge__",arguments,1,1,!1,!0);return a.ob$ge(b)};Sk.builtin.object.prototype.$r=function(){return new Sk.builtin.str("<object>")};Sk.builtin.hashCount=1;Sk.builtin.object.prototype.tp$hash=function(){this.$savedHash_||(this.$savedHash_=new Sk.builtin.int_(Sk.builtin.hashCount++));return this.$savedHash_};
Sk.builtin.object.prototype.ob$eq=function(a){return this===a?Sk.builtin.bool.true$:Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.object.prototype.ob$ne=function(a){return this===a?Sk.builtin.bool.false$:Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.object.prototype.ob$lt=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.object.prototype.ob$le=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.object.prototype.ob$gt=function(a){return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.object.prototype.ob$ge=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.object.pythonFunctions="__repr__ __str__ __hash__ __eq__ __ne__ __lt__ __le__ __gt__ __ge__ __getattr__ __setattr__".split(" ");Sk.builtin.none=function(){this.v=null};Sk.abstr.setUpInheritance("NoneType",Sk.builtin.none,Sk.builtin.object);Sk.builtin.none.prototype.$r=function(){return new Sk.builtin.str("None")};Sk.builtin.none.prototype.tp$hash=function(){return new Sk.builtin.int_(0)};
Sk.builtin.none.none$=new Sk.builtin.none;Sk.builtin.NotImplemented=function(){};Sk.abstr.setUpInheritance("NotImplementedType",Sk.builtin.NotImplemented,Sk.builtin.object);Sk.builtin.NotImplemented.prototype.$r=function(){return new Sk.builtin.str("NotImplemented")};Sk.builtin.NotImplemented.NotImplemented$=new Sk.builtin.NotImplemented;goog.exportSymbol("Sk.builtin.none",Sk.builtin.none);goog.exportSymbol("Sk.builtin.NotImplemented",Sk.builtin.NotImplemented);Sk.builtin.pyCheckArgs=function(a,b,c,d,e,f){b=b.length;var g="";void 0===d&&(d=Infinity);e&&(b-=1);f&&(b-=1);if(b<c||b>d)throw g=(c===d?a+"() takes exactly "+c+" arguments":b<c?a+"() takes at least "+c+" arguments":a+"() takes at most "+d+" arguments")+(" ("+b+" given)"),new Sk.builtin.TypeError(g);};goog.exportSymbol("Sk.builtin.pyCheckArgs",Sk.builtin.pyCheckArgs);Sk.builtin.pyCheckType=function(a,b,c){if(!c)throw new Sk.builtin.TypeError(a+" must be a "+b);};
goog.exportSymbol("Sk.builtin.pyCheckType",Sk.builtin.pyCheckType);Sk.builtin.checkSequence=function(a){return null!==a&&void 0!==a.mp$subscript};goog.exportSymbol("Sk.builtin.checkSequence",Sk.builtin.checkSequence);Sk.builtin.checkIterable=function(a){var b=!1;if(null!==a)try{return(b=Sk.abstr.iter(a))?!0:!1}catch(c){if(c instanceof Sk.builtin.TypeError)return!1;throw c;}return b};goog.exportSymbol("Sk.builtin.checkIterable",Sk.builtin.checkIterable);
Sk.builtin.checkCallable=function(a){return"function"===typeof a?!(a instanceof Sk.builtin.none)&&void 0!==a.ob$type:void 0!==a.tp$call||void 0!==a.__call__};Sk.builtin.checkNumber=function(a){return null!==a&&("number"===typeof a||a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_||a instanceof Sk.builtin.lng)};goog.exportSymbol("Sk.builtin.checkNumber",Sk.builtin.checkNumber);Sk.builtin.checkComplex=function(a){return Sk.builtin.complex._complex_check(a)};
goog.exportSymbol("Sk.builtin.checkComplex",Sk.builtin.checkComplex);Sk.builtin.checkInt=function(a){return null!==a&&("number"===typeof a&&a===(a|0)||a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng)};goog.exportSymbol("Sk.builtin.checkInt",Sk.builtin.checkInt);Sk.builtin.checkFloat=function(a){return null!==a&&a instanceof Sk.builtin.float_};goog.exportSymbol("Sk.builtin.checkFloat",Sk.builtin.checkFloat);Sk.builtin.checkString=function(a){return null!==a&&a.__class__==Sk.builtin.str};
goog.exportSymbol("Sk.builtin.checkString",Sk.builtin.checkString);Sk.builtin.checkClass=function(a){return null!==a&&a.sk$type};goog.exportSymbol("Sk.builtin.checkClass",Sk.builtin.checkClass);Sk.builtin.checkBool=function(a){return a instanceof Sk.builtin.bool};goog.exportSymbol("Sk.builtin.checkBool",Sk.builtin.checkBool);Sk.builtin.checkNone=function(a){return a instanceof Sk.builtin.none};goog.exportSymbol("Sk.builtin.checkNone",Sk.builtin.checkNone);
Sk.builtin.checkFunction=function(a){return null!==a&&void 0!==a.tp$call};goog.exportSymbol("Sk.builtin.checkFunction",Sk.builtin.checkFunction);Sk.builtin.func=function(a,b,c,d){var e;this.func_code=a;this.func_globals=b||null;if(void 0!==d)for(e in d)c[e]=d[e];this.func_closure=c;return this};goog.exportSymbol("Sk.builtin.func",Sk.builtin.func);Sk.builtin.func.prototype.tp$name="function";
Sk.builtin.func.prototype.tp$descr_get=function(a,b){goog.asserts.assert(void 0!==a&&void 0!==b);return null==a?this:new Sk.builtin.method(this,a)};
Sk.builtin.func.prototype.tp$call=function(a,b){var c,d,e,f,g,h,k;this.func_closure&&a.push(this.func_closure);k=this.func_code.co_kwargs;h=[];if(this.func_code.no_kw&&b)throw c=this.func_code&&this.func_code.co_name&&this.func_code.co_name.v||"<native JS>",new Sk.builtin.TypeError(c+"() takes no keyword arguments");if(b)for(g=b.length,e=(f=this.func_code.co_varnames)&&f.length,d=0;d<g;d+=2){for(c=0;c<e&&b[d]!==f[c];++c);if(f&&c!==e)a[c]=b[d+1];else if(k)h.push(new Sk.builtin.str(b[d])),h.push(b[d+
1]);else throw c=this.func_code&&this.func_code.co_name&&this.func_code.co_name.v||"<native JS>",new Sk.builtin.TypeError(c+"() got an unexpected keyword argument '"+b[d]+"'");}k&&a.unshift(h);return this.func_code.apply(this.func_globals,a)};Sk.builtin.func.prototype.tp$getattr=function(a){return this[a]};Sk.builtin.func.prototype.tp$setattr=function(a,b){this[a]=b};Sk.builtin.func.prototype.ob$type=Sk.builtin.type.makeTypeObj("function",new Sk.builtin.func(null,null));
Sk.builtin.func.prototype.$r=function(){return new Sk.builtin.str("<function "+(this.func_code&&this.func_code.co_name&&this.func_code.co_name.v||"<native JS>")+">")};Sk.builtin.range=function(a,b,c){var d=[],e;Sk.builtin.pyCheckArgs("range",arguments,1,3);Sk.builtin.pyCheckType("start","integer",Sk.builtin.checkInt(a));void 0!==b&&Sk.builtin.pyCheckType("stop","integer",Sk.builtin.checkInt(b));void 0!==c&&Sk.builtin.pyCheckType("step","integer",Sk.builtin.checkInt(c));a=Sk.builtin.asnum$(a);b=Sk.builtin.asnum$(b);c=Sk.builtin.asnum$(c);void 0===b&&void 0===c?(b=a,a=0,c=1):void 0===c&&(c=1);if(0===c)throw new Sk.builtin.ValueError("range() step argument must not be zero");
if(0<c)for(e=a;e<b;e+=c)d.push(new Sk.builtin.int_(e));else for(e=a;e>b;e+=c)d.push(new Sk.builtin.int_(e));return new Sk.builtin.list(d)};
Sk.builtin.asnum$=function(a){return void 0===a||null===a?a:a instanceof Sk.builtin.none?null:a instanceof Sk.builtin.bool?a.v?1:0:"number"===typeof a?a:"string"===typeof a?a:a instanceof Sk.builtin.int_?a.v:a instanceof Sk.builtin.float_?a.v:a instanceof Sk.builtin.lng?a.cantBeInt()?a.str$(10,!0):a.toInt$():a.constructor===Sk.builtin.biginteger?0<a.trueCompare(new Sk.builtin.biginteger(Sk.builtin.int_.threshold$))||0>a.trueCompare(new Sk.builtin.biginteger(-Sk.builtin.int_.threshold$))?a.toString():
a.intValue():a};goog.exportSymbol("Sk.builtin.asnum$",Sk.builtin.asnum$);Sk.builtin.assk$=function(a){return 0===a%1?new Sk.builtin.int_(a):new Sk.builtin.float_(a)};goog.exportSymbol("Sk.builtin.assk$",Sk.builtin.assk$);
Sk.builtin.asnum$nofloat=function(a){var b,c;if(void 0===a||null===a)return a;if(a.constructor===Sk.builtin.none)return null;if(a.constructor===Sk.builtin.bool)return a.v?1:0;"number"===typeof a&&(a=a.toString());a.constructor===Sk.builtin.int_&&(a=a.v.toString());a.constructor===Sk.builtin.float_&&(a=a.v.toString());a.constructor===Sk.builtin.lng&&(a=a.str$(10,!0));a.constructor===Sk.builtin.biginteger&&(a=a.toString());if(0>a.indexOf(".")&&0>a.indexOf("e")&&0>a.indexOf("E"))return a;c=0;0<=a.indexOf("e")?
(b=a.substr(0,a.indexOf("e")),c=a.substr(a.indexOf("e")+1)):0<=a.indexOf("E")?(b=a.substr(0,a.indexOf("e")),c=a.substr(a.indexOf("E")+1)):b=a;c=parseInt(c,10);a=b.indexOf(".");if(0>a){if(0<=c){for(;0<c--;)b+="0";return b}return b.length>-c?b.substr(0,b.length+c):0}b=0===a?b.substr(1):a<b.length?b.substr(0,a)+b.substr(a+1):b.substr(0,a);for(a+=c;a>b.length;)b+="0";return b=0>=a?0:b.substr(0,a)};goog.exportSymbol("Sk.builtin.asnum$nofloat",Sk.builtin.asnum$nofloat);
Sk.builtin.round=function(a,b){var c;Sk.builtin.pyCheckArgs("round",arguments,1,2);if(!Sk.builtin.checkNumber(a))throw new Sk.builtin.TypeError("a float is required");if(void 0!==b&&!Sk.misceval.isIndex(b))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(b)+"' object cannot be interpreted as an index");void 0===b&&(b=0);if(a.__round__)return a.__round__(a,b);c=Sk.abstr.lookupSpecial(a,"__round__");if(null!=c)return Sk.misceval.callsim(c,a,b)};
Sk.builtin.len=function(a){Sk.builtin.pyCheckArgs("len",arguments,1,1);if(a.sq$length)return new Sk.builtin.int_(a.sq$length());if(a.mp$length)return new Sk.builtin.int_(a.mp$length());if(a.tp$length)return new Sk.builtin.int_(a.tp$length());throw new Sk.builtin.TypeError("object of type '"+Sk.abstr.typeName(a)+"' has no len()");};
Sk.builtin.min=function(){var a,b,c;Sk.builtin.pyCheckArgs("min",arguments,1);c=Sk.misceval.arrayFromArguments(arguments);b=c[0];if(void 0===b)throw new Sk.builtin.ValueError("min() arg is an empty sequence");for(a=1;a<c.length;++a)Sk.misceval.richCompareBool(c[a],b,"Lt")&&(b=c[a]);return b};
Sk.builtin.max=function(){var a,b,c;Sk.builtin.pyCheckArgs("max",arguments,1);c=Sk.misceval.arrayFromArguments(arguments);b=c[0];if(void 0===b)throw new Sk.builtin.ValueError("max() arg is an empty sequence");for(a=1;a<c.length;++a)Sk.misceval.richCompareBool(c[a],b,"Gt")&&(b=c[a]);return b};
Sk.builtin.any=function(a){var b,c;Sk.builtin.pyCheckArgs("any",arguments,1,1);if(!Sk.builtin.checkIterable(a))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(a)+"' object is not iterable");b=Sk.abstr.iter(a);for(c=b.tp$iternext();void 0!==c;c=b.tp$iternext())if(Sk.misceval.isTrue(c))return Sk.builtin.bool.true$;return Sk.builtin.bool.false$};
Sk.builtin.all=function(a){var b,c;Sk.builtin.pyCheckArgs("all",arguments,1,1);if(!Sk.builtin.checkIterable(a))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(a)+"' object is not iterable");b=Sk.abstr.iter(a);for(c=b.tp$iternext();void 0!==c;c=b.tp$iternext())if(!Sk.misceval.isTrue(c))return Sk.builtin.bool.false$;return Sk.builtin.bool.true$};
Sk.builtin.sum=function(a,b){var c,d,e,f,g;Sk.builtin.pyCheckArgs("sum",arguments,1,2);Sk.builtin.pyCheckType("iter","iterable",Sk.builtin.checkIterable(a));if(void 0!==b&&Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("sum() can't sum strings [use ''.join(seq) instead]");c=void 0===b?new Sk.builtin.int_(0):b;e=Sk.abstr.iter(a);for(f=e.tp$iternext();void 0!==f;f=e.tp$iternext()){f instanceof Sk.builtin.float_?(g=!0,c instanceof Sk.builtin.float_||(c=new Sk.builtin.float_(Sk.builtin.asnum$(c)))):
f instanceof Sk.builtin.lng&&(g||c instanceof Sk.builtin.lng||(c=new Sk.builtin.lng(c)));if(void 0!==c.nb$add&&(d=c.nb$add(f),void 0!==d&&d!==Sk.builtin.NotImplemented.NotImplemented$)){c=c.nb$add(f);continue}throw new Sk.builtin.TypeError("unsupported operand type(s) for +: '"+Sk.abstr.typeName(c)+"' and '"+Sk.abstr.typeName(f)+"'");}return c};
Sk.builtin.zip=function(){var a,b,c,d,e,f;if(0===arguments.length)return new Sk.builtin.list([]);f=[];for(e=0;e<arguments.length;e++)if(Sk.builtin.checkIterable(arguments[e]))f.push(Sk.abstr.iter(arguments[e]));else throw new Sk.builtin.TypeError("argument "+e+" must support iteration");d=[];for(c=!1;!c;){b=[];for(e=0;e<arguments.length;e++){a=f[e].tp$iternext();if(void 0===a){c=!0;break}b.push(a)}c||d.push(new Sk.builtin.tuple(b))}return new Sk.builtin.list(d)};
Sk.builtin.abs=function(a){Sk.builtin.pyCheckArgs("abs",arguments,1,1);if(a instanceof Sk.builtin.int_)return new Sk.builtin.int_(Math.abs(a.v));if(a instanceof Sk.builtin.float_)return new Sk.builtin.float_(Math.abs(a.v));if(Sk.builtin.checkNumber(a))return Sk.builtin.assk$(Math.abs(Sk.builtin.asnum$(a)));if(Sk.builtin.checkComplex(a))return Sk.misceval.callsim(a.__abs__,a);throw new TypeError("bad operand type for abs(): '"+Sk.abstr.typeName(a)+"'");};
Sk.builtin.ord=function(a){Sk.builtin.pyCheckArgs("ord",arguments,1,1);if(!Sk.builtin.checkString(a))throw new Sk.builtin.TypeError("ord() expected a string of length 1, but "+Sk.abstr.typeName(a)+" found");if(1!==a.v.length)throw new Sk.builtin.TypeError("ord() expected a character, but string of length "+a.v.length+" found");return new Sk.builtin.int_(a.v.charCodeAt(0))};
Sk.builtin.chr=function(a){Sk.builtin.pyCheckArgs("chr",arguments,1,1);if(!Sk.builtin.checkInt(a))throw new Sk.builtin.TypeError("an integer is required");a=Sk.builtin.asnum$(a);if(0>a||255<a)throw new Sk.builtin.ValueError("chr() arg not in range(256)");return new Sk.builtin.str(String.fromCharCode(a))};
Sk.builtin.int2str_=function(a,b,c){var d,e="";if(a instanceof Sk.builtin.lng)return d="",2!==b&&(d="L"),e=a.str$(b,!1),a.nb$isnegative()?new Sk.builtin.str("-"+c+e+d):new Sk.builtin.str(c+e+d);a=Sk.misceval.asIndex(a);e=a.toString(b);return 0>a?new Sk.builtin.str("-"+c+e.slice(1)):new Sk.builtin.str(c+e)};
Sk.builtin.hex=function(a){Sk.builtin.pyCheckArgs("hex",arguments,1,1);if(!Sk.misceval.isIndex(a))throw new Sk.builtin.TypeError("hex() argument can't be converted to hex");return Sk.builtin.int2str_(a,16,"0x")};Sk.builtin.oct=function(a){Sk.builtin.pyCheckArgs("oct",arguments,1,1);if(!Sk.misceval.isIndex(a))throw new Sk.builtin.TypeError("oct() argument can't be converted to hex");return Sk.builtin.int2str_(a,8,"0")};
Sk.builtin.bin=function(a){Sk.builtin.pyCheckArgs("bin",arguments,1,1);if(!Sk.misceval.isIndex(a))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(a)+"' object can't be interpreted as an index");return Sk.builtin.int2str_(a,2,"0b")};
Sk.builtin.dir=function(a){var b,c,d,e,f,g,h;Sk.builtin.pyCheckArgs("dir",arguments,1,1);h=function(a){var b=null;if(-1!=="__bases__ __mro__ __class__ __name__ GenericGetAttr GenericSetAttr GenericPythonGetAttr GenericPythonSetAttr pythonFunctions HashNotImplemented constructor".split(" ").indexOf(a))return null;-1!==a.indexOf("$")?b=Sk.builtin.dir.slotNameToRichName(a):"_"!==a.charAt(a.length-1)?b=a:"_"===a.charAt(0)&&(b=a);return b};g=[];b=Sk.abstr.lookupSpecial(a,"__dir__");if(null!=b){c=Sk.misceval.callsim(b,
a);if(!Sk.builtin.checkSequence(c))throw new Sk.builtin.TypeError("__dir__ must return sequence.");c=Sk.ffi.remapToJs(c);for(e=0;e<c.length;++e)g.push(new Sk.builtin.str(c[e]))}else{for(e in a.constructor.prototype)(f=h(e))&&g.push(new Sk.builtin.str(f));if(a.$d)if(a.$d.tp$iter)for(b=a.$d.tp$iter(),e=b.tp$iternext();void 0!==e;e=b.tp$iternext())f=new Sk.builtin.str(e),(f=h(f.v))&&g.push(new Sk.builtin.str(f));else for(f in a.$d)g.push(new Sk.builtin.str(f));d=a.tp$mro;!d&&a.ob$type&&(d=a.ob$type.tp$mro);
if(d)for(e=0;e<d.v.length;++e)for(c in b=d.v[e],b)b.hasOwnProperty(c)&&(f=h(c))&&g.push(new Sk.builtin.str(f))}g.sort(function(a,b){return(a.v>b.v)-(a.v<b.v)});return new Sk.builtin.list(g.filter(function(a,b,c){return a!==c[b+1]}))};Sk.builtin.dir.slotNameToRichName=function(a){};Sk.builtin.repr=function(a){Sk.builtin.pyCheckArgs("repr",arguments,1,1);return Sk.misceval.objectRepr(a)};
Sk.builtin.open=function(a,b,c){Sk.builtin.pyCheckArgs("open",arguments,1,3);void 0===b&&(b=new Sk.builtin.str("r"));if("r"!==b.v&&"rb"!==b.v)throw"todo; haven't implemented non-read opens";return new Sk.builtin.file(a,b,c)};
Sk.builtin.isinstance=function(a,b){var c,d;Sk.builtin.pyCheckArgs("isinstance",arguments,2,2);if(!(Sk.builtin.checkClass(b)||b instanceof Sk.builtin.tuple))throw new Sk.builtin.TypeError("isinstance() arg 2 must be a class, type, or tuple of classes and types");if(b===Sk.builtin.none.prototype.ob$type)return a instanceof Sk.builtin.none?Sk.builtin.bool.true$:Sk.builtin.bool.false$;if(a.ob$type===b)return Sk.builtin.bool.true$;if(b instanceof Sk.builtin.tuple){for(d=0;d<b.v.length;++d)if(Sk.misceval.isTrue(Sk.builtin.isinstance(a,
b.v[d])))return Sk.builtin.bool.true$;return Sk.builtin.bool.false$}if(a instanceof b)return Sk.builtin.bool.true$;c=function(a,b){var d,h;if(a===b)return Sk.builtin.bool.true$;if(void 0===a.$d)return Sk.builtin.bool.false$;h=a.$d.mp$subscript(Sk.builtin.type.basesStr_);for(d=0;d<h.v.length;++d)if(Sk.misceval.isTrue(c(h.v[d],b)))return Sk.builtin.bool.true$;return Sk.builtin.bool.false$};return c(a.ob$type,b)};
Sk.builtin.hash=function(a){Sk.builtin.pyCheckArgs("hash",arguments,1,1);if(a instanceof Object){if(Sk.builtin.checkNone(a.tp$hash))throw new Sk.builtin.TypeError(new Sk.builtin.str("unhashable type: '"+Sk.abstr.typeName(a)+"'"));if(void 0!==a.tp$hash){if(a.$savedHash_)return a.$savedHash_;a.$savedHash_=a.tp$hash();return a.$savedHash_}void 0===a.__id&&(Sk.builtin.hashCount+=1,a.__id=Sk.builtin.hashCount);return new Sk.builtin.int_(a.__id)}if("number"===typeof a||null===a||!0===a||!1===a)throw new Sk.builtin.TypeError("unsupported Javascript type");
return new Sk.builtin.str(typeof a+" "+String(a))};Sk.builtin.getattr=function(a,b,c){var d;Sk.builtin.pyCheckArgs("getattr",arguments,2,3);if(!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("attribute name must be string");d=a.tp$getattr(b.v);if(void 0===d){if(void 0!==c)return c;throw new Sk.builtin.AttributeError("'"+Sk.abstr.typeName(a)+"' object has no attribute '"+b.v+"'");}return d};
Sk.builtin.setattr=function(a,b,c){Sk.builtin.pyCheckArgs("setattr",arguments,3,3);if(!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("attribute name must be string");if(a.tp$setattr)a.tp$setattr(Sk.ffi.remapToJs(b),c);else throw new Sk.builtin.AttributeError("object has no attribute "+Sk.ffi.remapToJs(b));return Sk.builtin.none.none$};
Sk.builtin.raw_input=function(a){var b,c;a=a?a.v:"";a=Sk.inputfun(a);return a instanceof Promise?(c=new Sk.misceval.Suspension,c.resume=function(){return new Sk.builtin.str(b)},c.data={type:"Sk.promise",promise:a.then(function(a){return b=a},function(a){b="";return a})},c):new Sk.builtin.str(a)};Sk.builtin.input=Sk.builtin.raw_input;Sk.builtin.jseval=function(a){goog.global.eval(a)};Sk.builtin.jsmillis=function(){return(new Date).valueOf()};
Sk.builtin.superbi=function(){throw new Sk.builtin.NotImplementedError("super is not yet implemented, please report your use case as a github issue.");};Sk.builtin.eval_=function(){throw new Sk.builtin.NotImplementedError("eval is not yet implemented");};
Sk.builtin.map=function(a,b){var c,d,e,f,g,h;Sk.builtin.pyCheckArgs("map",arguments,2);if(2<arguments.length){h=[];g=Array.prototype.slice.apply(arguments).slice(1);for(f in g){if(!Sk.builtin.checkIterable(g[f]))throw c=parseInt(f,10)+2,new Sk.builtin.TypeError("argument "+c+" to map() must support iteration");g[f]=Sk.abstr.iter(g[f])}for(;;){e=[];d=0;for(f in g)c=g[f].tp$iternext(),void 0===c?(e.push(Sk.builtin.none.none$),d++):e.push(c);if(d!==g.length)h.push(e);else break}b=new Sk.builtin.list(h)}if(!Sk.builtin.checkIterable(b))throw new Sk.builtin.TypeError("'"+
Sk.abstr.typeName(b)+"' object is not iterable");e=[];c=Sk.abstr.iter(b);for(d=c.tp$iternext();void 0!==d;d=c.tp$iternext())a===Sk.builtin.none.none$?(d instanceof Array&&(d=new Sk.builtin.tuple(d)),e.push(d)):(d instanceof Array||(d=[d]),e.push(Sk.misceval.apply(a,void 0,void 0,void 0,d)));return new Sk.builtin.list(e)};
Sk.builtin.reduce=function(a,b,c){var d,e,f;Sk.builtin.pyCheckArgs("reduce",arguments,2,3);if(!Sk.builtin.checkIterable(b))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(b)+"' object is not iterable");f=Sk.abstr.iter(b);if(void 0===c&&(c=f.tp$iternext(),void 0===c))throw new Sk.builtin.TypeError("reduce() of empty sequence with no initial value");e=c;for(d=f.tp$iternext();void 0!==d;d=f.tp$iternext())e=Sk.misceval.callsim(a,e,d);return e};
Sk.builtin.filter=function(a,b){var c,d,e,f,g,h;Sk.builtin.pyCheckArgs("filter",arguments,2,2);if(!Sk.builtin.checkIterable(b))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(b)+"' object is not iterable");c=function(){return[]};h=function(a,b){a.push(b);return a};g=function(a){return new Sk.builtin.list(a)};b.__class__===Sk.builtin.str?(c=function(){return new Sk.builtin.str("")},h=function(a,b){return a.sq$concat(b)},g=function(a){return a}):b.__class__===Sk.builtin.tuple&&(g=function(a){return new Sk.builtin.tuple(a)});
f=c();d=Sk.abstr.iter(b);for(e=d.tp$iternext();void 0!==e;e=d.tp$iternext())c=a===Sk.builtin.none.none$?new Sk.builtin.bool(e):Sk.misceval.callsim(a,e),Sk.misceval.isTrue(c)&&(f=h(f,e));return g(f)};
Sk.builtin.hasattr=function(a,b){Sk.builtin.pyCheckArgs("hasattr",arguments,2,2);if(!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("hasattr(): attribute name must be string");if(a.tp$getattr)return a.tp$getattr(b.v)?Sk.builtin.bool.true$:Sk.builtin.bool.false$;throw new Sk.builtin.AttributeError("Object has no tp$getattr method");};
Sk.builtin.pow=function(a,b,c){var d,e;Sk.builtin.pyCheckArgs("pow",arguments,2,3);c instanceof Sk.builtin.none&&(c=void 0);if(Sk.builtin.checkComplex(a))return a.nb$power(b,c);d=Sk.builtin.asnum$(a);e=Sk.builtin.asnum$(b);Sk.builtin.asnum$(c);if(!Sk.builtin.checkNumber(a)||!Sk.builtin.checkNumber(b)){if(void 0===c)throw new Sk.builtin.TypeError("unsupported operand type(s) for pow(): '"+Sk.abstr.typeName(a)+"' and '"+Sk.abstr.typeName(b)+"'");throw new Sk.builtin.TypeError("unsupported operand type(s) for pow(): '"+
Sk.abstr.typeName(a)+"', '"+Sk.abstr.typeName(b)+"', '"+Sk.abstr.typeName(c)+"'");}if(0>d&&b instanceof Sk.builtin.float_)throw new Sk.builtin.ValueError("negative number cannot be raised to a fractional power");if(void 0===c){if(a instanceof Sk.builtin.float_||b instanceof Sk.builtin.float_||0>e)return new Sk.builtin.float_(Math.pow(d,e));d=new Sk.builtin.int_(d);e=new Sk.builtin.int_(e);d=d.nb$power(e);return a instanceof Sk.builtin.lng||b instanceof Sk.builtin.lng?new Sk.builtin.lng(d):d}if(!Sk.builtin.checkInt(a)||
!Sk.builtin.checkInt(b)||!Sk.builtin.checkInt(c))throw new Sk.builtin.TypeError("pow() 3rd argument not allowed unless all arguments are integers");if(0>e)throw new Sk.builtin.TypeError("pow() 2nd argument cannot be negative when 3rd argument specified");return a instanceof Sk.builtin.lng||(b instanceof Sk.builtin.lng||c instanceof Sk.builtin.lng)||Infinity===Math.pow(d,e)?(a=new Sk.builtin.lng(a),a.nb$power(b,c)):(new Sk.builtin.int_(Math.pow(d,e))).nb$remainder(c)};
Sk.builtin.quit=function(a){a=(new Sk.builtin.str(a)).v;throw new Sk.builtin.SystemExit(a);};
Sk.builtin.issubclass=function(a,b){var c,d;Sk.builtin.pyCheckArgs("issubclass",arguments,2,2);if(!(Sk.builtin.checkClass(b)||b instanceof Sk.builtin.tuple))throw new Sk.builtin.TypeError("issubclass() arg 2 must be a classinfo, type, or tuple of classes and types");d=function(a,b){var c,h;if(a===b)return!0;if(void 0!==a.$d&&a.$d.mp$subscript)h=a.$d.mp$subscript(Sk.builtin.type.basesStr_);else return!1;for(c=0;c<h.v.length;++c)if(d(h.v[c],b))return!0;return!1};if(Sk.builtin.checkClass(b))return a===
b?!0:d(a,b);if(b instanceof Sk.builtin.tuple){for(c=0;c<b.v.length;++c)if(Sk.builtin.issubclass(a,b.v[c]))return!0;return!1}};Sk.builtin.globals=function(){var a,b=new Sk.builtin.dict([]);for(a in Sk.globals)b.mp$ass_subscript(new Sk.builtin.str(a),Sk.globals[a]);return b};Sk.builtin.divmod=function(a,b){return Sk.abstr.numberBinOp(a,b,"DivMod")};Sk.builtin.format=function(a,b){Sk.builtin.pyCheckArgs("format",arguments,1,2);return Sk.abstr.objectFormat(a,b)};
Sk.builtin.bytearray=function(){throw new Sk.builtin.NotImplementedError("bytearray is not yet implemented");};Sk.builtin.callable=function(){throw new Sk.builtin.NotImplementedError("callable is not yet implemented");};Sk.builtin.delattr=function(){throw new Sk.builtin.NotImplementedError("delattr is not yet implemented");};Sk.builtin.execfile=function(){throw new Sk.builtin.NotImplementedError("execfile is not yet implemented");};
Sk.builtin.frozenset=function(){throw new Sk.builtin.NotImplementedError("frozenset is not yet implemented");};Sk.builtin.help=function(){throw new Sk.builtin.NotImplementedError("help is not yet implemented");};Sk.builtin.iter=function(){throw new Sk.builtin.NotImplementedError("iter is not yet implemented");};Sk.builtin.locals=function(){throw new Sk.builtin.NotImplementedError("locals is not yet implemented");};
Sk.builtin.memoryview=function(){throw new Sk.builtin.NotImplementedError("memoryview is not yet implemented");};Sk.builtin.next_=function(){throw new Sk.builtin.NotImplementedError("next is not yet implemented");};Sk.builtin.property=function(){throw new Sk.builtin.NotImplementedError("property is not yet implemented");};Sk.builtin.reload=function(){throw new Sk.builtin.NotImplementedError("reload is not yet implemented");};
Sk.builtin.reversed=function(){throw new Sk.builtin.NotImplementedError("reversed is not yet implemented");};Sk.builtin.unichr=function(){throw new Sk.builtin.NotImplementedError("unichr is not yet implemented");};Sk.builtin.vars=function(){throw new Sk.builtin.NotImplementedError("vars is not yet implemented");};Sk.builtin.xrange=Sk.builtin.range;Sk.builtin.apply_=function(){throw new Sk.builtin.NotImplementedError("apply is not yet implemented");};
Sk.builtin.buffer=function(){throw new Sk.builtin.NotImplementedError("buffer is not yet implemented");};Sk.builtin.coerce=function(){throw new Sk.builtin.NotImplementedError("coerce is not yet implemented");};Sk.builtin.intern=function(){throw new Sk.builtin.NotImplementedError("intern is not yet implemented");};Sk.builtin.BaseException=function(a){var b;if(!(this instanceof Sk.builtin.BaseException))return b=Object.create(Sk.builtin.BaseException.prototype),b.constructor.apply(b,arguments),b;a=Array.prototype.slice.call(arguments);for(b=0;b<a.length;++b)"string"===typeof a[b]&&(a[b]=new Sk.builtin.str(a[b]));this.args=new Sk.builtin.tuple(a);this.traceback=[];3<=this.args.sq$length()&&this.traceback.push({lineno:this.args.v[2],filename:this.args.v[1].v||"<unknown>"})};
Sk.abstr.setUpInheritance("BaseException",Sk.builtin.BaseException,Sk.builtin.object);Sk.builtin.BaseException.prototype.tp$str=function(){var a,b;b=""+this.tp$name;this.args&&(b+=": "+(0<this.args.v.length?this.args.v[0].v:""));b=0!==this.traceback.length?b+(" on line "+this.traceback[0].lineno):b+" at <unknown>";if(4<this.args.v.length){b+="\n"+this.args.v[4].v+"\n";for(a=0;a<this.args.v[3];++a)b+=" ";b+="^\n"}return new Sk.builtin.str(b)};Sk.builtin.BaseException.prototype.toString=function(){return this.tp$str().v};
goog.exportSymbol("Sk.builtin.BaseException",Sk.builtin.BaseException);Sk.builtin.Exception=function(a){var b;if(!(this instanceof Sk.builtin.Exception))return b=Object.create(Sk.builtin.Exception.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.BaseException.apply(this,arguments)};Sk.abstr.setUpInheritance("Exception",Sk.builtin.Exception,Sk.builtin.BaseException);goog.exportSymbol("Sk.builtin.Exception",Sk.builtin.Exception);
Sk.builtin.StandardError=function(a){var b;if(!(this instanceof Sk.builtin.StandardError))return b=Object.create(Sk.builtin.StandardError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.Exception.apply(this,arguments)};Sk.abstr.setUpInheritance("StandardError",Sk.builtin.StandardError,Sk.builtin.Exception);goog.exportSymbol("Sk.builtin.StandardError",Sk.builtin.StandardError);
Sk.builtin.AssertionError=function(a){var b;if(!(this instanceof Sk.builtin.AssertionError))return b=Object.create(Sk.builtin.AssertionError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("AssertionError",Sk.builtin.AssertionError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.AssertionError",Sk.builtin.AssertionError);
Sk.builtin.AttributeError=function(a){var b;if(!(this instanceof Sk.builtin.AttributeError))return b=Object.create(Sk.builtin.AttributeError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("AttributeError",Sk.builtin.AttributeError,Sk.builtin.StandardError);
Sk.builtin.ImportError=function(a){var b;if(!(this instanceof Sk.builtin.ImportError))return b=Object.create(Sk.builtin.ImportError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("ImportError",Sk.builtin.ImportError,Sk.builtin.StandardError);
Sk.builtin.IndentationError=function(a){var b;if(!(this instanceof Sk.builtin.IndentationError))return b=Object.create(Sk.builtin.IndentationError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("IndentationError",Sk.builtin.IndentationError,Sk.builtin.StandardError);
Sk.builtin.IndexError=function(a){var b;if(!(this instanceof Sk.builtin.IndexError))return b=Object.create(Sk.builtin.IndexError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("IndexError",Sk.builtin.IndexError,Sk.builtin.StandardError);
Sk.builtin.KeyError=function(a){var b;if(!(this instanceof Sk.builtin.KeyError))return b=Object.create(Sk.builtin.KeyError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("KeyError",Sk.builtin.KeyError,Sk.builtin.StandardError);
Sk.builtin.NameError=function(a){var b;if(!(this instanceof Sk.builtin.NameError))return b=Object.create(Sk.builtin.NameError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("NameError",Sk.builtin.NameError,Sk.builtin.StandardError);
Sk.builtin.UnboundLocalError=function(a){var b;if(!(this instanceof Sk.builtin.UnboundLocalError))return b=Object.create(Sk.builtin.UnboundLocalError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("UnboundLocalError",Sk.builtin.UnboundLocalError,Sk.builtin.StandardError);
Sk.builtin.OverflowError=function(a){var b;if(!(this instanceof Sk.builtin.OverflowError))return b=Object.create(Sk.builtin.OverflowError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("OverflowError",Sk.builtin.OverflowError,Sk.builtin.StandardError);
Sk.builtin.ParseError=function(a){var b;if(!(this instanceof Sk.builtin.ParseError))return b=Object.create(Sk.builtin.ParseError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("ParseError",Sk.builtin.ParseError,Sk.builtin.StandardError);
Sk.builtin.RuntimeError=function(a){var b;if(!(this instanceof Sk.builtin.RuntimeError))return b=Object.create(Sk.builtin.RuntimeError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("RuntimeError",Sk.builtin.RuntimeError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.RuntimeError",Sk.builtin.RuntimeError);
Sk.builtin.SuspensionError=function(a){var b;if(!(this instanceof Sk.builtin.SuspensionError))return b=Object.create(Sk.builtin.SuspensionError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("SuspensionError",Sk.builtin.SuspensionError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.SuspensionError",Sk.builtin.SuspensionError);
Sk.builtin.SystemExit=function(a){var b;if(!(this instanceof Sk.builtin.SystemExit))return b=Object.create(Sk.builtin.SystemExit.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.BaseException.apply(this,arguments)};Sk.abstr.setUpInheritance("SystemExit",Sk.builtin.SystemExit,Sk.builtin.BaseException);goog.exportSymbol("Sk.builtin.SystemExit",Sk.builtin.SystemExit);
Sk.builtin.SyntaxError=function(a){var b;if(!(this instanceof Sk.builtin.SyntaxError))return b=Object.create(Sk.builtin.SyntaxError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("SyntaxError",Sk.builtin.SyntaxError,Sk.builtin.StandardError);
Sk.builtin.TokenError=function(a){var b;if(!(this instanceof Sk.builtin.TokenError))return b=Object.create(Sk.builtin.TokenError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("TokenError",Sk.builtin.TokenError,Sk.builtin.StandardError);
Sk.builtin.TypeError=function(a){var b;if(!(this instanceof Sk.builtin.TypeError))return b=Object.create(Sk.builtin.TypeError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("TypeError",Sk.builtin.TypeError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.TypeError",Sk.builtin.TypeError);
Sk.builtin.ValueError=function(a){var b;if(!(this instanceof Sk.builtin.ValueError))return b=Object.create(Sk.builtin.ValueError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("ValueError",Sk.builtin.ValueError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.ValueError",Sk.builtin.ValueError);
Sk.builtin.ZeroDivisionError=function(a){var b;if(!(this instanceof Sk.builtin.ZeroDivisionError))return b=Object.create(Sk.builtin.ZeroDivisionError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("ZeroDivisionError",Sk.builtin.ZeroDivisionError,Sk.builtin.StandardError);
Sk.builtin.TimeLimitError=function(a){var b;if(!(this instanceof Sk.builtin.TimeLimitError))return b=Object.create(Sk.builtin.TimeLimitError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("TimeLimitError",Sk.builtin.TimeLimitError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.TimeLimitError",Sk.builtin.TimeLimitError);
Sk.builtin.IOError=function(a){var b;if(!(this instanceof Sk.builtin.IOError))return b=Object.create(Sk.builtin.IOError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("IOError",Sk.builtin.IOError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.IOError",Sk.builtin.IOError);
Sk.builtin.NotImplementedError=function(a){var b;if(!(this instanceof Sk.builtin.NotImplementedError))return b=Object.create(Sk.builtin.NotImplementedError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("NotImplementedError",Sk.builtin.NotImplementedError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.NotImplementedError",Sk.builtin.NotImplementedError);
Sk.builtin.NegativePowerError=function(a){var b;if(!(this instanceof Sk.builtin.NegativePowerError))return b=Object.create(Sk.builtin.NegativePowerError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("NegativePowerError",Sk.builtin.NegativePowerError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.NegativePowerError",Sk.builtin.NegativePowerError);
Sk.builtin.ExternalError=function(a,b){var c;if(!(this instanceof Sk.builtin.ExternalError))return c=Object.create(Sk.builtin.ExternalError.prototype),c.constructor.apply(c,arguments),c;b=Array.prototype.slice.call(arguments);this.nativeError=b[0];b[0]instanceof Sk.builtin.str||(b[0]=""+b[0]);Sk.builtin.StandardError.apply(this,b)};Sk.abstr.setUpInheritance("ExternalError",Sk.builtin.ExternalError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.ExternalError",Sk.builtin.ExternalError);
Sk.builtin.OperationError=function(a){var b;if(!(this instanceof Sk.builtin.OperationError))return b=Object.create(Sk.builtin.OperationError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("OperationError",Sk.builtin.OperationError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.OperationError",Sk.builtin.OperationError);
Sk.builtin.SystemError=function(a){var b;if(!(this instanceof Sk.builtin.SystemError))return b=Object.create(Sk.builtin.SystemError.prototype),b.constructor.apply(b,arguments),b;Sk.builtin.StandardError.apply(this,arguments)};Sk.abstr.setUpInheritance("SystemError",Sk.builtin.SystemError,Sk.builtin.StandardError);goog.exportSymbol("Sk.builtin.SystemError",Sk.builtin.SystemError);goog.exportSymbol("Sk",Sk);Sk.nativejs={FN_ARGS:/^function\s*[^\(]*\(\s*([^\)]*)\)/m,FN_ARG_SPLIT:/,/,FN_ARG:/^\s*(_?)(\S+?)\1\s*$/,STRIP_COMMENTS:/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,formalParameterList:function(a){var b,c,d=[];a=a.toString().replace(this.STRIP_COMMENTS,"").match(this.FN_ARGS)[1].split(this.FN_ARG_SPLIT);for(b in a)c=a[b],c.replace(this.FN_ARG,function(a,b,c){d.push(c)});return d},func:function(a){a.co_name=new Sk.builtin.str(a.name);a.co_varnames=Sk.nativejs.formalParameterList(a);return new Sk.builtin.func(a)},
func_nokw:function(a){a.co_name=new Sk.builtin.str(a.name);a.co_varnames=Sk.nativejs.formalParameterList(a);a.no_kw=!0;return new Sk.builtin.func(a)}};goog.exportSymbol("Sk.nativejs.func",Sk.nativejs.func);goog.exportSymbol("Sk.nativejs.func_nokw",Sk.nativejs.func_nokw);Sk.builtin.method=function(a,b){this.im_func=a;this.im_self=b};goog.exportSymbol("Sk.builtin.method",Sk.builtin.method);
Sk.builtin.method.prototype.tp$call=function(a,b){var c,d,e,f,g,h,k;goog.asserts.assert(this.im_self,"should just be a function, not a method since there's no self?");goog.asserts.assert(this.im_func instanceof Sk.builtin.func);a.unshift(this.im_self);k=this.im_func.func_code.co_kwargs;h=[];if(this.im_func.func_code.no_kw)throw c=this.im_func.func_code.co_name&&this.im_func.func_code.co_name.v||"<native JS>",new Sk.builtin.TypeError(c+"() takes no keyword arguments");if(b)for(g=b.length,e=(f=this.im_func.func_code.co_varnames)&&
f.length,d=0;d<g;d+=2){for(c=0;c<e&&b[d]!==f[c];++c);if(f&&c!==e)a[c]=b[d+1];else if(k)h.push(new Sk.builtin.str(b[d])),h.push(b[d+1]);else throw c=this.im_func.func_code&&this.im_func.func_code.co_name&&this.im_func.func_code.co_name.v||"<native JS>",new Sk.builtin.TypeError(c+"() got an unexpected keyword argument '"+b[d]+"'");}k&&a.unshift(h);return this.im_func.func_code.apply(this.im_func.func_globals,a)};
Sk.builtin.method.prototype.$r=function(){return new Sk.builtin.str("<bound method "+this.im_self.ob$type.tp$name+"."+(this.im_func.func_code&&this.im_func.func_code.co_name&&this.im_func.func_code.co_name.v||"<native JS>")+" of "+this.im_self.$r().v+">")};Sk.misceval={};Sk.misceval.Suspension=function(a,b,c){this.isSuspension=!0;void 0!==a&&void 0!==b&&(this.resume=function(){return a(b.resume())});this.child=b;this.optional=void 0!==b&&b.optional;this.data=void 0===c&&void 0!==b?b.data:c};goog.exportSymbol("Sk.misceval.Suspension",Sk.misceval.Suspension);
Sk.misceval.retryOptionalSuspensionOrThrow=function(a,b){for(;a instanceof Sk.misceval.Suspension;){if(!a.optional)throw new Sk.builtin.SuspensionError(b||"Cannot call a function that blocks or suspends here");a=a.resume()}return a};goog.exportSymbol("Sk.misceval.retryOptionalSuspensionOrThrow",Sk.misceval.retryOptionalSuspensionOrThrow);Sk.misceval.isIndex=function(a){return Sk.builtin.checkInt(a)||Sk.abstr.lookupSpecial(a,"__index__")?!0:!1};goog.exportSymbol("Sk.misceval.isIndex",Sk.misceval.isIndex);
Sk.misceval.asIndex=function(a){var b;if(Sk.misceval.isIndex(a)&&null!==a){if(!0===a)return 1;if(!1===a)return 0;if("number"===typeof a)return a;if(a.constructor===Sk.builtin.int_)return a.v;if(a.constructor===Sk.builtin.lng)return a.tp$index();if(a.constructor===Sk.builtin.bool)return Sk.builtin.asnum$(a);if(b=Sk.abstr.lookupSpecial(a,"__index__")){a=Sk.misceval.callsim(b,a);if(!Sk.builtin.checkInt(a))throw new Sk.builtin.TypeError("__index__ returned non-(int,long) (type "+Sk.abstr.typeName(a)+
")");return Sk.builtin.asnum$(a)}goog.asserts.fail("todo asIndex;")}};Sk.misceval.applySlice=function(a,b,c,d){return a.sq$slice&&Sk.misceval.isIndex(b)&&Sk.misceval.isIndex(c)?(b=Sk.misceval.asIndex(b),void 0===b&&(b=0),c=Sk.misceval.asIndex(c),void 0===c&&(c=1E100),Sk.abstr.sequenceGetSlice(a,b,c)):Sk.abstr.objectGetItem(a,new Sk.builtin.slice(b,c,null),d)};goog.exportSymbol("Sk.misceval.applySlice",Sk.misceval.applySlice);
Sk.misceval.assignSlice=function(a,b,c,d,e){if(a.sq$ass_slice&&Sk.misceval.isIndex(b)&&Sk.misceval.isIndex(c))e=Sk.misceval.asIndex(b)||0,c=Sk.misceval.asIndex(c)||1E100,null===d?Sk.abstr.sequenceDelSlice(a,e,c):Sk.abstr.sequenceSetSlice(a,e,c,d);else return c=new Sk.builtin.slice(b,c),null===d?Sk.abstr.objectDelItem(a,c):Sk.abstr.objectSetItem(a,c,d,e)};goog.exportSymbol("Sk.misceval.assignSlice",Sk.misceval.assignSlice);
Sk.misceval.arrayFromArguments=function(a){var b,c;if(1!=a.length)return a;b=a[0];b instanceof Sk.builtin.set?b=b.tp$iter().$obj:b instanceof Sk.builtin.dict&&(b=Sk.builtin.dict.prototype.keys.func_code(b));if(b instanceof Sk.builtin.list||b instanceof Sk.builtin.tuple)return b.v;if(Sk.builtin.checkIterable(b)){a=[];b=Sk.abstr.iter(b);for(c=b.tp$iternext();void 0!==c;c=b.tp$iternext())a.push(c);return a}throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(b)+"' object is not iterable");};
goog.exportSymbol("Sk.misceval.arrayFromArguments",Sk.misceval.arrayFromArguments);Sk.misceval.swappedOp_={Eq:"Eq",NotEq:"NotEq",Lt:"GtE",LtE:"Gt",Gt:"LtE",GtE:"Lt",Is:"IsNot",IsNot:"Is",In_:"NotIn",NotIn:"In_"};
Sk.misceval.richCompareBool=function(a,b,c){var d,e,f,g,h,k,l;goog.asserts.assert(null!==a&&void 0!==a,"passed null or undefined parameter to Sk.misceval.richCompareBool");goog.asserts.assert(null!==b&&void 0!==b,"passed null or undefined parameter to Sk.misceval.richCompareBool");h=new Sk.builtin.type(a);f=new Sk.builtin.type(b);if(h!==f&&("GtE"===c||"Gt"===c||"LtE"===c||"Lt"===c)){l=[Sk.builtin.float_.prototype.ob$type,Sk.builtin.int_.prototype.ob$type,Sk.builtin.lng.prototype.ob$type,Sk.builtin.bool.prototype.ob$type];
k=[Sk.builtin.dict.prototype.ob$type,Sk.builtin.enumerate.prototype.ob$type,Sk.builtin.list.prototype.ob$type,Sk.builtin.str.prototype.ob$type,Sk.builtin.tuple.prototype.ob$type];g=l.indexOf(h);e=k.indexOf(h);l=l.indexOf(f);k=k.indexOf(f);if(h===Sk.builtin.none.prototype.ob$type)switch(c){case "Lt":return!0;case "LtE":return!0;case "Gt":return!1;case "GtE":return!1}if(f===Sk.builtin.none.prototype.ob$type)switch(c){case "Lt":return!1;case "LtE":return!1;case "Gt":return!0;case "GtE":return!0}if(-1!==
g&&-1!==k)switch(c){case "Lt":return!0;case "LtE":return!0;case "Gt":return!1;case "GtE":return!1}if(-1!==e&&-1!==l)switch(c){case "Lt":return!1;case "LtE":return!1;case "Gt":return!0;case "GtE":return!0}if(-1!==e&&-1!==k)switch(c){case "Lt":return e<k;case "LtE":return e<=k;case "Gt":return e>k;case "GtE":return e>=k}}if("Is"===c)return a instanceof Sk.builtin.int_&&b instanceof Sk.builtin.int_?0===a.numberCompare(b):a instanceof Sk.builtin.float_&&b instanceof Sk.builtin.float_?0===a.numberCompare(b):
a instanceof Sk.builtin.lng&&b instanceof Sk.builtin.lng?0===a.longCompare(b):a===b;if("IsNot"===c)return a instanceof Sk.builtin.int_&&b instanceof Sk.builtin.int_?0!==a.numberCompare(b):a instanceof Sk.builtin.float_&&b instanceof Sk.builtin.float_?0!==a.numberCompare(b):a instanceof Sk.builtin.lng&&b instanceof Sk.builtin.lng?0!==a.longCompare(b):a!==b;if("In"===c)return Sk.misceval.isTrue(Sk.abstr.sequenceContains(b,a));if("NotIn"===c)return!Sk.misceval.isTrue(Sk.abstr.sequenceContains(b,a));
f={Eq:"ob$eq",NotEq:"ob$ne",Gt:"ob$gt",GtE:"ob$ge",Lt:"ob$lt",LtE:"ob$le"};g=f[c];if((e=a.constructor.prototype.hasOwnProperty(g))&&(d=a[g](b))!==Sk.builtin.NotImplemented.NotImplemented$)return Sk.misceval.isTrue(d);f=f[Sk.misceval.swappedOp_[c]];if((g=b.constructor.prototype.hasOwnProperty(f))&&(d=b[f](a))!==Sk.builtin.NotImplemented.NotImplemented$)return Sk.misceval.isTrue(d);if(a.tp$richcompare&&void 0!==(d=a.tp$richcompare(b,c))&&d!=Sk.builtin.NotImplemented.NotImplemented$||b.tp$richcompare&&
void 0!==(d=b.tp$richcompare(a,Sk.misceval.swappedOp_[c]))&&d!=Sk.builtin.NotImplemented.NotImplemented$)return Sk.misceval.isTrue(d);h={Eq:"__eq__",NotEq:"__ne__",Gt:"__gt__",GtE:"__ge__",Lt:"__lt__",LtE:"__le__"};if((f=Sk.abstr.lookupSpecial(a,h[c]))&&!e&&(d=Sk.misceval.callsim(f,a,b),d!=Sk.builtin.NotImplemented.NotImplemented$)||(e=Sk.abstr.lookupSpecial(b,h[Sk.misceval.swappedOp_[c]]))&&!g&&(d=Sk.misceval.callsim(e,b,a),d!=Sk.builtin.NotImplemented.NotImplemented$))return Sk.misceval.isTrue(d);
if(e=Sk.abstr.lookupSpecial(a,"__cmp__"))try{d=Sk.misceval.callsim(e,a,b);if(Sk.builtin.checkNumber(d)){d=Sk.builtin.asnum$(d);if("Eq"===c)return 0===d;if("NotEq"===c)return 0!==d;if("Lt"===c)return 0>d;if("Gt"===c)return 0<d;if("LtE"===c)return 0>=d;if("GtE"===c)return 0<=d}if(d!==Sk.builtin.NotImplemented.NotImplemented$)throw new Sk.builtin.TypeError("comparison did not return an int");}catch(m){throw new Sk.builtin.TypeError("comparison did not return an int");}if(e=Sk.abstr.lookupSpecial(b,"__cmp__"))try{d=
Sk.misceval.callsim(e,b,a);if(Sk.builtin.checkNumber(d)){d=Sk.builtin.asnum$(d);if("Eq"===c)return 0===d;if("NotEq"===c)return 0!==d;if("Lt"===c)return 0<d;if("Gt"===c)return 0>d;if("LtE"===c)return 0<=d;if("GtE"===c)return 0>=d}if(d!==Sk.builtin.NotImplemented.NotImplemented$)throw new Sk.builtin.TypeError("comparison did not return an int");}catch(q){throw new Sk.builtin.TypeError("comparison did not return an int");}if(a instanceof Sk.builtin.none&&b instanceof Sk.builtin.none||a instanceof Sk.builtin.bool&&
b instanceof Sk.builtin.bool){if("Eq"===c)return a.v===b.v;if("NotEq"===c)return a.v!==b.v;if("Gt"===c)return a.v>b.v;if("GtE"===c)return a.v>=b.v;if("Lt"===c)return a.v<b.v;if("LtE"===c)return a.v<=b.v}if("Eq"===c)return a instanceof Sk.builtin.str&&b instanceof Sk.builtin.str?a.v===b.v:a===b;if("NotEq"===c)return a instanceof Sk.builtin.str&&b instanceof Sk.builtin.str?a.v!==b.v:a!==b;a=Sk.abstr.typeName(a);b=Sk.abstr.typeName(b);throw new Sk.builtin.ValueError("don't know how to compare '"+a+"' and '"+
b+"'");};goog.exportSymbol("Sk.misceval.richCompareBool",Sk.misceval.richCompareBool);
Sk.misceval.objectRepr=function(a){goog.asserts.assert(void 0!==a,"trying to repr undefined");return null===a||a instanceof Sk.builtin.none?new Sk.builtin.str("None"):!0===a?new Sk.builtin.str("True"):!1===a?new Sk.builtin.str("False"):"number"===typeof a?new Sk.builtin.str(""+a):a.$r?a.constructor===Sk.builtin.float_?Infinity===a.v?new Sk.builtin.str("inf"):-Infinity===a.v?new Sk.builtin.str("-inf"):a.$r():a.$r():a.tp$name?new Sk.builtin.str("<"+a.tp$name+" object>"):new Sk.builtin.str("<unknown>")};
goog.exportSymbol("Sk.misceval.objectRepr",Sk.misceval.objectRepr);Sk.misceval.opAllowsEquality=function(a){switch(a){case "LtE":case "Eq":case "GtE":return!0}return!1};goog.exportSymbol("Sk.misceval.opAllowsEquality",Sk.misceval.opAllowsEquality);
Sk.misceval.isTrue=function(a){if(!0===a)return!0;if(!1===a||null===a||a.constructor===Sk.builtin.none||a.constructor===Sk.builtin.NotImplemented)return!1;if(a.constructor===Sk.builtin.bool)return a.v;if("number"===typeof a)return 0!==a;if(a instanceof Sk.builtin.lng)return a.nb$nonzero();if(a.constructor===Sk.builtin.int_||a.constructor===Sk.builtin.float_)return 0!==a.v;if(a.__nonzero__){a=Sk.misceval.callsim(a.__nonzero__,a);if(!Sk.builtin.checkInt(a))throw new Sk.builtin.TypeError("__nonzero__ should return an int");
return 0!==Sk.builtin.asnum$(a)}if(a.__len__){a=Sk.misceval.callsim(a.__len__,a);if(!Sk.builtin.checkInt(a))throw new Sk.builtin.TypeError("__len__ should return an int");return 0!==Sk.builtin.asnum$(a)}return a.mp$length?0!==Sk.builtin.asnum$(a.mp$length()):a.sq$length?0!==Sk.builtin.asnum$(a.sq$length()):!0};goog.exportSymbol("Sk.misceval.isTrue",Sk.misceval.isTrue);Sk.misceval.softspace_=!1;
Sk.misceval.print_=function(a){var b;Sk.misceval.softspace_&&("\n"!==a&&Sk.output(" "),Sk.misceval.softspace_=!1);b=new Sk.builtin.str(a);Sk.output(b.v);a=function(a){return"\n"===a||"\t"===a||"\r"===a};0!==b.v.length&&a(b.v[b.v.length-1])&&" "!==b.v[b.v.length-1]||(Sk.misceval.softspace_=!0)};goog.exportSymbol("Sk.misceval.print_",Sk.misceval.print_);
Sk.misceval.loadname=function(a,b){var c;c=b[a];if(void 0!==c)return c;c=Sk.builtins[a];if(void 0!==c)return c;a=a.replace("_$rw$","");a=a.replace("_$rn$","");throw new Sk.builtin.NameError("name '"+a+"' is not defined");};goog.exportSymbol("Sk.misceval.loadname",Sk.misceval.loadname);Sk.misceval.call=function(a,b,c,d,e){e=Array.prototype.slice.call(arguments,4);return Sk.misceval.apply(a,b,c,d,e)};goog.exportSymbol("Sk.misceval.call",Sk.misceval.call);
Sk.misceval.callAsync=function(a,b,c,d,e,f){f=Array.prototype.slice.call(arguments,5);return Sk.misceval.applyAsync(a,b,c,d,e,f)};goog.exportSymbol("Sk.misceval.callAsync",Sk.misceval.callAsync);Sk.misceval.callOrSuspend=function(a,b,c,d,e){e=Array.prototype.slice.call(arguments,4);return Sk.misceval.applyOrSuspend(a,b,c,d,e)};goog.exportSymbol("Sk.misceval.callOrSuspend",Sk.misceval.callOrSuspend);
Sk.misceval.callsim=function(a,b){b=Array.prototype.slice.call(arguments,1);return Sk.misceval.apply(a,void 0,void 0,void 0,b)};goog.exportSymbol("Sk.misceval.callsim",Sk.misceval.callsim);Sk.misceval.callsimAsync=function(a,b,c){c=Array.prototype.slice.call(arguments,2);return Sk.misceval.applyAsync(a,b,void 0,void 0,void 0,c)};goog.exportSymbol("Sk.misceval.callsimAsync",Sk.misceval.callsimAsync);
Sk.misceval.callsimOrSuspend=function(a,b){b=Array.prototype.slice.call(arguments,1);return Sk.misceval.applyOrSuspend(a,void 0,void 0,void 0,b)};goog.exportSymbol("Sk.misceval.callsimOrSuspend",Sk.misceval.callsimOrSuspend);Sk.misceval.apply=function(a,b,c,d,e){a=Sk.misceval.applyOrSuspend(a,b,c,d,e);return a instanceof Sk.misceval.Suspension?Sk.misceval.retryOptionalSuspensionOrThrow(a):a};goog.exportSymbol("Sk.misceval.apply",Sk.misceval.apply);
Sk.misceval.asyncToPromise=function(a,b){return new Promise(function(c,d){try{(function g(a){try{for(var e=function(){g(a.resume())},l=function(b){try{a.data.result=b,e()}catch(c){d(c)}},m=function(b){try{a.data.error=b,e()}catch(c){d(c)}};a instanceof Sk.misceval.Suspension;){var q=b&&(b[a.data.type]||b["*"]);if(q){var n=q(a);if(n){n.then(g,d);return}}if("Sk.promise"==a.data.type){a.data.promise.then(l,m);return}if("Sk.yield"==a.data.type&&"function"===typeof setTimeout){setTimeout(e,0);return}if(a.optional)a=
a.resume();else throw new Sk.builtin.SuspensionError("Unhandled non-optional suspension of type '"+a.data.type+"'");}c(a)}catch(r){d(r)}})(a())}catch(e){d(e)}})};goog.exportSymbol("Sk.misceval.asyncToPromise",Sk.misceval.asyncToPromise);Sk.misceval.applyAsync=function(a,b,c,d,e,f){return Sk.misceval.asyncToPromise(function(){return Sk.misceval.applyOrSuspend(b,c,d,e,f)},a)};goog.exportSymbol("Sk.misceval.applyAsync",Sk.misceval.applyAsync);
Sk.misceval.chain=function(a,b){var c=arguments,d=1;return function f(a){for(;d<c.length;){if(a instanceof Sk.misceval.Suspension)return new Sk.misceval.Suspension(f,a);a=c[d](a);d++}return a}(a)};goog.exportSymbol("Sk.misceval.chain",Sk.misceval.chain);
Sk.misceval.applyOrSuspend=function(a,b,c,d,e){var f,g;if(null===a||a instanceof Sk.builtin.none)throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(a)+"' object is not callable");if("function"===typeof a){if(a.sk$klass)return a.apply(null,[b,c,d,e,!0]);if(c)for(g=c.tp$iter(),c=g.tp$iternext();void 0!==c;c=g.tp$iternext())e.push(c);b&&goog.asserts.fail("kwdict not implemented;");if(void 0!==d&&0<d.length){if(!a.co_varnames)throw new Sk.builtin.ValueError("Keyword arguments are not supported by this function");
g=a.co_numargs-a.co_varnames.length;f=e.length-g;e=e.concat(a.$defaults.slice(f));for(c=0;c<d.length;c+=2){b=a.co_varnames.indexOf(d[c]);if(-1===b)throw new Sk.builtin.TypeError("'"+d[c]+"' is an invalid keyword argument for this function");if(b<f)throw new Sk.builtin.TypeError("Argument given by name ('"+d[c]+"') and position ("+(b+g+1)+")");e[b+g]=d[c+1]}}return a.apply(null,e)}f=a.tp$call;if(void 0!==f){if(c)for(g=c.tp$iter(),c=g.tp$iternext();void 0!==c;c=g.tp$iternext())e.push(c);b&&goog.asserts.fail("kwdict not implemented;");
return f.call(a,e,d,b)}f=a.__call__;if(void 0!==f)return e.unshift(a),Sk.misceval.apply(f,d,e,b,c);throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(a)+"' object is not callable");};goog.exportSymbol("Sk.misceval.applyOrSuspend",Sk.misceval.applyOrSuspend);
Sk.misceval.buildClass=function(a,b,c,d){var e=Sk.builtin.type,f={};b(a,f,[]);f.__module__=a.__name__;a=new Sk.builtin.str(c);d=new Sk.builtin.tuple(d);b=[];for(var g in f)f.hasOwnProperty(g)&&(b.push(new Sk.builtin.str(g)),b.push(f[g]));b=new Sk.builtin.dict(b);return Sk.misceval.callsim(e,a,d,b)};goog.exportSymbol("Sk.misceval.buildClass",Sk.misceval.buildClass);Sk.builtin.seqtype=function(){throw new Sk.builtin.ExternalError("Cannot instantiate abstract Sk.builtin.seqtype class");};Sk.abstr.setUpInheritance("SequenceType",Sk.builtin.seqtype,Sk.builtin.object);Sk.builtin.seqtype.sk$abstract=!0;Sk.builtin.seqtype.prototype.__len__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__len__",arguments,0,0,!1,!0);return new Sk.builtin.int_(a.sq$length())});
Sk.builtin.seqtype.prototype.__iter__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__iter__",arguments,0,0,!1,!0);return a.tp$iter()});Sk.builtin.seqtype.prototype.__contains__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__contains__",arguments,1,1,!1,!0);return a.sq$contains(b)?Sk.builtin.bool.true$:Sk.builtin.bool.false$});Sk.builtin.seqtype.prototype.__getitem__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__getitem__",arguments,1,1,!1,!0);return a.mp$subscript(b)});
Sk.builtin.seqtype.prototype.__add__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__add__",arguments,1,1,!1,!0);return a.sq$concat(b)});Sk.builtin.seqtype.prototype.__mul__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__mul__",arguments,1,1,!1,!0);if(!Sk.misceval.isIndex(b))throw new Sk.builtin.TypeError("can't multiply sequence by non-int of type '"+Sk.abstr.typeName(b)+"'");return a.sq$repeat(b)});
Sk.builtin.seqtype.prototype.__rmul__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__rmul__",arguments,1,1,!1,!0);return a.sq$repeat(b)});Sk.builtin.list=function(a,b){var c,d,e;if(this instanceof Sk.builtin.list)b=b||!1;else return new Sk.builtin.list(a,b||!0);this.__class__=Sk.builtin.list;if(void 0===a)c=[];else if("[object Array]"===Object.prototype.toString.apply(a))c=a;else{if(Sk.builtin.checkIterable(a))return c=[],d=Sk.abstr.iter(a),e=this,function g(a){for(;;){if(a instanceof Sk.misceval.Suspension)return new Sk.misceval.Suspension(g,a);if(void 0===a)return e.v=c,e;c.push(a);a=d.tp$iternext(b)}}(d.tp$iternext(b));throw new Sk.builtin.TypeError("expecting Array or iterable");
}this.v=this.v=c;return this};Sk.abstr.setUpInheritance("list",Sk.builtin.list,Sk.builtin.seqtype);Sk.abstr.markUnhashable(Sk.builtin.list);Sk.builtin.list.prototype.list_iter_=function(){var a={tp$iter:function(){return a},$obj:this,$index:0,tp$iternext:function(){return a.$index>=a.$obj.v.length?void 0:a.$obj.v[a.$index++]},tp$name:"list_iterator"};return a};
Sk.builtin.list.prototype.list_concat_=function(a){var b,c;if(!a.__class__||a.__class__!=Sk.builtin.list)throw new Sk.builtin.TypeError("can only concatenate list to list");c=this.v.slice();for(b=0;b<a.v.length;++b)c.push(a.v[b]);return new Sk.builtin.list(c,!1)};
Sk.builtin.list.prototype.list_extend_=function(a){var b,c;if(!Sk.builtin.checkIterable(a))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(a)+"' object is not iterable");if(this==a){c=[];a=Sk.abstr.iter(a);for(b=a.tp$iternext();void 0!==b;b=a.tp$iternext())c.push(b);this.v.push.apply(this.v,c)}else for(a=Sk.abstr.iter(a),b=a.tp$iternext();void 0!==b;b=a.tp$iternext())this.v.push(b);return this};
Sk.builtin.list.prototype.list_del_item_=function(a){a=Sk.builtin.asnum$(a);if(0>a||a>=this.v.length)throw new Sk.builtin.IndexError("list assignment index out of range");this.list_del_slice_(a,a+1)};Sk.builtin.list.prototype.list_del_slice_=function(a,b){var c;a=Sk.builtin.asnum$(a);b=Sk.builtin.asnum$(b);c=[];c.unshift(b-a);c.unshift(a);this.v.splice.apply(this.v,c)};
Sk.builtin.list.prototype.list_ass_item_=function(a,b){a=Sk.builtin.asnum$(a);if(0>a||a>=this.v.length)throw new Sk.builtin.IndexError("list assignment index out of range");this.v[a]=b};Sk.builtin.list.prototype.list_ass_slice_=function(a,b,c){a=Sk.builtin.asnum$(a);b=Sk.builtin.asnum$(b);if(Sk.builtin.checkIterable(c))c=(new Sk.builtin.list(c,!1)).v.slice(0);else throw new Sk.builtin.TypeError("can only assign an iterable");c.unshift(b-a);c.unshift(a);this.v.splice.apply(this.v,c)};
Sk.builtin.list.prototype.$r=function(){var a,b,c=[];a=Sk.abstr.iter(this);for(b=a.tp$iternext();void 0!==b;b=a.tp$iternext())b===this?c.push("[...]"):c.push(Sk.misceval.objectRepr(b).v);return new Sk.builtin.str("["+c.join(", ")+"]")};
Sk.builtin.list.prototype.tp$richcompare=function(a,b){var c,d,e,f,g;if(this===a&&Sk.misceval.opAllowsEquality(b))return!0;if(!a.__class__||a.__class__!=Sk.builtin.list)return"Eq"===b?!1:"NotEq"===b?!0:!1;g=this.v;a=a.v;f=g.length;e=a.length;for(d=0;d<f&&d<e&&(c=Sk.misceval.richCompareBool(g[d],a[d],"Eq"),c);++d);if(d>=f||d>=e)switch(b){case "Lt":return f<e;case "LtE":return f<=e;case "Eq":return f===e;case "NotEq":return f!==e;case "Gt":return f>e;case "GtE":return f>=e;default:goog.asserts.fail()}return"Eq"===
b?!1:"NotEq"===b?!0:Sk.misceval.richCompareBool(g[d],a[d],b)};Sk.builtin.list.prototype.tp$iter=Sk.builtin.list.prototype.list_iter_;Sk.builtin.list.prototype.sq$length=function(){return this.v.length};Sk.builtin.list.prototype.sq$concat=Sk.builtin.list.prototype.list_concat_;Sk.builtin.list.prototype.nb$add=Sk.builtin.list.prototype.list_concat_;Sk.builtin.list.prototype.nb$inplace_add=Sk.builtin.list.prototype.list_extend_;
Sk.builtin.list.prototype.sq$repeat=function(a){var b,c,d;if(!Sk.misceval.isIndex(a))throw new Sk.builtin.TypeError("can't multiply sequence by non-int of type '"+Sk.abstr.typeName(a)+"'");a=Sk.misceval.asIndex(a);d=[];for(c=0;c<a;++c)for(b=0;b<this.v.length;++b)d.push(this.v[b]);return new Sk.builtin.list(d,!1)};Sk.builtin.list.prototype.nb$multiply=Sk.builtin.list.prototype.sq$repeat;
Sk.builtin.list.prototype.nb$inplace_multiply=function(a){var b,c,d;if(!Sk.misceval.isIndex(a))throw new Sk.builtin.TypeError("can't multiply sequence by non-int of type '"+Sk.abstr.typeName(a)+"'");a=Sk.misceval.asIndex(a);d=this.v.length;for(c=1;c<a;++c)for(b=0;b<d;++b)this.v.push(this.v[b]);return this};Sk.builtin.list.prototype.sq$ass_item=Sk.builtin.list.prototype.list_ass_item_;Sk.builtin.list.prototype.sq$del_item=Sk.builtin.list.prototype.list_del_item_;
Sk.builtin.list.prototype.sq$ass_slice=Sk.builtin.list.prototype.list_ass_slice_;Sk.builtin.list.prototype.sq$del_slice=Sk.builtin.list.prototype.list_del_slice_;Sk.builtin.list.prototype.sq$contains=function(a){var b,c;b=this.tp$iter();for(c=b.tp$iternext();void 0!==c;c=b.tp$iternext())if(Sk.misceval.richCompareBool(c,a,"Eq"))return!0;return!1};
Sk.builtin.list.prototype.list_subscript_=function(a){var b,c;if(Sk.misceval.isIndex(a)){if(c=Sk.misceval.asIndex(a),void 0!==c){0>c&&(c=this.v.length+c);if(0>c||c>=this.v.length)throw new Sk.builtin.IndexError("list index out of range");return this.v[c]}}else if(a instanceof Sk.builtin.slice)return b=[],a.sssiter$(this,function(a,c){b.push(c.v[a])}),new Sk.builtin.list(b,!1);throw new Sk.builtin.TypeError("list indices must be integers, not "+Sk.abstr.typeName(a));};
Sk.builtin.list.prototype.list_ass_subscript_=function(a,b){var c,d,e;if(Sk.misceval.isIndex(a)){if(c=Sk.misceval.asIndex(a),void 0!==c){0>c&&(c=this.v.length+c);this.list_ass_item_(c,b);return}}else if(a instanceof Sk.builtin.slice){c=a.slice_indices_(this.v.length);if(1===c[2])this.list_ass_slice_(c[0],c[1],b);else{e=[];a.sssiter$(this,function(a,b){e.push(a)});d=0;if(e.length!==b.v.length)throw new Sk.builtin.ValueError("attempt to assign sequence of size "+b.v.length+" to extended slice of size "+
e.length);for(c=0;c<e.length;++c)this.v.splice(e[c],1,b.v[d]),d+=1}return}throw new Sk.builtin.TypeError("list indices must be integers, not "+Sk.abstr.typeName(a));};
Sk.builtin.list.prototype.list_del_subscript_=function(a){var b,c,d,e;if(Sk.misceval.isIndex(a)){if(e=Sk.misceval.asIndex(a),void 0!==e){0>e&&(e=this.v.length+e);this.list_del_item_(e);return}}else if(a instanceof Sk.builtin.slice){e=a.slice_indices_(this.v.length);1===e[2]?this.list_del_slice_(e[0],e[1]):(d=this,c=0,b=0<e[2]?1:0,a.sssiter$(this,function(a,e){d.v.splice(a-c,1);c+=b}));return}throw new Sk.builtin.TypeError("list indices must be integers, not "+typeof a);};
Sk.builtin.list.prototype.mp$subscript=Sk.builtin.list.prototype.list_subscript_;Sk.builtin.list.prototype.mp$ass_subscript=Sk.builtin.list.prototype.list_ass_subscript_;Sk.builtin.list.prototype.mp$del_subscript=Sk.builtin.list.prototype.list_del_subscript_;Sk.builtin.list.prototype.__getitem__=new Sk.builtin.func(function(a,b){return Sk.builtin.list.prototype.list_subscript_.call(a,b)});
Sk.builtin.list.prototype.list_sort_=function(a,b,c,d){var e,f,g,h,k=void 0!==c&&null!==c;f=void 0!==b&&null!==b;var l;if(void 0===d)l=!1;else{if(d===Sk.builtin.none.none$)throw new Sk.builtin.TypeError("an integer is required");l=Sk.misceval.isTrue(d)}d=new Sk.builtin.timSort(a);a.v=[];h=new Sk.builtin.int_(0);if(k)for(d.lt=f?function(a,c){var d=Sk.misceval.callsim(b,a[0],c[0]);return Sk.misceval.richCompareBool(d,h,"Lt")}:function(a,b){return Sk.misceval.richCompareBool(a[0],b[0],"Lt")},g=0;g<d.listlength;g++)f=
d.list.v[g],e=Sk.misceval.callsim(c,f),d.list.v[g]=[e,f];else f&&(d.lt=function(a,c){var d=Sk.misceval.callsim(b,a,c);return Sk.misceval.richCompareBool(d,h,"Lt")});l&&d.list.list_reverse_(d.list);d.sort();l&&d.list.list_reverse_(d.list);if(k)for(c=0;c<d.listlength;c++)f=d.list.v[c][1],d.list.v[c]=f;c=0<a.sq$length();a.v=d.list.v;if(c)throw new Sk.builtin.OperationError("list modified during sort");return Sk.builtin.none.none$};
Sk.builtin.list.prototype.list_reverse_=function(a){var b,c,d;Sk.builtin.pyCheckArgs("reverse",arguments,1,1);b=a.v.length;d=a.v;c=[];for(b-=1;-1<b;--b)c.push(d[b]);a.v=c;return Sk.builtin.none.none$};Sk.builtin.list.prototype.__iter__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__iter__",arguments,1,1);return a.list_iter_()});Sk.builtin.list.prototype.append=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("append",arguments,2,2);a.v.push(b);return Sk.builtin.none.none$});
Sk.builtin.list.prototype.insert=new Sk.builtin.func(function(a,b,c){Sk.builtin.pyCheckArgs("insert",arguments,3,3);if(!Sk.builtin.checkNumber(b))throw new Sk.builtin.TypeError("an integer is required");b=Sk.builtin.asnum$(b);0>b&&(b+=a.v.length);0>b?b=0:b>a.v.length&&(b=a.v.length);a.v.splice(b,0,c);return Sk.builtin.none.none$});Sk.builtin.list.prototype.extend=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("extend",arguments,2,2);a.list_extend_(b);return Sk.builtin.none.none$});
Sk.builtin.list.prototype.pop=new Sk.builtin.func(function(a,b){var c;Sk.builtin.pyCheckArgs("pop",arguments,1,2);void 0===b&&(b=a.v.length-1);if(!Sk.builtin.checkNumber(b))throw new Sk.builtin.TypeError("an integer is required");b=Sk.builtin.asnum$(b);0>b&&(b+=a.v.length);if(0>b||b>=a.v.length)throw new Sk.builtin.IndexError("pop index out of range");c=a.v[b];a.v.splice(b,1);return c});
Sk.builtin.list.prototype.remove=new Sk.builtin.func(function(a,b){var c;Sk.builtin.pyCheckArgs("remove",arguments,2,2);c=Sk.builtin.list.prototype.index.func_code(a,b);a.v.splice(Sk.builtin.asnum$(c),1);return Sk.builtin.none.none$});
Sk.builtin.list.prototype.index=new Sk.builtin.func(function(a,b,c,d){var e,f;Sk.builtin.pyCheckArgs("index",arguments,2,4);if(void 0!==c&&!Sk.builtin.checkInt(c))throw new Sk.builtin.TypeError("slice indices must be integers");if(void 0!==d&&!Sk.builtin.checkInt(d))throw new Sk.builtin.TypeError("slice indices must be integers");e=a.v.length;f=a.v;c=void 0===c?0:c.v;0>c&&(c=0<=c+e?c+e:0);d=void 0===d?e:d.v;0>d&&(d=0<=d+e?d+e:0);for(e=c;e<d;++e)if(Sk.misceval.richCompareBool(f[e],b,"Eq"))return new Sk.builtin.int_(e);
throw new Sk.builtin.ValueError("list.index(x): x not in list");});Sk.builtin.list.prototype.count=new Sk.builtin.func(function(a,b){var c,d,e,f;Sk.builtin.pyCheckArgs("count",arguments,2,2);f=a.v.length;e=a.v;for(c=d=0;c<f;++c)Sk.misceval.richCompareBool(e[c],b,"Eq")&&(d+=1);return new Sk.builtin.int_(d)});Sk.builtin.list.prototype.reverse=new Sk.builtin.func(Sk.builtin.list.prototype.list_reverse_);Sk.builtin.list.prototype.sort=new Sk.builtin.func(Sk.builtin.list.prototype.list_sort_);
Sk.builtin.list.prototype.sort.func_code.co_varnames=["__self__","cmp","key","reverse"];goog.exportSymbol("Sk.builtin.list",Sk.builtin.list);Sk.builtin.interned={};
Sk.builtin.str=function(a){void 0===a&&(a="");if(a instanceof Sk.builtin.str)return a;if(!(this instanceof Sk.builtin.str))return new Sk.builtin.str(a);if(!0===a)a="True";else if(!1===a)a="False";else if(null===a||a instanceof Sk.builtin.none)a="None";else if(a instanceof Sk.builtin.bool)a=a.v?"True":"False";else if("number"===typeof a)a=a.toString(),"Infinity"===a?a="inf":"-Infinity"===a&&(a="-inf");else if("string"!==typeof a){if(void 0!==a.tp$str){a=a.tp$str();if(!(a instanceof Sk.builtin.str))throw new Sk.builtin.ValueError("__str__ didn't return a str");
return a}return Sk.misceval.objectRepr(a)}if(Sk.builtin.interned["1"+a])return Sk.builtin.interned["1"+a];this.__class__=Sk.builtin.str;this.v=this.v=a;Sk.builtin.interned["1"+a]=this;return this};goog.exportSymbol("Sk.builtin.str",Sk.builtin.str);Sk.abstr.setUpInheritance("str",Sk.builtin.str,Sk.builtin.seqtype);
Sk.builtin.str.prototype.mp$subscript=function(a){var b;if(Sk.misceval.isIndex(a)){a=Sk.misceval.asIndex(a);0>a&&(a=this.v.length+a);if(0>a||a>=this.v.length)throw new Sk.builtin.IndexError("string index out of range");return new Sk.builtin.str(this.v.charAt(a))}if(a instanceof Sk.builtin.slice)return b="",a.sssiter$(this,function(a,d){0<=a&&a<d.v.length&&(b+=d.v.charAt(a))}),new Sk.builtin.str(b);throw new Sk.builtin.TypeError("string indices must be integers, not "+Sk.abstr.typeName(a));};
Sk.builtin.str.prototype.sq$length=function(){return this.v.length};Sk.builtin.str.prototype.sq$concat=function(a){if(!a||!Sk.builtin.checkString(a))throw a=Sk.abstr.typeName(a),new Sk.builtin.TypeError("cannot concatenate 'str' and '"+a+"' objects");return new Sk.builtin.str(this.v+a.v)};Sk.builtin.str.prototype.nb$add=Sk.builtin.str.prototype.sq$concat;Sk.builtin.str.prototype.nb$inplace_add=Sk.builtin.str.prototype.sq$concat;
Sk.builtin.str.prototype.sq$repeat=function(a){var b,c;if(!Sk.misceval.isIndex(a))throw new Sk.builtin.TypeError("can't multiply sequence by non-int of type '"+Sk.abstr.typeName(a)+"'");a=Sk.misceval.asIndex(a);c="";for(b=0;b<a;++b)c+=this.v;return new Sk.builtin.str(c)};Sk.builtin.str.prototype.nb$multiply=Sk.builtin.str.prototype.sq$repeat;Sk.builtin.str.prototype.nb$inplace_multiply=Sk.builtin.str.prototype.sq$repeat;Sk.builtin.str.prototype.sq$item=function(){goog.asserts.fail()};
Sk.builtin.str.prototype.sq$slice=function(a,b){a=Sk.builtin.asnum$(a);b=Sk.builtin.asnum$(b);0>a&&(a=0);return new Sk.builtin.str(this.v.substr(a,b-a))};Sk.builtin.str.prototype.sq$contains=function(a){if(!(a instanceof Sk.builtin.str))throw new Sk.builtin.TypeError("TypeError: 'In <string> requires string as left operand");return-1!=this.v.indexOf(a.v)};
Sk.builtin.str.prototype.tp$iter=function(){var a={tp$iter:function(){return a},$obj:this,$index:0,tp$iternext:function(){return a.$index>=a.$obj.v.length?void 0:new Sk.builtin.str(a.$obj.v.substr(a.$index++,1))},tp$name:"str_iterator"};return a};
Sk.builtin.str.prototype.tp$richcompare=function(a,b){if(a instanceof Sk.builtin.str)switch(b){case "Lt":return this.v<a.v;case "LtE":return this.v<=a.v;case "Eq":return this.v===a.v;case "NotEq":return this.v!==a.v;case "Gt":return this.v>a.v;case "GtE":return this.v>=a.v;default:goog.asserts.fail()}};
Sk.builtin.str.prototype.$r=function(){var a,b,c,d,e="'";-1!==this.v.indexOf("'")&&-1===this.v.indexOf('"')&&(e='"');d=this.v.length;c=e;for(b=0;b<d;++b)a=this.v.charAt(b),a===e||"\\"===a?c+="\\"+a:"\t"===a?c+="\\t":"\n"===a?c+="\\n":"\r"===a?c+="\\r":" ">a||127<=a?(a=a.charCodeAt(0).toString(16),2>a.length&&(a="0"+a),c+="\\x"+a):c+=a;return new Sk.builtin.str(c+e)};
Sk.builtin.str.re_escape_=function(a){var b,c,d=[],e=/^[A-Za-z0-9]+$/;for(c=0;c<a.length;++c)b=a.charAt(c),e.test(b)?d.push(b):"\\000"===b?d.push("\\000"):d.push("\\"+b);return d.join("")};Sk.builtin.str.prototype.lower=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("lower",arguments,1,1);return new Sk.builtin.str(a.v.toLowerCase())});Sk.builtin.str.prototype.upper=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("upper",arguments,1,1);return new Sk.builtin.str(a.v.toUpperCase())});
Sk.builtin.str.prototype.capitalize=new Sk.builtin.func(function(a){var b,c,d;Sk.builtin.pyCheckArgs("capitalize",arguments,1,1);d=a.v;if(0===d.length)return new Sk.builtin.str("");c=d.charAt(0).toUpperCase();for(b=1;b<d.length;b++)c+=d.charAt(b).toLowerCase();return new Sk.builtin.str(c)});
Sk.builtin.str.prototype.join=new Sk.builtin.func(function(a,b){var c,d,e;Sk.builtin.pyCheckArgs("join",arguments,2,2);Sk.builtin.pyCheckType("seq","iterable",Sk.builtin.checkIterable(b));e=[];c=b.tp$iter();for(d=c.tp$iternext();void 0!==d;d=c.tp$iternext()){if(d.constructor!==Sk.builtin.str)throw new Sk.builtin.TypeError("TypeError: sequence item "+e.length+": expected string, "+typeof d+" found");e.push(d.v)}return new Sk.builtin.str(e.join(a.v))});
Sk.builtin.str.prototype.split=new Sk.builtin.func(function(a,b,c){var d,e,f,g,h,k;Sk.builtin.pyCheckArgs("split",arguments,1,3);if(void 0===b||b instanceof Sk.builtin.none)b=null;if(null!==b&&!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("expected a string");if(null!==b&&""===b.v)throw new Sk.builtin.ValueError("empty separator");if(void 0!==c&&!Sk.builtin.checkInt(c))throw new Sk.builtin.TypeError("an integer is required");c=Sk.builtin.asnum$(c);k=/[\s]+/g;h=a.v;null===b?h=goog.string.trimLeft(h):
(d=b.v.replace(/([.*+?=|\\\/()\[\]\{\}^$])/g,"\\$1"),k=RegExp(d,"g"));g=[];for(d=e=0;null!=(f=k.exec(h))&&f.index!==k.lastIndex&&!(g.push(new Sk.builtin.str(h.substring(e,f.index))),e=k.lastIndex,d+=1,c&&d>=c););h=h.substring(e);(null!==b||0<h.length)&&g.push(new Sk.builtin.str(h));return new Sk.builtin.list(g)});
Sk.builtin.str.prototype.strip=new Sk.builtin.func(function(a,b){var c;Sk.builtin.pyCheckArgs("strip",arguments,1,2);if(void 0!==b&&!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("strip arg must be None or str");void 0===b?c=/^\s+|\s+$/g:(c=Sk.builtin.str.re_escape_(b.v),c=RegExp("^["+c+"]+|["+c+"]+$","g"));return new Sk.builtin.str(a.v.replace(c,""))});
Sk.builtin.str.prototype.lstrip=new Sk.builtin.func(function(a,b){var c;Sk.builtin.pyCheckArgs("lstrip",arguments,1,2);if(void 0!==b&&!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("lstrip arg must be None or str");void 0===b?c=/^\s+/g:(c=Sk.builtin.str.re_escape_(b.v),c=RegExp("^["+c+"]+","g"));return new Sk.builtin.str(a.v.replace(c,""))});
Sk.builtin.str.prototype.rstrip=new Sk.builtin.func(function(a,b){var c;Sk.builtin.pyCheckArgs("rstrip",arguments,1,2);if(void 0!==b&&!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("rstrip arg must be None or str");void 0===b?c=/\s+$/g:(c=Sk.builtin.str.re_escape_(b.v),c=RegExp("["+c+"]+$","g"));return new Sk.builtin.str(a.v.replace(c,""))});
Sk.builtin.str.prototype.partition=new Sk.builtin.func(function(a,b){var c,d;Sk.builtin.pyCheckArgs("partition",arguments,2,2);Sk.builtin.pyCheckType("sep","string",Sk.builtin.checkString(b));d=new Sk.builtin.str(b);c=a.v.indexOf(d.v);return 0>c?new Sk.builtin.tuple([a,Sk.builtin.str.$emptystr,Sk.builtin.str.$emptystr]):new Sk.builtin.tuple([new Sk.builtin.str(a.v.substring(0,c)),d,new Sk.builtin.str(a.v.substring(c+d.v.length))])});
Sk.builtin.str.prototype.rpartition=new Sk.builtin.func(function(a,b){var c,d;Sk.builtin.pyCheckArgs("rpartition",arguments,2,2);Sk.builtin.pyCheckType("sep","string",Sk.builtin.checkString(b));d=new Sk.builtin.str(b);c=a.v.lastIndexOf(d.v);return 0>c?new Sk.builtin.tuple([Sk.builtin.str.$emptystr,Sk.builtin.str.$emptystr,a]):new Sk.builtin.tuple([new Sk.builtin.str(a.v.substring(0,c)),d,new Sk.builtin.str(a.v.substring(c+d.v.length))])});
Sk.builtin.str.prototype.count=new Sk.builtin.func(function(a,b,c,d){var e;Sk.builtin.pyCheckArgs("count",arguments,2,4);if(!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("expected a character buffer object");if(void 0!==c&&!Sk.builtin.checkInt(c))throw new Sk.builtin.TypeError("slice indices must be integers or None or have an __index__ method");if(void 0!==d&&!Sk.builtin.checkInt(d))throw new Sk.builtin.TypeError("slice indices must be integers or None or have an __index__ method");void 0===
c?c=0:(c=Sk.builtin.asnum$(c),c=0<=c?c:a.v.length+c);void 0===d?d=a.v.length:(d=Sk.builtin.asnum$(d),d=0<=d?d:a.v.length+d);e=RegExp(b.v,"g");return(e=a.v.slice(c,d).match(e))?new Sk.builtin.int_(e.length):new Sk.builtin.int_(0)});
Sk.builtin.str.prototype.ljust=new Sk.builtin.func(function(a,b,c){var d;Sk.builtin.pyCheckArgs("ljust",arguments,2,3);if(!Sk.builtin.checkInt(b))throw new Sk.builtin.TypeError("integer argument exepcted, got "+Sk.abstr.typeName(b));if(void 0!==c&&(!Sk.builtin.checkString(c)||1!==c.v.length))throw new Sk.builtin.TypeError("must be char, not "+Sk.abstr.typeName(c));c=void 0===c?" ":c.v;b=Sk.builtin.asnum$(b);if(a.v.length>=b)return a;d=Array.prototype.join.call({length:Math.floor(b-a.v.length)+1},
c);return new Sk.builtin.str(a.v+d)});
Sk.builtin.str.prototype.rjust=new Sk.builtin.func(function(a,b,c){var d;Sk.builtin.pyCheckArgs("rjust",arguments,2,3);if(!Sk.builtin.checkInt(b))throw new Sk.builtin.TypeError("integer argument exepcted, got "+Sk.abstr.typeName(b));if(void 0!==c&&(!Sk.builtin.checkString(c)||1!==c.v.length))throw new Sk.builtin.TypeError("must be char, not "+Sk.abstr.typeName(c));c=void 0===c?" ":c.v;b=Sk.builtin.asnum$(b);if(a.v.length>=b)return a;d=Array.prototype.join.call({length:Math.floor(b-a.v.length)+1},
c);return new Sk.builtin.str(d+a.v)});
Sk.builtin.str.prototype.center=new Sk.builtin.func(function(a,b,c){var d;Sk.builtin.pyCheckArgs("center",arguments,2,3);if(!Sk.builtin.checkInt(b))throw new Sk.builtin.TypeError("integer argument exepcted, got "+Sk.abstr.typeName(b));if(void 0!==c&&(!Sk.builtin.checkString(c)||1!==c.v.length))throw new Sk.builtin.TypeError("must be char, not "+Sk.abstr.typeName(c));c=void 0===c?" ":c.v;b=Sk.builtin.asnum$(b);if(a.v.length>=b)return a;d=Array.prototype.join.call({length:Math.floor((b-a.v.length)/
2)+1},c);d=d+a.v+d;d.length<b&&(d+=c);return new Sk.builtin.str(d)});
Sk.builtin.str.prototype.find=new Sk.builtin.func(function(a,b,c,d){var e;Sk.builtin.pyCheckArgs("find",arguments,2,4);if(!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("expected a character buffer object");if(void 0!==c&&!Sk.builtin.checkInt(c))throw new Sk.builtin.TypeError("slice indices must be integers or None or have an __index__ method");if(void 0!==d&&!Sk.builtin.checkInt(d))throw new Sk.builtin.TypeError("slice indices must be integers or None or have an __index__ method");void 0===
c?c=0:(c=Sk.builtin.asnum$(c),c=0<=c?c:a.v.length+c);void 0===d?d=a.v.length:(d=Sk.builtin.asnum$(d),d=0<=d?d:a.v.length+d);e=a.v.indexOf(b.v,c);return new Sk.builtin.int_(e>=c&&e<d?e:-1)});Sk.builtin.str.prototype.index=new Sk.builtin.func(function(a,b,c,d){var e;Sk.builtin.pyCheckArgs("index",arguments,2,4);e=Sk.misceval.callsim(a.find,a,b,c,d);if(-1===Sk.builtin.asnum$(e))throw new Sk.builtin.ValueError("substring not found");return e});
Sk.builtin.str.prototype.rfind=new Sk.builtin.func(function(a,b,c,d){var e;Sk.builtin.pyCheckArgs("rfind",arguments,2,4);if(!Sk.builtin.checkString(b))throw new Sk.builtin.TypeError("expected a character buffer object");if(void 0!==c&&!Sk.builtin.checkInt(c))throw new Sk.builtin.TypeError("slice indices must be integers or None or have an __index__ method");if(void 0!==d&&!Sk.builtin.checkInt(d))throw new Sk.builtin.TypeError("slice indices must be integers or None or have an __index__ method");void 0===
c?c=0:(c=Sk.builtin.asnum$(c),c=0<=c?c:a.v.length+c);void 0===d?d=a.v.length:(d=Sk.builtin.asnum$(d),d=0<=d?d:a.v.length+d);e=a.v.lastIndexOf(b.v,d);e=e!==d?e:a.v.lastIndexOf(b.v,d-1);return new Sk.builtin.int_(e>=c&&e<d?e:-1)});Sk.builtin.str.prototype.rindex=new Sk.builtin.func(function(a,b,c,d){var e;Sk.builtin.pyCheckArgs("rindex",arguments,2,4);e=Sk.misceval.callsim(a.rfind,a,b,c,d);if(-1===Sk.builtin.asnum$(e))throw new Sk.builtin.ValueError("substring not found");return e});
Sk.builtin.str.prototype.startswith=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("startswith",arguments,2,2);Sk.builtin.pyCheckType("tgt","string",Sk.builtin.checkString(b));return new Sk.builtin.bool(0===a.v.indexOf(b.v))});Sk.builtin.str.prototype.endswith=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("endswith",arguments,2,2);Sk.builtin.pyCheckType("tgt","string",Sk.builtin.checkString(b));return new Sk.builtin.bool(-1!==a.v.indexOf(b.v,a.v.length-b.v.length))});
Sk.builtin.str.prototype.replace=new Sk.builtin.func(function(a,b,c,d){var e,f;Sk.builtin.pyCheckArgs("replace",arguments,3,4);Sk.builtin.pyCheckType("oldS","string",Sk.builtin.checkString(b));Sk.builtin.pyCheckType("newS","string",Sk.builtin.checkString(c));if(void 0!==d&&!Sk.builtin.checkInt(d))throw new Sk.builtin.TypeError("integer argument expected, got "+Sk.abstr.typeName(d));d=Sk.builtin.asnum$(d);f=RegExp(Sk.builtin.str.re_escape_(b.v),"g");if(void 0===d||0>d)return new Sk.builtin.str(a.v.replace(f,
c.v));e=0;return new Sk.builtin.str(a.v.replace(f,function(a){e++;return e<=d?c.v:a}))});Sk.builtin.str.prototype.zfill=new Sk.builtin.func(function(a,b){var c=a.v,d,e,f="";Sk.builtin.pyCheckArgs("zfill",arguments,2,2);if(!Sk.builtin.checkInt(b))throw new Sk.builtin.TypeError("integer argument exepected, got "+Sk.abstr.typeName(b));d=b.v-c.length;e="+"===c[0]||"-"===c[0]?1:0;for(var g=0;g<d;g++)f+="0";c=c.substr(0,e)+f+c.substr(e);return new Sk.builtin.str(c)});
Sk.builtin.str.prototype.isdigit=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("isdigit",arguments,1,1);return new Sk.builtin.bool(/^\d+$/.test(a.v))});Sk.builtin.str.prototype.isspace=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("isspace",arguments,1,1);return new Sk.builtin.bool(/^\s+$/.test(a.v))});
Sk.builtin.str.prototype.expandtabs=new Sk.builtin.func(function(a,b){var c,d;Sk.builtin.pyCheckArgs("expandtabs",arguments,1,2);if(void 0!==b&&!Sk.builtin.checkInt(b))throw new Sk.builtin.TypeError("integer argument exepected, got "+Sk.abstr.typeName(b));b=void 0===b?8:Sk.builtin.asnum$(b);c=Array(b+1).join(" ");d=a.v.replace(/([^\r\n\t]*)\t/g,function(a,d){return d+c.slice(d.length%b)});return new Sk.builtin.str(d)});
Sk.builtin.str.prototype.swapcase=new Sk.builtin.func(function(a){var b;Sk.builtin.pyCheckArgs("swapcase",arguments,1,1);b=a.v.replace(/[a-z]/gi,function(a){var b=a.toLowerCase();return b===a?a.toUpperCase():b});return new Sk.builtin.str(b)});
Sk.builtin.str.prototype.splitlines=new Sk.builtin.func(function(a,b){var c=a.v,d=0,e=a.v.length,f=[],g,h=0;Sk.builtin.pyCheckArgs("splitlines",arguments,1,2);if(void 0!==b&&!Sk.builtin.checkBool(b))throw new Sk.builtin.TypeError("boolean argument expected, got "+Sk.abstr.typeName(b));b=void 0===b?!1:b.v;for(d=0;d<e;d++)if(g=c.charAt(d),"\n"===c.charAt(d+1)&&"\r"===g)g=d+2,h=c.slice(h,g),b||(h=h.replace(/(\r|\n)/g,"")),f.push(new Sk.builtin.str(h)),h=g;else if("\n"===g&&"\r"!==c.charAt(d-1)||"\r"===
g)g=d+1,h=c.slice(h,g),b||(h=h.replace(/(\r|\n)/g,"")),f.push(new Sk.builtin.str(h)),h=g;h<e&&(h=c.slice(h,e),b||(h=h.replace(/(\r|\n)/g,"")),f.push(new Sk.builtin.str(h)));return new Sk.builtin.list(f)});Sk.builtin.str.prototype.title=new Sk.builtin.func(function(a){var b;Sk.builtin.pyCheckArgs("title",arguments,1,1);b=a.v.replace(/[a-z][a-z]*/gi,function(a){return a[0].toUpperCase()+a.substr(1).toLowerCase()});return new Sk.builtin.str(b)});
Sk.builtin.str.prototype.isalpha=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("isalpha",arguments,1,1);return new Sk.builtin.bool(a.v.length&&goog.string.isAlpha(a.v))});Sk.builtin.str.prototype.isalnum=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("isalnum",arguments,1,1);return new Sk.builtin.bool(a.v.length&&goog.string.isAlphaNumeric(a.v))});
Sk.builtin.str.prototype.isnumeric=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("isnumeric",arguments,1,1);return new Sk.builtin.bool(a.v.length&&goog.string.isNumeric(a.v))});Sk.builtin.str.prototype.islower=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("islower",arguments,1,1);return new Sk.builtin.bool(a.v.length&&/[a-z]/.test(a.v)&&!/[A-Z]/.test(a.v))});
Sk.builtin.str.prototype.isupper=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("isupper",arguments,1,1);return new Sk.builtin.bool(a.v.length&&!/[a-z]/.test(a.v)&&/[A-Z]/.test(a.v))});
Sk.builtin.str.prototype.istitle=new Sk.builtin.func(function(a){var b=a.v,c=!1,d=!1,e,f;Sk.builtin.pyCheckArgs("istitle",arguments,1,1);for(e=0;e<b.length;e++)if(f=b.charAt(e),!/[a-z]/.test(f)&&/[A-Z]/.test(f)){if(d)return new Sk.builtin.bool(!1);c=d=!0}else if(/[a-z]/.test(f)&&!/[A-Z]/.test(f)){if(!d)return new Sk.builtin.bool(!1);c=!0}else d=!1;return new Sk.builtin.bool(c)});
Sk.builtin.str.prototype.nb$remainder=function(a){var b,c;a.constructor===Sk.builtin.tuple||void 0!==a.mp$subscript&&a.constructor!==Sk.builtin.str||(a=new Sk.builtin.tuple([a]));c=0;b=this.v.replace(/%(\([a-zA-Z0-9]+\))?([#0 +\-]+)?(\*|[0-9]+)?(\.(\*|[0-9]+))?[hlL]?([diouxXeEfFgGcrs%])/g,function(b,e,f,g,h,k,l){var m,q,n,r,p,s;g=Sk.builtin.asnum$(g);h=Sk.builtin.asnum$(h);if(void 0===e||""===e)m=c++;""===h&&(h=void 0);q=n=r=p=s=!1;f&&(-1!==f.indexOf("-")?p=!0:-1!==f.indexOf("0")&&(s=!0),-1!==f.indexOf("+")?
n=!0:-1!==f.indexOf(" ")&&(r=!0),q=-1!==f.indexOf("#"));h&&(h=parseInt(h.substr(1),10));f=function(a,b){var c,d,e,f;b=Sk.builtin.asnum$(b);e=!1;"number"===typeof a?(0>a&&(a=-a,e=!0),f=a.toString(b)):a instanceof Sk.builtin.float_?(f=a.str$(b,!1),2<f.length&&".0"===f.substr(-2)&&(f=f.substr(0,f.length-2)),e=a.nb$isnegative()):a instanceof Sk.builtin.int_?(f=a.str$(b,!1),e=a.nb$isnegative()):a instanceof Sk.builtin.lng&&(f=a.str$(b,!1),e=a.nb$isnegative());goog.asserts.assert(void 0!==f,"unhandled number format");
c=!1;if(h)for(d=f.length;d<h;++d)f="0"+f,c=!0;d="";e?d="-":n?d="+"+d:r&&(d=" "+d);q&&(16===b?d+="0x":8!==b||(c||"0"===f)||(d+="0"));return[d,f]};b=function(a){var b,c=a[0];a=a[1];if(g)if(g=parseInt(g,10),b=a.length+c.length,s)for(;b<g;++b)a="0"+a;else if(p)for(;b<g;++b)a+=" ";else for(;b<g;++b)c=" "+c;return c+a};if(a.constructor===Sk.builtin.tuple)e=a.v[m];else if(void 0!==a.mp$subscript&&void 0!==e)e=e.substring(1,e.length-1),e=a.mp$subscript(new Sk.builtin.str(e));else if(a.constructor===Sk.builtin.dict||
a.constructor===Sk.builtin.list)e=a;else throw new Sk.builtin.AttributeError(a.tp$name+" instance has no attribute 'mp$subscript'");if("d"===l||"i"===l)return b(f(e,10));if("o"===l)return b(f(e,8));if("x"===l)return b(f(e,16));if("X"===l)return b(f(e,16)).toUpperCase();if("f"===l||"F"===l||"e"===l||"E"===l||"g"===l||"G"===l){m=Sk.builtin.asnum$(e);"string"===typeof m&&(m=Number(m));if(Infinity===m)return"inf";if(-Infinity===m)return"-inf";if(isNaN(m))return"nan";f=["toExponential","toFixed","toPrecision"]["efg".indexOf(l.toLowerCase())];
if(void 0===h||""===h)if("e"===l||"E"===l)h=6;else if("f"===l||"F"===l)h=7;f=m[f](h);Sk.builtin.checkFloat(e)&&0===m&&-Infinity===1/m&&(f="-"+f);-1!=="EFG".indexOf(l)&&(f=f.toUpperCase());return b(["",f])}if("c"===l){if("number"===typeof e)return String.fromCharCode(e);if(e instanceof Sk.builtin.int_)return String.fromCharCode(e.v);if(e instanceof Sk.builtin.float_)return String.fromCharCode(e.v);if(e instanceof Sk.builtin.lng)return String.fromCharCode(e.str$(10,!1)[0]);if(e.constructor===Sk.builtin.str)return e.v.substr(0,
1);throw new Sk.builtin.TypeError("an integer is required");}if("r"===l)return l=Sk.builtin.repr(e),h?l.v.substr(0,h):l.v;if("s"===l){l=new Sk.builtin.str(e);if(h)return l.v.substr(0,h);g&&(l.v=b([" ",l.v]));return l.v}if("%"===l)return"%"});return new Sk.builtin.str(b)};var format=function(a){var b,c,d,e={};Sk.builtin.pyCheckArgs("format",arguments,0,Infinity,!0,!0);b=new Sk.builtins.tuple(Array.prototype.slice.call(arguments,1));c=new Sk.builtins.dict(a);if(void 0===arguments[1])return b.v;d=0;if(0!==c.size){c=Sk.misceval.callsim(Sk.builtin.dict.prototype.items,c);for(var f in c.v)e[c.v[f].v[0].v]=c.v[f].v[1].v}for(var g in b.v)"0"!==g&&(e[g-1]=b.v[g].v);b=b.v[0].v.replace(/{(((?:\d+)|(?:\w+))?((?:\.(\w+))|(?:\[((?:\d+)|(?:\w+))\])?))?(?:\!([rs]))?(?:\:((?:(.)?([<\>\=\^]))?([\+\-\s])?(#)?(0)?(\d+)?(,)?(?:\.(\d+))?([bcdeEfFgGnosxX%])?))?}/g,
function(a,b,c,f,g,n,r,p,s,B,x,y,C,v,J,w,t,K,E){var D,u,z,A,F,G,H,I;v=Sk.builtin.asnum$(v);w=Sk.builtin.asnum$(w);if(void 0!==n&&""!==n)u=e[c][n].v,d++;else if(void 0!==g&&""!==g)u=e[c][g].v,d++;else if(void 0!==c&&""!==c)u=e[c],d++;else if(void 0===b||""===b)a=e[d],d++,u=a;else if(b instanceof Sk.builtin.int_||b instanceof Sk.builtin.float_||b instanceof Sk.builtin.lng||!isNaN(parseInt(b,10)))a=e[b],d++,u=a;""===w&&(w=void 0);if(void 0===s||""===s)s=" ";A=F=G=H=!1;p&&(void 0!==x&&""!==x&&(-1!=="-".indexOf(x)?
H=!0:-1!=="+".indexOf(x)?F=!0:-1!==" ".indexOf(x)&&(G=!0)),y&&(A=-1!=="#".indexOf(y)),void 0===v||""===v||void 0!==s&&""!==s||(s=" "),-1!=="%".indexOf(t)&&(I=!0));w&&(w=parseInt(w,10));D=function(a){if(void 0===r||""===r)return a;if("r"==r)return a=new Sk.builtin.str(a),a=Sk.builtin.repr(a),a.v;if("s"==r)return a=new Sk.builtin.str(a),a.v};z=function(a,b){var c;I&&(b+="%");if(void 0!==v&&""!==v)if(v=parseInt(v,10),c=b.length+a.length,H)for(;c<v;++c)b+=s;else if(-1!==">".indexOf(B))for(;c<v;++c)a=
s+a;else if(-1!=="^".indexOf(B))for(;c<v;++c)0===c%2?a=s+a:1===c%2&&(b+=s);else if(-1!=="=".indexOf(B))for(;c<v;++c)b=s+b;else for(;c<v;++c)b+=s;return D(a+b)};x=function(a,b){var c,d,e;b=Sk.builtin.asnum$(b);d=!1;if(void 0===p)return D(u);"number"!==typeof a||w?w?(0>a&&(a=-a,d=!0),a=Number(a.toString(b)),e=a.toFixed(w)):a instanceof Sk.builtin.float_?(e=a.str$(b,!1),2<e.length&&".0"===e.substr(-2)&&(e=e.substr(0,e.length-2)),d=a.nb$isnegative()):a instanceof Sk.builtin.int_?(e=a.str$(b,!1),d=a.nb$isnegative()):
a instanceof Sk.builtin.lng?(e=a.str$(b,!1),d=a.nb$isnegative()):e=a:(0>a&&(a=-a,d=!0),e=a.toString(b));c="";d?c="-":F?c="+":G&&(c=" ");A&&(16===b?c+="0x":8===b&&"0"!==e?c+="0o":2===b&&"0"!==e&&(c+="0b"));"n"===t?e=e.toLocaleString():-1!==",".indexOf(J)&&(d=e.toString().split("."),d[0]=d[0].replace(/\B(?=(\d{3})+(?!\d))/g,","),e=d.join("."));return z(c,e)};if("d"===t||"n"===t||""===t||void 0===t)return x(u,10);if("b"===t)return x(u,2);if("o"===t)return x(u,8);if("x"===t)return x(u,16);if("X"===t)return x(u,
16).toUpperCase();if("f"===t||"F"===t||"e"===t||"E"===t||"g"===t||"G"===t){if(A)throw new Sk.builtin.ValueError("Alternate form (#) not allowed in float format specifier");a=Sk.builtin.asnum$(u);"string"===typeof a&&(a=Number(a));if(Infinity===a)return z("","inf");if(-Infinity===a)return z("-","inf");if(isNaN(a))return z("","nan");y=["toExponential","toFixed","toPrecision"]["efg".indexOf(t.toLowerCase())];if(void 0===w||""===w)if("e"===t||"E"===t||"%"===t)w=6;else if("f"===t||"F"===t)w=6;y=a[y](w);
-1!=="EFG".indexOf(t)&&(y=y.toUpperCase());return x(y,10)}if("c"===t){if("number"===typeof u)return z("",String.fromCharCode(u));if(u instanceof Sk.builtin.int_)return z("",String.fromCharCode(u.v));if(u instanceof Sk.builtin.float_)return z("",String.fromCharCode(u.v));if(u instanceof Sk.builtin.lng)return z("",String.fromCharCode(u.str$(10,!1)[0]));if(u.constructor===Sk.builtin.str)return z("",u.v.substr(0,1));throw new Sk.builtin.TypeError("an integer is required");}if(I)return void 0===w&&(w=
7),x(100*u,10)});return new Sk.builtin.str(b)};format.co_kwargs=!0;Sk.builtin.str.prototype.format=new Sk.builtin.func(format);Sk.builtin.tuple=function(a){var b;if(!(this instanceof Sk.builtin.tuple))return new Sk.builtin.tuple(a);void 0===a&&(a=[]);if("[object Array]"===Object.prototype.toString.apply(a))this.v=a;else if(Sk.builtin.checkIterable(a))for(this.v=[],a=Sk.abstr.iter(a),b=a.tp$iternext();void 0!==b;b=a.tp$iternext())this.v.push(b);else throw new Sk.builtin.TypeError("expecting Array or iterable");this.__class__=Sk.builtin.tuple;this.v=this.v;return this};Sk.abstr.setUpInheritance("tuple",Sk.builtin.tuple,Sk.builtin.seqtype);
Sk.builtin.tuple.prototype.$r=function(){var a,b;if(0===this.v.length)return new Sk.builtin.str("()");b=[];for(a=0;a<this.v.length;++a)b[a]=Sk.misceval.objectRepr(this.v[a]).v;a=b.join(", ");1===this.v.length&&(a+=",");return new Sk.builtin.str("("+a+")")};
Sk.builtin.tuple.prototype.mp$subscript=function(a){var b,c;if(Sk.misceval.isIndex(a)){if(c=Sk.misceval.asIndex(a),void 0!==c){0>c&&(c=this.v.length+c);if(0>c||c>=this.v.length)throw new Sk.builtin.IndexError("tuple index out of range");return this.v[c]}}else if(a instanceof Sk.builtin.slice)return b=[],a.sssiter$(this,function(a,c){b.push(c.v[a])}),new Sk.builtin.tuple(b);throw new Sk.builtin.TypeError("tuple indices must be integers, not "+Sk.abstr.typeName(a));};
Sk.builtin.tuple.prototype.tp$hash=function(){var a,b,c=1000003,d=3430008,e=this.v.length;for(b=0;b<e;++b){a=Sk.builtin.hash(this.v[b]).v;if(-1===a)return new Sk.builtin.int_(-1);d=(d^a)*c;c+=82520+e+e}d+=97531;-1===d&&(d=-2);return new Sk.builtin.int_(d|0)};Sk.builtin.tuple.prototype.sq$repeat=function(a){var b,c,d;a=Sk.misceval.asIndex(a);d=[];for(c=0;c<a;++c)for(b=0;b<this.v.length;++b)d.push(this.v[b]);return new Sk.builtin.tuple(d)};Sk.builtin.tuple.prototype.nb$multiply=Sk.builtin.tuple.prototype.sq$repeat;
Sk.builtin.tuple.prototype.nb$inplace_multiply=Sk.builtin.tuple.prototype.sq$repeat;Sk.builtin.tuple.prototype.tp$iter=function(){var a={tp$iter:function(){return a},$obj:this,$index:0,tp$iternext:function(){return a.$index>=a.$obj.v.length?void 0:a.$obj.v[a.$index++]},tp$name:"tuple_iterator"};return a};Sk.builtin.tuple.prototype.__iter__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__iter__",arguments,1,1);return a.tp$iter()});
Sk.builtin.tuple.prototype.tp$richcompare=function(a,b){var c,d,e,f,g;if(!a.__class__||!Sk.builtin.isinstance(a,Sk.builtin.tuple))return"Eq"===b?!1:"NotEq"===b?!0:!1;g=this.v;a=a.v;f=g.length;e=a.length;for(d=0;d<f&&d<e&&(c=Sk.misceval.richCompareBool(g[d],a[d],"Eq"),c);++d);if(d>=f||d>=e)switch(b){case "Lt":return f<e;case "LtE":return f<=e;case "Eq":return f===e;case "NotEq":return f!==e;case "Gt":return f>e;case "GtE":return f>=e;default:goog.asserts.fail()}return"Eq"===b?!1:"NotEq"===b?!0:Sk.misceval.richCompareBool(g[d],
a[d],b)};Sk.builtin.tuple.prototype.sq$concat=function(a){if(a.__class__!=Sk.builtin.tuple)throw a='can only concatenate tuple (not "'+(Sk.abstr.typeName(a)+'") to tuple'),new Sk.builtin.TypeError(a);return new Sk.builtin.tuple(this.v.concat(a.v))};Sk.builtin.tuple.prototype.sq$contains=function(a){var b,c;b=this.tp$iter();for(c=b.tp$iternext();void 0!==c;c=b.tp$iternext())if(Sk.misceval.richCompareBool(c,a,"Eq"))return!0;return!1};Sk.builtin.tuple.prototype.nb$add=Sk.builtin.tuple.prototype.sq$concat;
Sk.builtin.tuple.prototype.nb$inplace_add=Sk.builtin.tuple.prototype.sq$concat;Sk.builtin.tuple.prototype.sq$length=function(){return this.v.length};Sk.builtin.tuple.prototype.index=new Sk.builtin.func(function(a,b){var c,d=a.v.length,e=a.v;for(c=0;c<d;++c)if(Sk.misceval.richCompareBool(e[c],b,"Eq"))return new Sk.builtin.int_(c);throw new Sk.builtin.ValueError("tuple.index(x): x not in tuple");});
Sk.builtin.tuple.prototype.count=new Sk.builtin.func(function(a,b){var c,d=a.v.length,e=a.v,f=0;for(c=0;c<d;++c)Sk.misceval.richCompareBool(e[c],b,"Eq")&&(f+=1);return new Sk.builtin.int_(f)});goog.exportSymbol("Sk.builtin.tuple",Sk.builtin.tuple);Sk.builtin.dict=function(a){var b,c,d;if(!(this instanceof Sk.builtin.dict))return new Sk.builtin.dict(a);void 0===a&&(a=[]);this.size=0;if("[object Array]"===Object.prototype.toString.apply(a))for(b=0;b<a.length;b+=2)this.mp$ass_subscript(a[b],a[b+1]);else if(a instanceof Sk.builtin.dict)for(c=Sk.abstr.iter(a),d=c.tp$iternext();void 0!==d;d=c.tp$iternext())b=a.mp$subscript(d),void 0===b&&(b=null),this.mp$ass_subscript(d,b);else if(Sk.builtin.checkIterable(a))for(c=Sk.abstr.iter(a),b=c.tp$iternext();void 0!==
b;b=c.tp$iternext())if(b.mp$subscript)this.mp$ass_subscript(b.mp$subscript(0),b.mp$subscript(1));else throw new Sk.builtin.TypeError("element "+this.size+" is not a sequence");else throw new Sk.builtin.TypeError("object is not iterable");this.__class__=Sk.builtin.dict;return this};Sk.abstr.setUpInheritance("dict",Sk.builtin.dict,Sk.builtin.object);Sk.abstr.markUnhashable(Sk.builtin.dict);var kf=Sk.builtin.hash;
Sk.builtin.dict.prototype.key$lookup=function(a,b){var c,d,e;for(e=0;e<a.items.length;e++)if(c=a.items[e],d=Sk.misceval.richCompareBool(c.lhs,b,"Eq"))return c;return null};Sk.builtin.dict.prototype.key$pop=function(a,b){var c,d,e;for(e=0;e<a.items.length;e++)if(c=a.items[e],d=Sk.misceval.richCompareBool(c.lhs,b,"Eq"))return a.items.splice(e,1),this.size-=1,c};Sk.builtin.dict.prototype.mp$lookup=function(a){var b=this[kf(a).v];if(void 0!==b&&(a=this.key$lookup(b,a)))return a.rhs};
Sk.builtin.dict.prototype.mp$subscript=function(a){Sk.builtin.pyCheckArgs("[]",arguments,1,2,!1,!1);var b;b=this.mp$lookup(a);if(void 0!==b)return b;b=new Sk.builtin.str(a);throw new Sk.builtin.KeyError(b.v);};Sk.builtin.dict.prototype.sq$contains=function(a){Sk.builtin.pyCheckArgs("__contains__()",arguments,1,1,!1,!1);return void 0!==this.mp$lookup(a)};
Sk.builtin.dict.prototype.mp$ass_subscript=function(a,b){var c=kf(a),d=this[c.v];void 0===d?(d={$hash:c,items:[{lhs:a,rhs:b}]},this[c.v]=d,this.size+=1):(c=this.key$lookup(d,a))?c.rhs=b:(d.items.push({lhs:a,rhs:b}),this.size+=1)};Sk.builtin.dict.prototype.mp$del_subscript=function(a){Sk.builtin.pyCheckArgs("del",arguments,1,1,!1,!1);var b=this[kf(a).v];if(void 0!==b&&(b=this.key$pop(b,a),void 0!==b))return;b=new Sk.builtin.str(a);throw new Sk.builtin.KeyError(b.v);};
Sk.builtin.dict.prototype.tp$iter=function(){var a,b,c,d,e=[];for(d in this)if(this.hasOwnProperty(d)&&(c=this[d])&&void 0!==c.$hash)for(b=0;b<c.items.length;b++)e.push(c.items[b].lhs);return a={tp$iter:function(){return a},$obj:this,$index:0,$keys:e,tp$iternext:function(){return a.$index>=a.$keys.length?void 0:a.$keys[a.$index++]},tp$name:"dict_keyiterator"}};
Sk.builtin.dict.prototype.$r=function(){var a,b,c,d=[];b=Sk.abstr.iter(this);for(c=b.tp$iternext();void 0!==c;c=b.tp$iternext())a=this.mp$subscript(c),void 0===a&&(a=null),a===this?d.push(Sk.misceval.objectRepr(c).v+": {...}"):d.push(Sk.misceval.objectRepr(c).v+": "+Sk.misceval.objectRepr(a).v);return new Sk.builtin.str("{"+d.join(", ")+"}")};Sk.builtin.dict.prototype.mp$length=function(){return this.size};
Sk.builtin.dict.prototype.get=new Sk.builtin.func(function(a,b,c){Sk.builtin.pyCheckArgs("get()",arguments,1,2,!1,!0);var d;void 0===c&&(c=Sk.builtin.none.none$);d=a.mp$lookup(b);void 0===d&&(d=c);return d});Sk.builtin.dict.prototype.pop=new Sk.builtin.func(function(a,b,c){Sk.builtin.pyCheckArgs("pop()",arguments,1,2,!1,!0);var d=kf(b),d=a[d.v];if(void 0!==d&&(d=a.key$pop(d,b),void 0!==d))return d.rhs;if(void 0!==c)return c;d=new Sk.builtin.str(b);throw new Sk.builtin.KeyError(d.v);});
Sk.builtin.dict.prototype.has_key=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("has_key()",arguments,1,1,!1,!0);return new Sk.builtin.bool(a.sq$contains(b))});Sk.builtin.dict.prototype.items=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("items()",arguments,0,0,!1,!0);var b,c,d,e=[];c=Sk.abstr.iter(a);for(d=c.tp$iternext();void 0!==d;d=c.tp$iternext())b=a.mp$subscript(d),void 0===b&&(b=null),e.push(new Sk.builtin.tuple([d,b]));return new Sk.builtin.list(e)});
Sk.builtin.dict.prototype.keys=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("keys()",arguments,0,0,!1,!0);var b,c,d=[];b=Sk.abstr.iter(a);for(c=b.tp$iternext();void 0!==c;c=b.tp$iternext())d.push(c);return new Sk.builtin.list(d)});Sk.builtin.dict.prototype.values=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("values()",arguments,0,0,!1,!0);var b,c,d=[];c=Sk.abstr.iter(a);for(b=c.tp$iternext();void 0!==b;b=c.tp$iternext())b=a.mp$subscript(b),void 0===b&&(b=null),d.push(b);return new Sk.builtin.list(d)});
Sk.builtin.dict.prototype.clear=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("clear()",arguments,0,0,!1,!0);var b,c;c=Sk.abstr.iter(a);for(b=c.tp$iternext();void 0!==b;b=c.tp$iternext())a.mp$del_subscript(b)});Sk.builtin.dict.prototype.setdefault=new Sk.builtin.func(function(a,b,c){try{return a.mp$subscript(b)}catch(d){return void 0===c&&(c=Sk.builtin.none.none$),a.mp$ass_subscript(b,c),c}});
Sk.builtin.dict.prototype.dict_merge=function(a){var b,c,d;if(a instanceof Sk.builtin.dict)for(b=a.tp$iter(),c=b.tp$iternext();void 0!==c;c=b.tp$iternext()){d=a.mp$subscript(c);if(void 0===d)throw new Sk.builtin.AttributeError("cannot get item for key: "+c.v);this.mp$ass_subscript(c,d)}else for(b=Sk.misceval.callsim(a.keys,a),b=Sk.abstr.iter(b),c=b.tp$iternext();void 0!==c;c=b.tp$iternext()){d=a.tp$getitem(c);if(void 0===d)throw new Sk.builtin.AttributeError("cannot get item for key: "+c.v);this.mp$ass_subscript(c,
d)}};
var update_f=function(a,b,c){if(void 0!==c&&("dict"===c.tp$name||c.keys))b.dict_merge(c);else if(void 0!==c&&Sk.builtin.checkIterable(c)){var d,e=0;c=Sk.abstr.iter(c);for(d=c.tp$iternext();void 0!==d;d=c.tp$iternext(),e++){if(!Sk.builtin.checkIterable(d))throw new Sk.builtin.TypeError("cannot convert dictionary update sequence element #"+e+" to a sequence");if(2===d.sq$length()){var f=Sk.abstr.iter(d);d=f.tp$iternext();f=f.tp$iternext();b.mp$ass_subscript(d,f)}else throw new Sk.builtin.ValueError("dictionary update sequence element #"+e+
" has length "+d.sq$length()+"; 2 is required");}}else if(void 0!==c)throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(c)+"' object is not iterable");a=new Sk.builtins.dict(a);b.dict_merge(a);return Sk.builtin.none.none$};update_f.co_kwargs=!0;Sk.builtin.dict.prototype.update=new Sk.builtin.func(update_f);Sk.builtin.dict.prototype.__contains__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__contains__",arguments,1,1,!1,!0);return Sk.builtin.dict.prototype.sq$contains.call(a,b)});
Sk.builtin.dict.prototype.__cmp__=new Sk.builtin.func(function(a,b,c){return Sk.builtin.NotImplemented.NotImplemented$});Sk.builtin.dict.prototype.__delitem__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__delitem__",arguments,1,1,!1,!0);return Sk.builtin.dict.prototype.mp$del_subscript.call(a,b)});Sk.builtin.dict.prototype.__getitem__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__getitem__",arguments,1,1,!1,!0);return Sk.builtin.dict.prototype.mp$subscript.call(a,b)});
Sk.builtin.dict.prototype.__setitem__=new Sk.builtin.func(function(a,b,c){Sk.builtin.pyCheckArgs("__setitem__",arguments,2,2,!1,!0);return Sk.builtin.dict.prototype.mp$ass_subscript.call(a,b,c)});Sk.builtin.dict.prototype.__hash__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__hash__",arguments,0,0,!1,!0);return Sk.builtin.dict.prototype.tp$hash.call(a)});Sk.builtin.dict.prototype.__len__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__len__",arguments,0,0,!1,!0);return Sk.builtin.dict.prototype.mp$length.call(a)});
Sk.builtin.dict.prototype.__getattr__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__getattr__",arguments,1,1,!1,!0);return Sk.builtin.dict.prototype.tp$getattr.call(a,b)});Sk.builtin.dict.prototype.__iter__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__iter__",arguments,0,0,!1,!0);return Sk.builtin.dict.prototype.tp$iter.call(a)});Sk.builtin.dict.prototype.__repr__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__repr__",arguments,0,0,!1,!0);return Sk.builtin.dict.prototype.$r.call(a)});
Sk.builtin.dict.prototype.ob$eq=function(a){var b,c,d;if(this===a)return Sk.builtin.bool.true$;if(!(a instanceof Sk.builtin.dict))return Sk.builtin.NotImplemented.NotImplemented$;if(this.size!==a.size)return Sk.builtin.bool.false$;b=this.tp$iter();for(c=b.tp$iternext();void 0!==c;c=b.tp$iternext())if(d=this.mp$subscript(c),c=a.mp$subscript(c),!Sk.misceval.richCompareBool(d,c,"Eq"))return Sk.builtin.bool.false$;return Sk.builtin.bool.true$};
Sk.builtin.dict.prototype.ob$ne=function(a){a=this.ob$eq(a);return a instanceof Sk.builtin.NotImplemented?a:a.v?Sk.builtin.bool.false$:Sk.builtin.bool.true$};Sk.builtin.dict.prototype.copy=new Sk.builtin.func(function(a){throw new Sk.builtin.NotImplementedError("dict.copy is not yet implemented in Skulpt");});Sk.builtin.dict.prototype.fromkeys=new Sk.builtin.func(function(a,b){throw new Sk.builtin.NotImplementedError("dict.fromkeys is not yet implemented in Skulpt");});
Sk.builtin.dict.prototype.iteritems=new Sk.builtin.func(function(a){throw new Sk.builtin.NotImplementedError("dict.iteritems is not yet implemented in Skulpt");});Sk.builtin.dict.prototype.iterkeys=new Sk.builtin.func(function(a){throw new Sk.builtin.NotImplementedError("dict.iterkeys is not yet implemented in Skulpt");});Sk.builtin.dict.prototype.itervalues=new Sk.builtin.func(function(a){throw new Sk.builtin.NotImplementedError("dict.itervalues is not yet implemented in Skulpt");});
Sk.builtin.dict.prototype.popitem=new Sk.builtin.func(function(a){throw new Sk.builtin.NotImplementedError("dict.popitem is not yet implemented in Skulpt");});Sk.builtin.dict.prototype.viewitems=new Sk.builtin.func(function(a){throw new Sk.builtin.NotImplementedError("dict.viewitems is not yet implemented in Skulpt");});Sk.builtin.dict.prototype.viewkeys=new Sk.builtin.func(function(a){throw new Sk.builtin.NotImplementedError("dict.viewkeys is not yet implemented in Skulpt");});
Sk.builtin.dict.prototype.viewvalues=new Sk.builtin.func(function(a){throw new Sk.builtin.NotImplementedError("dict.viewvalues is not yet implemented in Skulpt");});goog.exportSymbol("Sk.builtin.dict",Sk.builtin.dict);Sk.builtin.numtype=function(){throw new Sk.builtin.ExternalError("Cannot instantiate abstract Sk.builtin.numtype class");};Sk.abstr.setUpInheritance("NumericType",Sk.builtin.numtype,Sk.builtin.object);Sk.builtin.numtype.sk$abstract=!0;Sk.builtin.numtype.prototype.__abs__=new Sk.builtin.func(function(a){if(void 0===a.nb$abs)throw new Sk.builtin.NotImplementedError("__abs__ is not yet implemented");Sk.builtin.pyCheckArgs("__abs__",arguments,0,0,!1,!0);return a.nb$abs()});
Sk.builtin.numtype.prototype.__neg__=new Sk.builtin.func(function(a){if(void 0===a.nb$negative)throw new Sk.builtin.NotImplementedError("__neg__ is not yet implemented");Sk.builtin.pyCheckArgs("__neg__",arguments,0,0,!1,!0);return a.nb$negative()});Sk.builtin.numtype.prototype.__pos__=new Sk.builtin.func(function(a){if(void 0===a.nb$positive)throw new Sk.builtin.NotImplementedError("__pos__ is not yet implemented");Sk.builtin.pyCheckArgs("__pos__",arguments,0,0,!1,!0);return a.nb$positive()});
Sk.builtin.numtype.prototype.__int__=new Sk.builtin.func(function(a){if(void 0===a.nb$int_)throw new Sk.builtin.NotImplementedError("__int__ is not yet implemented");Sk.builtin.pyCheckArgs("__int__",arguments,0,0,!1,!0);return a.nb$int_()});Sk.builtin.numtype.prototype.__long__=new Sk.builtin.func(function(a){if(void 0===a.nb$lng)throw new Sk.builtin.NotImplementedError("__long__ is not yet implemented");Sk.builtin.pyCheckArgs("__long__",arguments,0,0,!1,!0);return a.nb$lng()});
Sk.builtin.numtype.prototype.__float__=new Sk.builtin.func(function(a){if(void 0===a.nb$float_)throw new Sk.builtin.NotImplementedError("__float__ is not yet implemented");Sk.builtin.pyCheckArgs("__float__",arguments,0,0,!1,!0);return a.nb$float_()});Sk.builtin.numtype.prototype.__add__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$add)throw new Sk.builtin.NotImplementedError("__add__ is not yet implemented");Sk.builtin.pyCheckArgs("__add__",arguments,1,1,!1,!0);return a.nb$add(b)});
Sk.builtin.numtype.prototype.__radd__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$reflected_add)throw new Sk.builtin.NotImplementedError("__radd__ is not yet implemented");Sk.builtin.pyCheckArgs("__radd__",arguments,1,1,!1,!0);return a.nb$reflected_add(b)});Sk.builtin.numtype.prototype.__sub__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$subtract)throw new Sk.builtin.NotImplementedError("__sub__ is not yet implemented");Sk.builtin.pyCheckArgs("__sub__",arguments,1,1,!1,!0);return a.nb$subtract(b)});
Sk.builtin.numtype.prototype.__rsub__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$reflected_subtract)throw new Sk.builtin.NotImplementedError("__rsub__ is not yet implemented");Sk.builtin.pyCheckArgs("__rsub__",arguments,1,1,!1,!0);return a.nb$reflected_subtract(b)});
Sk.builtin.numtype.prototype.__mul__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$multiply)throw new Sk.builtin.NotImplementedError("__mul__ is not yet implemented");Sk.builtin.pyCheckArgs("__mul__",arguments,1,1,!1,!0);return a.nb$multiply(b)});Sk.builtin.numtype.prototype.__rmul__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$reflected_multiply)throw new Sk.builtin.NotImplementedError("__rmul__ is not yet implemented");Sk.builtin.pyCheckArgs("__rmul__",arguments,1,1,!1,!0);return a.nb$reflected_multiply(b)});
Sk.builtin.numtype.prototype.__div__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$divide)throw new Sk.builtin.NotImplementedError("__div__ is not yet implemented");Sk.builtin.pyCheckArgs("__div__",arguments,1,1,!1,!0);return a.nb$divide(b)});Sk.builtin.numtype.prototype.__rdiv__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$reflected_divide)throw new Sk.builtin.NotImplementedError("__rdiv__ is not yet implemented");Sk.builtin.pyCheckArgs("__rdiv__",arguments,1,1,!1,!0);return a.nb$reflected_divide(b)});
Sk.builtin.numtype.prototype.__floordiv__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$floor_divide)throw new Sk.builtin.NotImplementedError("__floordiv__ is not yet implemented");Sk.builtin.pyCheckArgs("__floordiv__",arguments,1,1,!1,!0);return a.nb$floor_divide(b)});
Sk.builtin.numtype.prototype.__rfloordiv__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$reflected_floor_divide)throw new Sk.builtin.NotImplementedError("__rfloordiv__ is not yet implemented");Sk.builtin.pyCheckArgs("__rfloordiv__",arguments,1,1,!1,!0);return a.nb$reflected_floor_divide(b)});
Sk.builtin.numtype.prototype.__mod__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$remainder)throw new Sk.builtin.NotImplementedError("__mod__ is not yet implemented");Sk.builtin.pyCheckArgs("__mod__",arguments,1,1,!1,!0);return a.nb$remainder(b)});Sk.builtin.numtype.prototype.__rmod__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$reflected_remainder)throw new Sk.builtin.NotImplementedError("__rmod__ is not yet implemented");Sk.builtin.pyCheckArgs("__rmod__",arguments,1,1,!1,!0);return a.nb$reflected_remainder(b)});
Sk.builtin.numtype.prototype.__divmod__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$divmod)throw new Sk.builtin.NotImplementedError("__divmod__ is not yet implemented");Sk.builtin.pyCheckArgs("__divmod__",arguments,1,1,!1,!0);return a.nb$divmod(b)});
Sk.builtin.numtype.prototype.__rdivmod__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$reflected_divmod)throw new Sk.builtin.NotImplementedError("__rdivmod__ is not yet implemented");Sk.builtin.pyCheckArgs("__rdivmod__",arguments,1,1,!1,!0);return a.nb$reflected_divmod(b)});
Sk.builtin.numtype.prototype.__pow__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$power)throw new Sk.builtin.NotImplementedError("__pow__ is not yet implemented");Sk.builtin.pyCheckArgs("__pow__",arguments,1,1,!1,!0);return a.nb$power(b)});Sk.builtin.numtype.prototype.__rpow__=new Sk.builtin.func(function(a,b){if(void 0===a.nb$reflected_power)throw new Sk.builtin.NotImplementedError("__rpow__ is not yet implemented");Sk.builtin.pyCheckArgs("__rpow__",arguments,1,1,!1,!0);return a.nb$reflected_power(b)});
Sk.builtin.numtype.prototype.__coerce__=new Sk.builtin.func(function(a,b){throw new Sk.builtin.NotImplementedError("__coerce__ is not yet implemented");});Sk.builtin.numtype.prototype.nb$add=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$reflected_add=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$inplace_add=function(a){return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.numtype.prototype.nb$subtract=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$reflected_subtract=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$inplace_subtract=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$multiply=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$reflected_multiply=function(a){return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.numtype.prototype.nb$inplace_multiply=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$divide=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$reflected_divide=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$inplace_divide=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$floor_divide=function(a){return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.numtype.prototype.nb$reflected_floor_divide=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$inplace_floor_divide=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$remainder=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$reflected_remainder=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$inplace_remainder=function(a){return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.numtype.prototype.nb$divmod=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$reflected_divmod=function(a){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$power=function(a,b){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$reflected_power=function(a,b){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$inplace_power=function(a){return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.numtype.prototype.nb$abs=function(){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$negative=function(){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$positive=function(){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$nonzero=function(){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.numtype.prototype.nb$isnegative=function(){return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.numtype.prototype.nb$ispositive=function(){return Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.biginteger=function(a,b,c){null!=a&&("number"==typeof a?this.fromNumber(a,b,c):null==b&&"string"!=typeof a?this.fromString(a,256):this.fromString(a,b))};Sk.builtin.biginteger.canary=0xdeadbeefcafe;Sk.builtin.biginteger.j_lm=15715070==(Sk.builtin.biginteger.canary&16777215);Sk.builtin.biginteger.nbi=function(){return new Sk.builtin.biginteger(null)};
Sk.builtin.biginteger.prototype.am1=function(a,b,c,d,e,f){for(var g;0<=--f;)g=b*this[a++]+c[d]+e,e=Math.floor(g/67108864),c[d++]=g&67108863;return e};Sk.builtin.biginteger.prototype.am2=function(a,b,c,d,e,f){for(var g,h,k=b&32767,l=b>>15;0<=--f;)h=this[a]&32767,g=this[a++]>>15,b=l*h+g*k,h=k*h+((b&32767)<<15)+c[d]+(e&1073741823),e=(h>>>30)+(b>>>15)+l*g+(e>>>30),c[d++]=h&1073741823;return e};
Sk.builtin.biginteger.prototype.am3=function(a,b,c,d,e,f){for(var g,h,k=b&16383,l=b>>14;0<=--f;)h=this[a]&16383,g=this[a++]>>14,b=l*h+g*k,h=k*h+((b&16383)<<14)+c[d]+e,e=(h>>28)+(b>>14)+l*g,c[d++]=h&268435455;return e};Sk.builtin.biginteger.prototype.am=Sk.builtin.biginteger.prototype.am3;Sk.builtin.biginteger.dbits=28;Sk.builtin.biginteger.prototype.DB=Sk.builtin.biginteger.dbits;Sk.builtin.biginteger.prototype.DM=(1<<Sk.builtin.biginteger.dbits)-1;Sk.builtin.biginteger.prototype.DV=1<<Sk.builtin.biginteger.dbits;
Sk.builtin.biginteger.BI_FP=52;Sk.builtin.biginteger.prototype.FV=Math.pow(2,Sk.builtin.biginteger.BI_FP);Sk.builtin.biginteger.prototype.F1=Sk.builtin.biginteger.BI_FP-Sk.builtin.biginteger.dbits;Sk.builtin.biginteger.prototype.F2=2*Sk.builtin.biginteger.dbits-Sk.builtin.biginteger.BI_FP;Sk.builtin.biginteger.BI_RM="0123456789abcdefghijklmnopqrstuvwxyz";Sk.builtin.biginteger.BI_RC=[];var rr,vv;rr=48;for(vv=0;9>=vv;++vv)Sk.builtin.biginteger.BI_RC[rr++]=vv;rr=97;
for(vv=10;36>vv;++vv)Sk.builtin.biginteger.BI_RC[rr++]=vv;rr=65;for(vv=10;36>vv;++vv)Sk.builtin.biginteger.BI_RC[rr++]=vv;Sk.builtin.biginteger.int2char=function(a){return Sk.builtin.biginteger.BI_RM.charAt(a)};Sk.builtin.biginteger.intAt=function(a,b){var c=Sk.builtin.biginteger.BI_RC[a.charCodeAt(b)];return null==c?-1:c};Sk.builtin.biginteger.prototype.bnpCopyTo=function(a){var b;for(b=this.t-1;0<=b;--b)a[b]=this[b];a.t=this.t;a.s=this.s};
Sk.builtin.biginteger.prototype.bnpFromInt=function(a){this.t=1;this.s=0>a?-1:0;0<a?this[0]=a:-1>a?this[0]=a+this.DV:this.t=0};Sk.builtin.biginteger.nbv=function(a){var b=new Sk.builtin.biginteger(null);b.bnpFromInt(a);return b};
Sk.builtin.biginteger.prototype.bnpFromString=function(a,b){var c,d,e,f,g;if(16==b)g=4;else if(8==b)g=3;else if(256==b)g=8;else if(2==b)g=1;else if(32==b)g=5;else if(4==b)g=2;else{this.fromRadix(a,b);return}this.s=this.t=0;d=a.length;e=!1;for(f=0;0<=--d;)c=8==g?a[d]&255:Sk.builtin.biginteger.intAt(a,d),0>c?"-"==a.charAt(d)&&(e=!0):(e=!1,0===f?this[this.t++]=c:f+g>this.DB?(this[this.t-1]|=(c&(1<<this.DB-f)-1)<<f,this[this.t++]=c>>this.DB-f):this[this.t-1]|=c<<f,f+=g,f>=this.DB&&(f-=this.DB));8==g&&
0!==(a[0]&128)&&(this.s=-1,0<f&&(this[this.t-1]|=(1<<this.DB-f)-1<<f));this.clamp();e&&Sk.builtin.biginteger.ZERO.subTo(this,this)};Sk.builtin.biginteger.prototype.bnpClamp=function(){for(var a=this.s&this.DM;0<this.t&&this[this.t-1]==a;)--this.t};
Sk.builtin.biginteger.prototype.bnToString=function(a){var b,c,d,e,f,g;if(0>this.s)return"-"+this.negate().toString(a);if(16==a)g=4;else if(8==a)g=3;else if(2==a)g=1;else if(32==a)g=5;else if(4==a)g=2;else return this.toRadix(a);b=(1<<g)-1;d=!1;e="";f=this.t;a=this.DB-f*this.DB%g;if(0<f--)for(a<this.DB&&0<(c=this[f]>>a)&&(d=!0,e=Sk.builtin.biginteger.int2char(c));0<=f;)a<g?(c=(this[f]&(1<<a)-1)<<g-a,c|=this[--f]>>(a+=this.DB-g)):(c=this[f]>>(a-=g)&b,0>=a&&(a+=this.DB,--f)),0<c&&(d=!0),d&&(e+=Sk.builtin.biginteger.int2char(c));
return d?e:"0"};Sk.builtin.biginteger.prototype.bnNegate=function(){var a=Sk.builtin.biginteger.nbi();Sk.builtin.biginteger.ZERO.subTo(this,a);return a};Sk.builtin.biginteger.prototype.bnAbs=function(){return 0>this.s?this.negate():this};Sk.builtin.biginteger.prototype.bnCompareTo=function(a){var b,c=this.s-a.s;if(0!==c)return c;b=this.t;c=b-a.t;if(0!==c)return 0>this.s?-c:c;for(;0<=--b;)if(0!==(c=this[b]-a[b]))return c;return 0};
Sk.builtin.biginteger.nbits=function(a){var b=1,c;0!==(c=a>>>16)&&(a=c,b+=16);0!==(c=a>>8)&&(a=c,b+=8);0!==(c=a>>4)&&(a=c,b+=4);0!==(c=a>>2)&&(a=c,b+=2);0!==a>>1&&(b+=1);return b};Sk.builtin.biginteger.prototype.bnBitLength=function(){return 0>=this.t?0:this.DB*(this.t-1)+Sk.builtin.biginteger.nbits(this[this.t-1]^this.s&this.DM)};Sk.builtin.biginteger.prototype.bnpDLShiftTo=function(a,b){var c;for(c=this.t-1;0<=c;--c)b[c+a]=this[c];for(c=a-1;0<=c;--c)b[c]=0;b.t=this.t+a;b.s=this.s};
Sk.builtin.biginteger.prototype.bnpDRShiftTo=function(a,b){var c;for(c=a;c<this.t;++c)b[c-a]=this[c];b.t=Math.max(this.t-a,0);b.s=this.s};Sk.builtin.biginteger.prototype.bnpLShiftTo=function(a,b){var c=a%this.DB,d=this.DB-c,e=(1<<d)-1,f=Math.floor(a/this.DB),g=this.s<<c&this.DM,h;for(h=this.t-1;0<=h;--h)b[h+f+1]=this[h]>>d|g,g=(this[h]&e)<<c;for(h=f-1;0<=h;--h)b[h]=0;b[f]=g;b.t=this.t+f+1;b.s=this.s;b.clamp()};
Sk.builtin.biginteger.prototype.bnpRShiftTo=function(a,b){var c,d,e,f,g;b.s=this.s;g=Math.floor(a/this.DB);if(g>=this.t)b.t=0;else{f=a%this.DB;e=this.DB-f;d=(1<<f)-1;b[0]=this[g]>>f;for(c=g+1;c<this.t;++c)b[c-g-1]|=(this[c]&d)<<e,b[c-g]=this[c]>>f;0<f&&(b[this.t-g-1]|=(this.s&d)<<e);b.t=this.t-g;b.clamp()}};
Sk.builtin.biginteger.prototype.bnpSubTo=function(a,b){for(var c=0,d=0,e=Math.min(a.t,this.t);c<e;)d+=this[c]-a[c],b[c++]=d&this.DM,d>>=this.DB;if(a.t<this.t){for(d-=a.s;c<this.t;)d+=this[c],b[c++]=d&this.DM,d>>=this.DB;d+=this.s}else{for(d+=this.s;c<a.t;)d-=a[c],b[c++]=d&this.DM,d>>=this.DB;d-=a.s}b.s=0>d?-1:0;-1>d?b[c++]=this.DV+d:0<d&&(b[c++]=d);b.t=c;b.clamp()};
Sk.builtin.biginteger.prototype.bnpMultiplyTo=function(a,b){var c=this.abs(),d=a.abs(),e=c.t;for(b.t=e+d.t;0<=--e;)b[e]=0;for(e=0;e<d.t;++e)b[e+c.t]=c.am(0,d[e],b,e,0,c.t);b.s=0;b.clamp();this.s!=a.s&&Sk.builtin.biginteger.ZERO.subTo(b,b)};
Sk.builtin.biginteger.prototype.bnpSquareTo=function(a){for(var b,c=this.abs(),d=a.t=2*c.t;0<=--d;)a[d]=0;for(d=0;d<c.t-1;++d)b=c.am(d,c[d],a,2*d,0,1),(a[d+c.t]+=c.am(d+1,2*c[d],a,2*d+1,b,c.t-d-1))>=c.DV&&(a[d+c.t]-=c.DV,a[d+c.t+1]=1);0<a.t&&(a[a.t-1]+=c.am(d,c[d],a,2*d,0,1));a.s=0;a.clamp()};
Sk.builtin.biginteger.prototype.bnpDivRemTo=function(a,b,c){var d,e,f,g,h,k,l,m,q,n,r,p;m=a.abs();if(!(0>=m.t))if(h=this.abs(),h.t<m.t)null!=b&&b.fromInt(0),null!=c&&this.copyTo(c);else if(null==c&&(c=Sk.builtin.biginteger.nbi()),n=Sk.builtin.biginteger.nbi(),r=this.s,p=a.s,a=this.DB-Sk.builtin.biginteger.nbits(m[m.t-1]),0<a?(m.lShiftTo(a,n),h.lShiftTo(a,c)):(m.copyTo(n),h.copyTo(c)),q=n.t,m=n[q-1],0!==m){d=m*(1<<this.F1)+(1<q?n[q-2]>>this.F2:0);h=this.FV/d;k=(1<<this.F1)/d;l=1<<this.F2;e=c.t;f=e-
q;g=null==b?Sk.builtin.biginteger.nbi():b;n.dlShiftTo(f,g);0<=c.compareTo(g)&&(c[c.t++]=1,c.subTo(g,c));Sk.builtin.biginteger.ONE.dlShiftTo(q,g);for(g.subTo(n,n);n.t<q;)n[n.t++]=0;for(;0<=--f;)if(d=c[--e]==m?this.DM:Math.floor(c[e]*h+(c[e-1]+l)*k),(c[e]+=n.am(0,d,c,f,0,q))<d)for(n.dlShiftTo(f,g),c.subTo(g,c);c[e]<--d;)c.subTo(g,c);null!=b&&(c.drShiftTo(q,b),r!=p&&Sk.builtin.biginteger.ZERO.subTo(b,b));c.t=q;c.clamp();0<a&&c.rShiftTo(a,c);0>r&&Sk.builtin.biginteger.ZERO.subTo(c,c)}};
Sk.builtin.biginteger.prototype.bnMod=function(a){var b=Sk.builtin.biginteger.nbi();this.abs().divRemTo(a,null,b);0>this.s&&0<b.compareTo(Sk.builtin.biginteger.ZERO)&&a.subTo(b,b);return b};Sk.builtin.biginteger.Classic=function(a){this.m=a};Sk.builtin.biginteger.prototype.cConvert=function(a){return 0>a.s||0<=a.compareTo(this.m)?a.mod(this.m):a};Sk.builtin.biginteger.prototype.cRevert=function(a){return a};Sk.builtin.biginteger.prototype.cReduce=function(a){a.divRemTo(this.m,null,a)};
Sk.builtin.biginteger.prototype.cMulTo=function(a,b,c){a.multiplyTo(b,c);this.reduce(c)};Sk.builtin.biginteger.prototype.cSqrTo=function(a,b){a.squareTo(b);this.reduce(b)};Sk.builtin.biginteger.Classic.prototype.convert=Sk.builtin.biginteger.prototype.cConvert;Sk.builtin.biginteger.Classic.prototype.revert=Sk.builtin.biginteger.prototype.cRevert;Sk.builtin.biginteger.Classic.prototype.reduce=Sk.builtin.biginteger.prototype.cReduce;Sk.builtin.biginteger.Classic.prototype.mulTo=Sk.builtin.biginteger.prototype.cMulTo;
Sk.builtin.biginteger.Classic.prototype.sqrTo=Sk.builtin.biginteger.prototype.cSqrTo;Sk.builtin.biginteger.prototype.bnpInvDigit=function(){var a,b;if(1>this.t)return 0;b=this[0];if(0===(b&1))return 0;a=b&3;a=a*(2-(b&15)*a)&15;a=a*(2-(b&255)*a)&255;a=a*(2-((b&65535)*a&65535))&65535;a=a*(2-b*a%this.DV)%this.DV;return 0<a?this.DV-a:-a};Sk.builtin.biginteger.Montgomery=function(a){this.m=a;this.mp=a.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<a.DB-15)-1;this.mt2=2*a.t};
Sk.builtin.biginteger.prototype.montConvert=function(a){var b=Sk.builtin.biginteger.nbi();a.abs().dlShiftTo(this.m.t,b);b.divRemTo(this.m,null,b);0>a.s&&0<b.compareTo(Sk.builtin.biginteger.ZERO)&&this.m.subTo(b,b);return b};Sk.builtin.biginteger.prototype.montRevert=function(a){var b=Sk.builtin.biginteger.nbi();a.copyTo(b);this.reduce(b);return b};
Sk.builtin.biginteger.prototype.montReduce=function(a){for(var b,c,d;a.t<=this.mt2;)a[a.t++]=0;for(d=0;d<this.m.t;++d)for(c=a[d]&32767,b=c*this.mpl+((c*this.mph+(a[d]>>15)*this.mpl&this.um)<<15)&a.DM,c=d+this.m.t,a[c]+=this.m.am(0,b,a,d,0,this.m.t);a[c]>=a.DV;)a[c]-=a.DV,a[++c]++;a.clamp();a.drShiftTo(this.m.t,a);0<=a.compareTo(this.m)&&a.subTo(this.m,a)};Sk.builtin.biginteger.prototype.montSqrTo=function(a,b){a.squareTo(b);this.reduce(b)};
Sk.builtin.biginteger.prototype.montMulTo=function(a,b,c){a.multiplyTo(b,c);this.reduce(c)};Sk.builtin.biginteger.Montgomery.prototype.convert=Sk.builtin.biginteger.prototype.montConvert;Sk.builtin.biginteger.Montgomery.prototype.revert=Sk.builtin.biginteger.prototype.montRevert;Sk.builtin.biginteger.Montgomery.prototype.reduce=Sk.builtin.biginteger.prototype.montReduce;Sk.builtin.biginteger.Montgomery.prototype.mulTo=Sk.builtin.biginteger.prototype.montMulTo;
Sk.builtin.biginteger.Montgomery.prototype.sqrTo=Sk.builtin.biginteger.prototype.montSqrTo;Sk.builtin.biginteger.prototype.bnpIsEven=function(){return 0===(0<this.t?this[0]&1:this.s)};Sk.builtin.biginteger.prototype.bnpExp=function(a,b){var c,d,e,f,g;if(4294967295<a||1>a)return Sk.builtin.biginteger.ONE;d=Sk.builtin.biginteger.nbi();e=Sk.builtin.biginteger.nbi();f=b.convert(this);g=Sk.builtin.biginteger.nbits(a)-1;for(f.copyTo(d);0<=--g;)b.sqrTo(d,e),0<(a&1<<g)?b.mulTo(e,f,d):(c=d,d=e,e=c);return b.revert(d)};
Sk.builtin.biginteger.prototype.bnModPowInt=function(a,b){var c;c=256>a||b.isEven()?new Sk.builtin.biginteger.Classic(b):new Sk.builtin.biginteger.Montgomery(b);return this.exp(a,c)};Sk.builtin.biginteger.prototype.copyTo=Sk.builtin.biginteger.prototype.bnpCopyTo;Sk.builtin.biginteger.prototype.fromInt=Sk.builtin.biginteger.prototype.bnpFromInt;Sk.builtin.biginteger.prototype.fromString=Sk.builtin.biginteger.prototype.bnpFromString;Sk.builtin.biginteger.prototype.clamp=Sk.builtin.biginteger.prototype.bnpClamp;
Sk.builtin.biginteger.prototype.dlShiftTo=Sk.builtin.biginteger.prototype.bnpDLShiftTo;Sk.builtin.biginteger.prototype.drShiftTo=Sk.builtin.biginteger.prototype.bnpDRShiftTo;Sk.builtin.biginteger.prototype.lShiftTo=Sk.builtin.biginteger.prototype.bnpLShiftTo;Sk.builtin.biginteger.prototype.rShiftTo=Sk.builtin.biginteger.prototype.bnpRShiftTo;Sk.builtin.biginteger.prototype.subTo=Sk.builtin.biginteger.prototype.bnpSubTo;Sk.builtin.biginteger.prototype.multiplyTo=Sk.builtin.biginteger.prototype.bnpMultiplyTo;
Sk.builtin.biginteger.prototype.squareTo=Sk.builtin.biginteger.prototype.bnpSquareTo;Sk.builtin.biginteger.prototype.divRemTo=Sk.builtin.biginteger.prototype.bnpDivRemTo;Sk.builtin.biginteger.prototype.invDigit=Sk.builtin.biginteger.prototype.bnpInvDigit;Sk.builtin.biginteger.prototype.isEven=Sk.builtin.biginteger.prototype.bnpIsEven;Sk.builtin.biginteger.prototype.exp=Sk.builtin.biginteger.prototype.bnpExp;Sk.builtin.biginteger.prototype.toString=Sk.builtin.biginteger.prototype.bnToString;
Sk.builtin.biginteger.prototype.negate=Sk.builtin.biginteger.prototype.bnNegate;Sk.builtin.biginteger.prototype.abs=Sk.builtin.biginteger.prototype.bnAbs;Sk.builtin.biginteger.prototype.compareTo=Sk.builtin.biginteger.prototype.bnCompareTo;Sk.builtin.biginteger.prototype.bitLength=Sk.builtin.biginteger.prototype.bnBitLength;Sk.builtin.biginteger.prototype.mod=Sk.builtin.biginteger.prototype.bnMod;Sk.builtin.biginteger.prototype.modPowInt=Sk.builtin.biginteger.prototype.bnModPowInt;
Sk.builtin.biginteger.ZERO=Sk.builtin.biginteger.nbv(0);Sk.builtin.biginteger.ONE=Sk.builtin.biginteger.nbv(1);Sk.builtin.biginteger.prototype.bnClone=function(){var a=Sk.builtin.biginteger.nbi();this.copyTo(a);return a};Sk.builtin.biginteger.prototype.bnIntValue=function(){if(0>this.s){if(1==this.t)return this[0]-this.DV;if(0===this.t)return-1}else{if(1==this.t)return this[0];if(0===this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]};
Sk.builtin.biginteger.prototype.bnByteValue=function(){return 0===this.t?this.s:this[0]<<24>>24};Sk.builtin.biginteger.prototype.bnShortValue=function(){return 0===this.t?this.s:this[0]<<16>>16};Sk.builtin.biginteger.prototype.bnpChunkSize=function(a){return Math.floor(Math.LN2*this.DB/Math.log(a))};Sk.builtin.biginteger.prototype.bnSigNum=function(){return 0>this.s?-1:0>=this.t||1==this.t&&0>=this[0]?0:1};
Sk.builtin.biginteger.prototype.bnpToRadix=function(a){var b,c,d,e,f;null==a&&(a=10);if(0===this.signum()||2>a||36<a)return"0";b=this.chunkSize(a);f=Math.pow(a,b);b=Sk.builtin.biginteger.nbv(f);c=Sk.builtin.biginteger.nbi();d=Sk.builtin.biginteger.nbi();e="";for(this.divRemTo(b,c,d);0<c.signum();)e=(f+d.intValue()).toString(a).substr(1)+e,c.divRemTo(b,c,d);return d.intValue().toString(a)+e};
Sk.builtin.biginteger.prototype.bnpFromRadix=function(a,b){var c,d,e,f,g,h,k;this.fromInt(0);null==b&&(b=10);k=this.chunkSize(b);e=Math.pow(b,k);f=!1;for(d=h=g=0;d<a.length;++d)if(c=Sk.builtin.biginteger.intAt(a,d),0>c){if("-"==a.charAt(d)&&0===this.signum()&&(f=!0),"."==a.charAt(d))break}else h=b*h+c,++g>=k&&(this.dMultiply(e),this.dAddOffset(h,0),h=g=0);0<g&&(this.dMultiply(Math.pow(b,g)),this.dAddOffset(h,0));f&&Sk.builtin.biginteger.ZERO.subTo(this,this)};
Sk.builtin.biginteger.prototype.bnpFromNumber=function(a,b,c){if("number"==typeof b)if(2>a)this.fromInt(1);else for(this.fromNumber(a,c),this.testBit(a-1)||this.bitwiseTo(Sk.builtin.biginteger.ONE.shiftLeft(a-1),Sk.builtin.biginteger.op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(b);)this.dAddOffset(2,0),this.bitLength()>a&&this.subTo(Sk.builtin.biginteger.ONE.shiftLeft(a-1),this);this.fromString(a+"")};
Sk.builtin.biginteger.prototype.bnToByteArray=function(){var a,b,c,d=this.t,e=[];e[0]=this.s;a=this.DB-d*this.DB%8;c=0;if(0<d--)for(a<this.DB&&(b=this[d]>>a)!=(this.s&this.DM)>>a&&(e[c++]=b|this.s<<this.DB-a);0<=d;)if(8>a?(b=(this[d]&(1<<a)-1)<<8-a,b|=this[--d]>>(a+=this.DB-8)):(b=this[d]>>(a-=8)&255,0>=a&&(a+=this.DB,--d)),0!==(b&128)&&(b|=-256),0===c&&(this.s&128)!=(b&128)&&++c,0<c||b!=this.s)e[c++]=b;return e};Sk.builtin.biginteger.prototype.bnEquals=function(a){return 0===this.compareTo(a)};
Sk.builtin.biginteger.prototype.bnMin=function(a){return 0>this.compareTo(a)?this:a};Sk.builtin.biginteger.prototype.bnMax=function(a){return 0<this.compareTo(a)?this:a};Sk.builtin.biginteger.prototype.bnpBitwiseTo=function(a,b,c){var d,e,f=Math.min(a.t,this.t);for(d=0;d<f;++d)c[d]=b(this[d],a[d]);if(a.t<this.t){e=a.s&this.DM;for(d=f;d<this.t;++d)c[d]=b(this[d],e);c.t=this.t}else{e=this.s&this.DM;for(d=f;d<a.t;++d)c[d]=b(e,a[d]);c.t=a.t}c.s=b(this.s,a.s);c.clamp()};
Sk.builtin.biginteger.op_and=function(a,b){return a&b};Sk.builtin.biginteger.prototype.bnAnd=function(a){var b=Sk.builtin.biginteger.nbi();this.bitwiseTo(a,Sk.builtin.biginteger.op_and,b);return b};Sk.builtin.biginteger.op_or=function(a,b){return a|b};Sk.builtin.biginteger.prototype.bnOr=function(a){var b=Sk.builtin.biginteger.nbi();this.bitwiseTo(a,Sk.builtin.biginteger.op_or,b);return b};Sk.builtin.biginteger.op_xor=function(a,b){return a^b};
Sk.builtin.biginteger.prototype.bnXor=function(a){var b=Sk.builtin.biginteger.nbi();this.bitwiseTo(a,Sk.builtin.biginteger.op_xor,b);return b};Sk.builtin.biginteger.op_andnot=function(a,b){return a&~b};Sk.builtin.biginteger.prototype.bnAndNot=function(a){var b=Sk.builtin.biginteger.nbi();this.bitwiseTo(a,Sk.builtin.biginteger.op_andnot,b);return b};
Sk.builtin.biginteger.prototype.bnNot=function(){var a,b=Sk.builtin.biginteger.nbi();for(a=0;a<this.t;++a)b[a]=this.DM&~this[a];b.t=this.t;b.s=~this.s;return b};Sk.builtin.biginteger.prototype.bnShiftLeft=function(a){var b=Sk.builtin.biginteger.nbi();0>a?this.rShiftTo(-a,b):this.lShiftTo(a,b);return b};Sk.builtin.biginteger.prototype.bnShiftRight=function(a){var b=Sk.builtin.biginteger.nbi();0>a?this.lShiftTo(-a,b):this.rShiftTo(a,b);return b};
Sk.builtin.biginteger.lbit=function(a){var b;if(0===a)return-1;b=0;0===(a&65535)&&(a>>=16,b+=16);0===(a&255)&&(a>>=8,b+=8);0===(a&15)&&(a>>=4,b+=4);0===(a&3)&&(a>>=2,b+=2);0===(a&1)&&++b;return b};Sk.builtin.biginteger.prototype.bnGetLowestSetBit=function(){var a;for(a=0;a<this.t;++a)if(0!==this[a])return a*this.DB+Sk.builtin.biginteger.lbit(this[a]);return 0>this.s?this.t*this.DB:-1};Sk.builtin.biginteger.cbit=function(a){for(var b=0;0!==a;)a&=a-1,++b;return b};
Sk.builtin.biginteger.prototype.bnBitCount=function(){var a,b=0,c=this.s&this.DM;for(a=0;a<this.t;++a)b+=Sk.builtin.biginteger.cbit(this[a]^c);return b};Sk.builtin.biginteger.prototype.bnTestBit=function(a){var b=Math.floor(a/this.DB);return b>=this.t?0!==this.s:0!==(this[b]&1<<a%this.DB)};Sk.builtin.biginteger.prototype.bnpChangeBit=function(a,b){var c=Sk.builtin.biginteger.ONE.shiftLeft(a);this.bitwiseTo(c,b,c);return c};
Sk.builtin.biginteger.prototype.bnSetBit=function(a){return this.changeBit(a,Sk.builtin.biginteger.op_or)};Sk.builtin.biginteger.prototype.bnClearBit=function(a){return this.changeBit(a,Sk.builtin.biginteger.op_andnot)};Sk.builtin.biginteger.prototype.bnFlipBit=function(a){return this.changeBit(a,Sk.builtin.biginteger.op_xor)};
Sk.builtin.biginteger.prototype.bnpAddTo=function(a,b){for(var c=0,d=0,e=Math.min(a.t,this.t);c<e;)d+=this[c]+a[c],b[c++]=d&this.DM,d>>=this.DB;if(a.t<this.t){for(d+=a.s;c<this.t;)d+=this[c],b[c++]=d&this.DM,d>>=this.DB;d+=this.s}else{for(d+=this.s;c<a.t;)d+=a[c],b[c++]=d&this.DM,d>>=this.DB;d+=a.s}b.s=0>d?-1:0;0<d?b[c++]=d:-1>d&&(b[c++]=this.DV+d);b.t=c;b.clamp()};Sk.builtin.biginteger.prototype.bnAdd=function(a){var b=Sk.builtin.biginteger.nbi();this.addTo(a,b);return b};
Sk.builtin.biginteger.prototype.bnSubtract=function(a){var b=Sk.builtin.biginteger.nbi();this.subTo(a,b);return b};Sk.builtin.biginteger.prototype.bnMultiply=function(a){var b=Sk.builtin.biginteger.nbi();this.multiplyTo(a,b);return b};Sk.builtin.biginteger.prototype.bnDivide=function(a){var b=Sk.builtin.biginteger.nbi();this.divRemTo(a,b,null);return b};Sk.builtin.biginteger.prototype.bnRemainder=function(a){var b=Sk.builtin.biginteger.nbi();this.divRemTo(a,null,b);return b};
Sk.builtin.biginteger.prototype.bnDivideAndRemainder=function(a){var b=Sk.builtin.biginteger.nbi(),c=Sk.builtin.biginteger.nbi();this.divRemTo(a,b,c);return[b,c]};Sk.builtin.biginteger.prototype.bnpDMultiply=function(a){this[this.t]=this.am(0,a-1,this,0,0,this.t);++this.t;this.clamp()};Sk.builtin.biginteger.prototype.bnpDAddOffset=function(a,b){if(0!==a){for(;this.t<=b;)this[this.t++]=0;for(this[b]+=a;this[b]>=this.DV;)this[b]-=this.DV,++b>=this.t&&(this[this.t++]=0),++this[b]}};
Sk.builtin.biginteger.NullExp=function(){};Sk.builtin.biginteger.prototype.nNop=function(a){return a};Sk.builtin.biginteger.prototype.nMulTo=function(a,b,c){a.multiplyTo(b,c)};Sk.builtin.biginteger.prototype.nSqrTo=function(a,b){a.squareTo(b)};Sk.builtin.biginteger.NullExp.prototype.convert=Sk.builtin.biginteger.prototype.nNop;Sk.builtin.biginteger.NullExp.prototype.revert=Sk.builtin.biginteger.prototype.nNop;Sk.builtin.biginteger.NullExp.prototype.mulTo=Sk.builtin.biginteger.prototype.nMulTo;
Sk.builtin.biginteger.NullExp.prototype.sqrTo=Sk.builtin.biginteger.prototype.nSqrTo;Sk.builtin.biginteger.prototype.bnPow=function(a){return this.exp(a,new Sk.builtin.biginteger.NullExp)};Sk.builtin.biginteger.prototype.bnpMultiplyLowerTo=function(a,b,c){var d,e=Math.min(this.t+a.t,b);c.s=0;for(c.t=e;0<e;)c[--e]=0;for(d=c.t-this.t;e<d;++e)c[e+this.t]=this.am(0,a[e],c,e,0,this.t);for(d=Math.min(a.t,b);e<d;++e)this.am(0,a[e],c,e,0,b-e);c.clamp()};
Sk.builtin.biginteger.prototype.bnpMultiplyUpperTo=function(a,b,c){var d;--b;d=c.t=this.t+a.t-b;for(c.s=0;0<=--d;)c[d]=0;for(d=Math.max(b-this.t,0);d<a.t;++d)c[this.t+d-b]=this.am(b-d,a[d],c,0,0,this.t+d-b);c.clamp();c.drShiftTo(1,c)};Sk.builtin.biginteger.Barrett=function(a){this.r2=Sk.builtin.biginteger.nbi();this.q3=Sk.builtin.biginteger.nbi();Sk.builtin.biginteger.ONE.dlShiftTo(2*a.t,this.r2);this.mu=this.r2.divide(a);this.m=a};
Sk.builtin.biginteger.prototype.barrettConvert=function(a){var b;if(0>a.s||a.t>2*this.m.t)return a.mod(this.m);if(0>a.compareTo(this.m))return a;b=Sk.builtin.biginteger.nbi();a.copyTo(b);this.reduce(b);return b};Sk.builtin.biginteger.prototype.barrettRevert=function(a){return a};
Sk.builtin.biginteger.prototype.barrettReduce=function(a){a.drShiftTo(this.m.t-1,this.r2);a.t>this.m.t+1&&(a.t=this.m.t+1,a.clamp());this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);for(this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);0>a.compareTo(this.r2);)a.dAddOffset(1,this.m.t+1);for(a.subTo(this.r2,a);0<=a.compareTo(this.m);)a.subTo(this.m,a)};Sk.builtin.biginteger.prototype.barrettSqrTo=function(a,b){a.squareTo(b);this.reduce(b)};
Sk.builtin.biginteger.prototype.barrettMulTo=function(a,b,c){a.multiplyTo(b,c);this.reduce(c)};Sk.builtin.biginteger.Barrett.prototype.convert=Sk.builtin.biginteger.prototype.barrettConvert;Sk.builtin.biginteger.Barrett.prototype.revert=Sk.builtin.biginteger.prototype.barrettRevert;Sk.builtin.biginteger.Barrett.prototype.reduce=Sk.builtin.biginteger.prototype.barrettReduce;Sk.builtin.biginteger.Barrett.prototype.mulTo=Sk.builtin.biginteger.prototype.barrettMulTo;
Sk.builtin.biginteger.Barrett.prototype.sqrTo=Sk.builtin.biginteger.prototype.barrettSqrTo;
Sk.builtin.biginteger.prototype.bnModPow=function(a,b){var c,d,e,f,g,h,k,l,m=a.bitLength(),q,n=Sk.builtin.biginteger.nbv(1),r;if(0>=m)return n;q=18>m?1:48>m?3:144>m?4:768>m?5:6;r=8>m?new Sk.builtin.biginteger.Classic(b):b.isEven()?new Sk.builtin.biginteger.Barrett(b):new Sk.builtin.biginteger.Montgomery(b);h=[];g=3;k=q-1;l=(1<<q)-1;h[1]=r.convert(this);if(1<q)for(c=Sk.builtin.biginteger.nbi(),r.sqrTo(h[1],c);g<=l;)h[g]=Sk.builtin.biginteger.nbi(),r.mulTo(c,h[g-2],h[g]),g+=2;c=a.t-1;e=!0;f=Sk.builtin.biginteger.nbi();
for(m=Sk.builtin.biginteger.nbits(a[c])-1;0<=c;){m>=k?d=a[c]>>m-k&l:(d=(a[c]&(1<<m+1)-1)<<k-m,0<c&&(d|=a[c-1]>>this.DB+m-k));for(g=q;0===(d&1);)d>>=1,--g;0>(m-=g)&&(m+=this.DB,--c);if(e)h[d].copyTo(n),e=!1;else{for(;1<g;)r.sqrTo(n,f),r.sqrTo(f,n),g-=2;0<g?r.sqrTo(n,f):(g=n,n=f,f=g);r.mulTo(f,h[d],n)}for(;0<=c&&0===(a[c]&1<<m);)r.sqrTo(n,f),g=n,n=f,f=g,0>--m&&(m=this.DB-1,--c)}return r.revert(n)};
Sk.builtin.biginteger.prototype.bnGCD=function(a){var b,c,d=0>this.s?this.negate():this.clone();a=0>a.s?a.negate():a.clone();0>d.compareTo(a)&&(b=d,d=a,a=b);b=d.getLowestSetBit();c=a.getLowestSetBit();if(0>c)return d;b<c&&(c=b);0<c&&(d.rShiftTo(c,d),a.rShiftTo(c,a));for(;0<d.signum();)0<(b=d.getLowestSetBit())&&d.rShiftTo(b,d),0<(b=a.getLowestSetBit())&&a.rShiftTo(b,a),0<=d.compareTo(a)?(d.subTo(a,d),d.rShiftTo(1,d)):(a.subTo(d,a),a.rShiftTo(1,a));0<c&&a.lShiftTo(c,a);return a};
Sk.builtin.biginteger.prototype.bnpModInt=function(a){var b,c,d;if(0>=a)return 0;c=this.DV%a;d=0>this.s?a-1:0;if(0<this.t)if(0===c)d=this[0]%a;else for(b=this.t-1;0<=b;--b)d=(c*d+this[b])%a;return d};
Sk.builtin.biginteger.prototype.bnModInverse=function(a){var b,c,d,e,f,g,h=a.isEven();if(this.isEven()&&h||0===a.signum())return Sk.builtin.biginteger.ZERO;f=a.clone();g=this.clone();b=Sk.builtin.biginteger.nbv(1);c=Sk.builtin.biginteger.nbv(0);d=Sk.builtin.biginteger.nbv(0);for(e=Sk.builtin.biginteger.nbv(1);0!==f.signum();){for(;f.isEven();)f.rShiftTo(1,f),h?(b.isEven()&&c.isEven()||(b.addTo(this,b),c.subTo(a,c)),b.rShiftTo(1,b)):c.isEven()||c.subTo(a,c),c.rShiftTo(1,c);for(;g.isEven();)g.rShiftTo(1,
g),h?(d.isEven()&&e.isEven()||(d.addTo(this,d),e.subTo(a,e)),d.rShiftTo(1,d)):e.isEven()||e.subTo(a,e),e.rShiftTo(1,e);0<=f.compareTo(g)?(f.subTo(g,f),h&&b.subTo(d,b),c.subTo(e,c)):(g.subTo(f,g),h&&d.subTo(b,d),e.subTo(c,e))}if(0!==g.compareTo(Sk.builtin.biginteger.ONE))return Sk.builtin.biginteger.ZERO;if(0<=e.compareTo(a))return e.subtract(a);if(0>e.signum())e.addTo(a,e);else return e;return 0>e.signum()?e.add(a):e};
Sk.builtin.biginteger.lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];
Sk.builtin.biginteger.lplim=67108864/Sk.builtin.biginteger.lowprimes[Sk.builtin.biginteger.lowprimes.length-1];
Sk.builtin.biginteger.prototype.bnIsProbablePrime=function(a){var b,c,d,e=this.abs();if(1==e.t&&e[0]<=Sk.builtin.biginteger.lowprimes[Sk.builtin.biginteger.lowprimes.length-1]){for(d=0;d<Sk.builtin.biginteger.lowprimes.length;++d)if(e[0]==Sk.builtin.biginteger.lowprimes[d])return!0;return!1}if(e.isEven())return!1;for(d=1;d<Sk.builtin.biginteger.lowprimes.length;){b=Sk.builtin.biginteger.lowprimes[d];for(c=d+1;c<Sk.builtin.biginteger.lowprimes.length&&b<Sk.builtin.biginteger.lplim;)b*=Sk.builtin.biginteger.lowprimes[c++];
for(b=e.modInt(b);d<c;)if(0===b%Sk.builtin.biginteger.lowprimes[d++])return!1}return e.millerRabin(a)};
Sk.builtin.biginteger.prototype.bnpMillerRabin=function(a){var b,c,d,e,f,g=this.subtract(Sk.builtin.biginteger.ONE),h=g.getLowestSetBit();if(0>=h)return!1;f=g.shiftRight(h);a=a+1>>1;a>Sk.builtin.biginteger.lowprimes.length&&(a=Sk.builtin.biginteger.lowprimes.length);e=Sk.builtin.biginteger.nbi();for(d=0;d<a;++d)if(e.fromInt(Sk.builtin.biginteger.lowprimes[d]),c=e.modPow(f,this),0!==c.compareTo(Sk.builtin.biginteger.ONE)&&0!==c.compareTo(g)){for(b=1;b++<h&&0!==c.compareTo(g);)if(c=c.modPowInt(2,this),
0===c.compareTo(Sk.builtin.biginteger.ONE))return!1;if(0!==c.compareTo(g))return!1}return!0};Sk.builtin.biginteger.prototype.isnegative=function(){return 0>this.s};Sk.builtin.biginteger.prototype.ispositive=function(){return 0<=this.s};Sk.builtin.biginteger.prototype.trueCompare=function(a){return 0<=this.s&&0>a.s?1:0>this.s&&0<=a.s?-1:this.compare(a)};Sk.builtin.biginteger.prototype.chunkSize=Sk.builtin.biginteger.prototype.bnpChunkSize;Sk.builtin.biginteger.prototype.toRadix=Sk.builtin.biginteger.prototype.bnpToRadix;
Sk.builtin.biginteger.prototype.fromRadix=Sk.builtin.biginteger.prototype.bnpFromRadix;Sk.builtin.biginteger.prototype.fromNumber=Sk.builtin.biginteger.prototype.bnpFromNumber;Sk.builtin.biginteger.prototype.bitwiseTo=Sk.builtin.biginteger.prototype.bnpBitwiseTo;Sk.builtin.biginteger.prototype.changeBit=Sk.builtin.biginteger.prototype.bnpChangeBit;Sk.builtin.biginteger.prototype.addTo=Sk.builtin.biginteger.prototype.bnpAddTo;Sk.builtin.biginteger.prototype.dMultiply=Sk.builtin.biginteger.prototype.bnpDMultiply;
Sk.builtin.biginteger.prototype.dAddOffset=Sk.builtin.biginteger.prototype.bnpDAddOffset;Sk.builtin.biginteger.prototype.multiplyLowerTo=Sk.builtin.biginteger.prototype.bnpMultiplyLowerTo;Sk.builtin.biginteger.prototype.multiplyUpperTo=Sk.builtin.biginteger.prototype.bnpMultiplyUpperTo;Sk.builtin.biginteger.prototype.modInt=Sk.builtin.biginteger.prototype.bnpModInt;Sk.builtin.biginteger.prototype.millerRabin=Sk.builtin.biginteger.prototype.bnpMillerRabin;Sk.builtin.biginteger.prototype.clone=Sk.builtin.biginteger.prototype.bnClone;
Sk.builtin.biginteger.prototype.intValue=Sk.builtin.biginteger.prototype.bnIntValue;Sk.builtin.biginteger.prototype.byteValue=Sk.builtin.biginteger.prototype.bnByteValue;Sk.builtin.biginteger.prototype.shortValue=Sk.builtin.biginteger.prototype.bnShortValue;Sk.builtin.biginteger.prototype.signum=Sk.builtin.biginteger.prototype.bnSigNum;Sk.builtin.biginteger.prototype.toByteArray=Sk.builtin.biginteger.prototype.bnToByteArray;Sk.builtin.biginteger.prototype.equals=Sk.builtin.biginteger.prototype.bnEquals;
Sk.builtin.biginteger.prototype.compare=Sk.builtin.biginteger.prototype.compareTo;Sk.builtin.biginteger.prototype.min=Sk.builtin.biginteger.prototype.bnMin;Sk.builtin.biginteger.prototype.max=Sk.builtin.biginteger.prototype.bnMax;Sk.builtin.biginteger.prototype.and=Sk.builtin.biginteger.prototype.bnAnd;Sk.builtin.biginteger.prototype.or=Sk.builtin.biginteger.prototype.bnOr;Sk.builtin.biginteger.prototype.xor=Sk.builtin.biginteger.prototype.bnXor;Sk.builtin.biginteger.prototype.andNot=Sk.builtin.biginteger.prototype.bnAndNot;
Sk.builtin.biginteger.prototype.not=Sk.builtin.biginteger.prototype.bnNot;Sk.builtin.biginteger.prototype.shiftLeft=Sk.builtin.biginteger.prototype.bnShiftLeft;Sk.builtin.biginteger.prototype.shiftRight=Sk.builtin.biginteger.prototype.bnShiftRight;Sk.builtin.biginteger.prototype.getLowestSetBit=Sk.builtin.biginteger.prototype.bnGetLowestSetBit;Sk.builtin.biginteger.prototype.bitCount=Sk.builtin.biginteger.prototype.bnBitCount;Sk.builtin.biginteger.prototype.testBit=Sk.builtin.biginteger.prototype.bnTestBit;
Sk.builtin.biginteger.prototype.setBit=Sk.builtin.biginteger.prototype.bnSetBit;Sk.builtin.biginteger.prototype.clearBit=Sk.builtin.biginteger.prototype.bnClearBit;Sk.builtin.biginteger.prototype.flipBit=Sk.builtin.biginteger.prototype.bnFlipBit;Sk.builtin.biginteger.prototype.add=Sk.builtin.biginteger.prototype.bnAdd;Sk.builtin.biginteger.prototype.subtract=Sk.builtin.biginteger.prototype.bnSubtract;Sk.builtin.biginteger.prototype.multiply=Sk.builtin.biginteger.prototype.bnMultiply;
Sk.builtin.biginteger.prototype.divide=Sk.builtin.biginteger.prototype.bnDivide;Sk.builtin.biginteger.prototype.remainder=Sk.builtin.biginteger.prototype.bnRemainder;Sk.builtin.biginteger.prototype.divideAndRemainder=Sk.builtin.biginteger.prototype.bnDivideAndRemainder;Sk.builtin.biginteger.prototype.modPow=Sk.builtin.biginteger.prototype.bnModPow;Sk.builtin.biginteger.prototype.modInverse=Sk.builtin.biginteger.prototype.bnModInverse;Sk.builtin.biginteger.prototype.pow=Sk.builtin.biginteger.prototype.bnPow;
Sk.builtin.biginteger.prototype.gcd=Sk.builtin.biginteger.prototype.bnGCD;Sk.builtin.biginteger.prototype.isProbablePrime=Sk.builtin.biginteger.prototype.bnIsProbablePrime;Sk.builtin.int_=function(a,b){var c,d;if(!(this instanceof Sk.builtin.int_))return new Sk.builtin.int_(a,b);if(this instanceof Sk.builtin.bool)return this;if(a instanceof Sk.builtin.int_&&void 0===b)return this.v=a.v,this;if(void 0!==b&&!Sk.builtin.checkInt(b)){if(Sk.builtin.checkFloat(b))throw new Sk.builtin.TypeError("integer argument expected, got "+Sk.abstr.typeName(b));if(b.__index__)b=Sk.misceval.callsim(b.__index__,b);else if(b.__int__)b=Sk.misceval.callsim(b.__int__,b);else throw new Sk.builtin.AttributeError(Sk.abstr.typeName(b)+
" instance has no attribute '__index__' or '__int__'");}if(a instanceof Sk.builtin.str){b=Sk.builtin.asnum$(b);c=Sk.str2number(a.v,b,parseInt,function(a){return-a},"int");if(c>Sk.builtin.int_.threshold$||c<-Sk.builtin.int_.threshold$)return new Sk.builtin.lng(a,b);this.v=c;return this}if(void 0!==b)throw new Sk.builtin.TypeError("int() can't convert non-string with explicit base");if(void 0===a||a===Sk.builtin.none)a=0;void 0!==a&&a.tp$getattr&&a.tp$getattr("__int__")?(c=Sk.misceval.callsim(a.tp$getattr("__int__")),
d="__int__"):void 0!==a&&a.__int__?(c=Sk.misceval.callsim(a.__int__,a),d="__int__"):void 0!==a&&a.tp$getattr&&a.tp$getattr("__trunc__")?(c=Sk.misceval.callsim(a.tp$getattr("__trunc__")),d="__trunc__"):void 0!==a&&a.__trunc__&&(c=Sk.misceval.callsim(a.__trunc__,a),d="__trunc__");if(void 0===c||Sk.builtin.checkInt(c))void 0!==c&&(a=c);else throw new Sk.builtin.TypeError(d+" returned non-Integral (type "+Sk.abstr.typeName(c)+")");if(!Sk.builtin.checkNumber(a))throw new Sk.builtin.TypeError("int() argument must be a string or a number, not '"+
Sk.abstr.typeName(a)+"'");a=Sk.builtin.asnum$(a);if(a>Sk.builtin.int_.threshold$||a<-Sk.builtin.int_.threshold$)return new Sk.builtin.lng(a);-1<a&&1>a&&(a=0);this.v=parseInt(a,b);return this};Sk.abstr.setUpInheritance("int",Sk.builtin.int_,Sk.builtin.numtype);Sk.builtin.int_.prototype.nb$int_=function(){return this};Sk.builtin.int_.prototype.nb$float_=function(){return new Sk.builtin.float_(this.v)};Sk.builtin.int_.prototype.nb$lng=function(){return new Sk.builtin.lng(this.v)};
Sk.builtin.int_.prototype.__trunc__=new Sk.builtin.func(function(a){return a});Sk.builtin.int_.prototype.__index__=new Sk.builtin.func(function(a){return a});Sk.builtin.int_.prototype.__complex__=new Sk.builtin.func(function(a){return Sk.builtin.NotImplemented.NotImplemented$});Sk.builtin.int_.prototype.tp$index=function(){return this.v};Sk.builtin.int_.prototype.tp$hash=function(){return new Sk.builtin.int_(this.v)};Sk.builtin.int_.threshold$=Math.pow(2,53)-1;Sk.builtin.int_.prototype.clone=function(){return new Sk.builtin.int_(this.v)};
Sk.builtin.int_.prototype.nb$add=function(a){var b;return a instanceof Sk.builtin.int_?new Sk.builtin.int_(this.v+a.v):a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$add(a)):a instanceof Sk.builtin.float_?(b=new Sk.builtin.float_(this.v),b.nb$add(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.nb$reflected_add=function(a){return Sk.builtin.int_.prototype.nb$add.call(this,a)};
Sk.builtin.int_.prototype.nb$subtract=function(a){var b;return a instanceof Sk.builtin.int_?new Sk.builtin.int_(this.v-a.v):a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$subtract(a)):a instanceof Sk.builtin.float_?(b=new Sk.builtin.float_(this.v),b.nb$subtract(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.nb$reflected_subtract=function(a){var b=this.nb$negative();return Sk.builtin.int_.prototype.nb$add.call(b,a)};
Sk.builtin.int_.prototype.nb$multiply=function(a){var b;return a instanceof Sk.builtin.int_?(b=this.v*a.v,b>Sk.builtin.int_.threshold$||b<-Sk.builtin.int_.threshold$?(b=new Sk.builtin.lng(this.v),b.nb$multiply(a)):new Sk.builtin.int_(b)):a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$multiply(a)):a instanceof Sk.builtin.float_?(b=new Sk.builtin.float_(this.v),b.nb$multiply(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.nb$reflected_multiply=function(a){return Sk.builtin.int_.prototype.nb$multiply.call(this,a)};Sk.builtin.int_.prototype.nb$divide=function(a){var b;return Sk.python3?(b=new Sk.builtin.float_(this.v),b.nb$divide(a)):this.nb$floor_divide(a)};Sk.builtin.int_.prototype.nb$reflected_divide=function(a){return this.nb$reflected_floor_divide(a)};
Sk.builtin.int_.prototype.nb$floor_divide=function(a){var b;if(a instanceof Sk.builtin.int_){if(0===a.v)throw new Sk.builtin.ZeroDivisionError("integer division or modulo by zero");return new Sk.builtin.int_(Math.floor(this.v/a.v))}return a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$divide(a)):a instanceof Sk.builtin.float_?(b=new Sk.builtin.float_(this.v),b.nb$divide(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.nb$reflected_floor_divide=function(a){return a instanceof Sk.builtin.int_?a.nb$divide(this):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.nb$remainder=function(a){var b;return a instanceof Sk.builtin.int_?(b=this.v%a.v,0>this.v?0<a.v&&0>b&&(b+=a.v):0>a.v&&0!==b&&(b+=a.v),0>a.v&&0===b?b=-0:0===b&&-Infinity===Infinity/b&&(b=0),new Sk.builtin.int_(b)):a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$remainder(a)):a instanceof Sk.builtin.float_?(b=new Sk.builtin.float_(this.v),b.nb$remainder(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.nb$reflected_remainder=function(a){return a instanceof Sk.builtin.int_?a.nb$remainder(this):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.nb$divmod=function(a){var b;return a instanceof Sk.builtin.int_?new Sk.builtin.tuple([this.nb$floor_divide(a),this.nb$remainder(a)]):a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$divmod(a)):a instanceof Sk.builtin.float_?(b=new Sk.builtin.float_(this.v),b.nb$divmod(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.nb$reflected_divmod=function(a){return a instanceof Sk.builtin.int_?new Sk.builtin.tuple([a.nb$floor_divide(this),a.nb$remainder(this)]):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.nb$power=function(a,b){var c;if(a instanceof Sk.builtin.int_&&(void 0===b||b instanceof Sk.builtin.int_)){c=Math.pow(this.v,a.v);c>Sk.builtin.int_.threshold$||c<-Sk.builtin.int_.threshold$?(c=new Sk.builtin.lng(this.v),c=c.nb$power(a,b)):c=0>a.v?new Sk.builtin.float_(c):new Sk.builtin.int_(c);if(void 0!==b){if(0>a.v)throw new Sk.builtin.TypeError("pow() 2nd argument cannot be negative when 3rd argument specified");return c.nb$remainder(b)}return c}return a instanceof Sk.builtin.lng?
(c=new Sk.builtin.lng(this.v),c.nb$power(a)):a instanceof Sk.builtin.float_?(c=new Sk.builtin.float_(this.v),c.nb$power(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.nb$reflected_power=function(a,b){return a instanceof Sk.builtin.int_?a.nb$power(this,b):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.nb$abs=function(){return new Sk.builtin.int_(Math.abs(this.v))};
Sk.builtin.int_.prototype.nb$and=function(a){var b;return a instanceof Sk.builtin.int_&&(a=Sk.builtin.asnum$(a),b=this.v&a,void 0!==b&&0>b&&(b+=4294967296),void 0!==b)?new Sk.builtin.int_(b):a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$and(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.nb$reflected_and=Sk.builtin.int_.prototype.nb$and;
Sk.builtin.int_.prototype.nb$or=function(a){var b;return a instanceof Sk.builtin.int_&&(a=Sk.builtin.asnum$(a),b=this.v|a,void 0!==b&&0>b&&(b+=4294967296),void 0!==b)?new Sk.builtin.int_(b):a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$and(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.nb$reflected_or=Sk.builtin.int_.prototype.nb$or;
Sk.builtin.int_.prototype.nb$xor=function(a){var b;return a instanceof Sk.builtin.int_&&(a=Sk.builtin.asnum$(a),b=this.v^a,void 0!==b&&0>b&&(b+=4294967296),void 0!==b)?new Sk.builtin.int_(b):a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$xor(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.nb$reflected_xor=Sk.builtin.int_.prototype.nb$xor;
Sk.builtin.int_.prototype.nb$lshift=function(a){var b;if(a instanceof Sk.builtin.int_){var c=Sk.builtin.asnum$(a);if(void 0!==c){if(0>c)throw new Sk.builtin.ValueError("negative shift count");b=this.v<<c;if(b<=this.v)return(new Sk.builtin.lng(this.v)).nb$lshift(a)}if(void 0!==b)return new Sk.builtin.int_(b)}return a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$lshift(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.nb$reflected_lshift=function(a){return a instanceof Sk.builtin.int_?a.nb$lshift(this):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.nb$rshift=function(a){var b;if(a instanceof Sk.builtin.int_){var c=Sk.builtin.asnum$(a);if(void 0!==c){if(0>c)throw new Sk.builtin.ValueError("negative shift count");b=this.v>>c;0<this.v&&0>b&&(b&=Math.pow(2,32-c)-1)}if(void 0!==b)return new Sk.builtin.int_(b)}return a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.v),b.nb$rshift(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.nb$reflected_rshift=function(a){return a instanceof Sk.builtin.int_?a.nb$rshift(this):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.nb$invert=function(){return new Sk.builtin.int_(~this.v)};Sk.builtin.int_.prototype.nb$inplace_add=Sk.builtin.int_.prototype.nb$add;Sk.builtin.int_.prototype.nb$inplace_subtract=Sk.builtin.int_.prototype.nb$subtract;Sk.builtin.int_.prototype.nb$inplace_multiply=Sk.builtin.int_.prototype.nb$multiply;
Sk.builtin.int_.prototype.nb$inplace_divide=Sk.builtin.int_.prototype.nb$divide;Sk.builtin.int_.prototype.nb$inplace_remainder=Sk.builtin.int_.prototype.nb$remainder;Sk.builtin.int_.prototype.nb$inplace_floor_divide=Sk.builtin.int_.prototype.nb$floor_divide;Sk.builtin.int_.prototype.nb$inplace_power=Sk.builtin.int_.prototype.nb$power;Sk.builtin.int_.prototype.nb$inplace_and=Sk.builtin.int_.prototype.nb$and;Sk.builtin.int_.prototype.nb$inplace_or=Sk.builtin.int_.prototype.nb$or;
Sk.builtin.int_.prototype.nb$inplace_xor=Sk.builtin.int_.prototype.nb$xor;Sk.builtin.int_.prototype.nb$inplace_lshift=Sk.builtin.int_.prototype.nb$lshift;Sk.builtin.int_.prototype.nb$inplace_rshift=Sk.builtin.int_.prototype.nb$rshift;Sk.builtin.int_.prototype.nb$negative=function(){return new Sk.builtin.int_(-this.v)};Sk.builtin.int_.prototype.nb$positive=function(){return this.clone()};Sk.builtin.int_.prototype.nb$nonzero=function(){return 0!==this.v};
Sk.builtin.int_.prototype.nb$isnegative=function(){return 0>this.v};Sk.builtin.int_.prototype.nb$ispositive=function(){return 0<=this.v};Sk.builtin.int_.prototype.numberCompare=function(a){return a instanceof Sk.builtin.int_?this.v-a.v:a instanceof Sk.builtin.lng?-a.longCompare(this):a instanceof Sk.builtin.float_?-a.numberCompare(this):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.ob$eq=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0==this.numberCompare(a)):a instanceof Sk.builtin.none?Sk.builtin.bool.false$:Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.ob$ne=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0!=this.numberCompare(a)):a instanceof Sk.builtin.none?Sk.builtin.bool.true$:Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.ob$lt=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0>this.numberCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.ob$le=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0>=this.numberCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.int_.prototype.ob$gt=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0<this.numberCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.ob$ge=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0<=this.numberCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.int_.prototype.__round__=function(a,b){Sk.builtin.pyCheckArgs("__round__",arguments,1,2);var c,d;if(void 0!==b&&!Sk.misceval.isIndex(b))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(b)+"' object cannot be interpreted as an index");void 0===b&&(b=0);d=Sk.builtin.asnum$(a);b=Sk.misceval.asIndex(b);c=Math.pow(10,b);c=Math.round(d*c)/c;return new Sk.builtin.int_(c)};Sk.builtin.int_.prototype.$r=function(){return new Sk.builtin.str(this.str$(10,!0))};
Sk.builtin.int_.prototype.tp$str=function(){return new Sk.builtin.str(this.str$(10,!0))};Sk.builtin.int_.prototype.str$=function(a,b){var c;void 0===b&&(b=!0);c=b?this.v:Math.abs(this.v);return void 0===a||10===a?c.toString():c.toString(a)};
Sk.str2number=function(a,b,c,d,e){var f=a,g=!1,h,k,l;a=a.replace(/^\s+|\s+$/g,"");"-"===a.charAt(0)&&(g=!0,a=a.substring(1));"+"===a.charAt(0)&&(a=a.substring(1));void 0===b&&(b=10);if((2>b||36<b)&&0!==b)throw new Sk.builtin.ValueError(e+"() base must be >= 2 and <= 36");if("0x"===a.substring(0,2).toLowerCase())if(16===b||0===b)a=a.substring(2),b=16;else{if(34>b)throw new Sk.builtin.ValueError("invalid literal for "+e+"() with base "+b+": '"+f+"'");}else if("0b"===a.substring(0,2).toLowerCase())if(2===
b||0===b)a=a.substring(2),b=2;else{if(12>b)throw new Sk.builtin.ValueError("invalid literal for "+e+"() with base "+b+": '"+f+"'");}else if("0o"===a.substring(0,2).toLowerCase())if(8===b||0===b)a=a.substring(2),b=8;else{if(25>b)throw new Sk.builtin.ValueError("invalid literal for "+e+"() with base "+b+": '"+f+"'");}else if("0"===a.charAt(0)){if("0"===a)return 0;if(8===b||0===b)b=8}0===b&&(b=10);if(0===a.length)throw new Sk.builtin.ValueError("invalid literal for "+e+"() with base "+b+": '"+f+"'");
for(h=0;h<a.length;h+=1)if(k=a.charCodeAt(h),l=b,48<=k&&57>=k?l=k-48:65<=k&&90>=k?l=k-65+10:97<=k&&122>=k&&(l=k-97+10),l>=b)throw new Sk.builtin.ValueError("invalid literal for "+e+"() with base "+b+": '"+f+"'");l=c(a,b);g&&(l=d(l));return l};goog.exportSymbol("Sk.builtin.int_",Sk.builtin.int_);Sk.builtin.bool=function(a){Sk.builtin.pyCheckArgs("bool",arguments,1);return Sk.misceval.isTrue(a)?Sk.builtin.bool.true$:Sk.builtin.bool.false$};Sk.abstr.setUpInheritance("bool",Sk.builtin.bool,Sk.builtin.int_);Sk.builtin.bool.prototype.$r=function(){return this.v?new Sk.builtin.str("True"):new Sk.builtin.str("False")};Sk.builtin.bool.prototype.tp$hash=function(){return new Sk.builtin.int_(this.v)};Sk.builtin.bool.prototype.__int__=new Sk.builtin.func(function(a){a=Sk.builtin.asnum$(a);return new Sk.builtin.int_(a)});
Sk.builtin.bool.prototype.__float__=new Sk.builtin.func(function(a){return new Sk.builtin.float_(Sk.ffi.remapToJs(a))});goog.exportSymbol("Sk.builtin.bool",Sk.builtin.bool);Sk.builtin.float_=function(a){if(void 0===a)return new Sk.builtin.float_(0);if(!(this instanceof Sk.builtin.float_))return new Sk.builtin.float_(a);if(a instanceof Sk.builtin.str){if(a.v.match(/^-inf$/i))a=-Infinity;else if(a.v.match(/^[+]?inf$/i))a=Infinity;else if(a.v.match(/^[-+]?nan$/i))a=NaN;else{if(isNaN(a.v))throw new Sk.builtin.ValueError("float: Argument: "+a.v+" is not number");a=parseFloat(a.v)}return new Sk.builtin.float_(a)}if("number"===typeof a||a instanceof Sk.builtin.int_||a instanceof
Sk.builtin.lng||a instanceof Sk.builtin.float_)return this.v=Sk.builtin.asnum$(a),this;if(a instanceof Sk.builtin.bool)return this.v=Sk.builtin.asnum$(a),this;if("boolean"===typeof a)return this.v=a?1:0,this;if("string"===typeof a)return this.v=parseFloat(a),this;var b=Sk.abstr.lookupSpecial(a,"__float__");if(null!=b)return Sk.misceval.callsim(b,a);throw new Sk.builtin.TypeError("float() argument must be a string or a number");};Sk.abstr.setUpInheritance("float",Sk.builtin.float_,Sk.builtin.numtype);
Sk.builtin.float_.prototype.nb$int_=function(){var a=this.v,a=0>a?Math.ceil(a):Math.floor(a);return new Sk.builtin.int_(a)};Sk.builtin.float_.prototype.nb$float_=function(){return this};Sk.builtin.float_.prototype.nb$lng=function(){return new Sk.builtin.lng(this.v)};Sk.builtin.float_.PyFloat_Check=function(a){return void 0===a?!1:Sk.builtin.checkNumber(a)||Sk.builtin.checkFloat(a)||Sk.builtin.issubclass(a.ob$type,Sk.builtin.float_)?!0:!1};Sk.builtin.float_.PyFloat_Check_Exact=function(a){return Sk.builtin.checkFloat(a)};
Sk.builtin.float_.PyFloat_AsDouble=function(a){var b;if(a&&Sk.builtin.float_.PyFloat_Check(a))return Sk.ffi.remapToJs(a);if(null==a)throw Error("bad argument for internal PyFloat_AsDouble function");b=Sk.builtin.type.typeLookup(a.ob$type,"__float__");if(null==b)throw new Sk.builtin.TypeError("a float is required");a=Sk.misceval.callsim(b,a);if(!Sk.builtin.float_.PyFloat_Check(a))throw new Sk.builtin.TypeError("nb_float should return float object");return Sk.ffi.remapToJs(a)};
Sk.builtin.float_.prototype.tp$index=function(){return this.v};Sk.builtin.float_.prototype.tp$hash=function(){return this.nb$int_()};Sk.builtin.float_.prototype.clone=function(){return new Sk.builtin.float_(this.v)};Sk.builtin.float_.prototype.toFixed=function(a){a=Sk.builtin.asnum$(a);return this.v.toFixed(a)};
Sk.builtin.float_.prototype.nb$add=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_?new Sk.builtin.float_(this.v+a.v):a instanceof Sk.builtin.lng?new Sk.builtin.float_(this.v+parseFloat(a.str$(10,!0))):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.float_.prototype.nb$reflected_add=function(a){return Sk.builtin.float_.prototype.nb$add.call(this,a)};
Sk.builtin.float_.prototype.nb$subtract=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_?new Sk.builtin.float_(this.v-a.v):a instanceof Sk.builtin.lng?new Sk.builtin.float_(this.v-parseFloat(a.str$(10,!0))):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.float_.prototype.nb$reflected_subtract=function(a){var b=this.nb$negative();return Sk.builtin.float_.prototype.nb$add.call(b,a)};
Sk.builtin.float_.prototype.nb$multiply=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_?new Sk.builtin.float_(this.v*a.v):a instanceof Sk.builtin.lng?new Sk.builtin.float_(this.v*parseFloat(a.str$(10,!0))):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.float_.prototype.nb$reflected_multiply=function(a){return Sk.builtin.float_.prototype.nb$multiply.call(this,a)};
Sk.builtin.float_.prototype.nb$divide=function(a){if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_){if(0===a.v)throw new Sk.builtin.ZeroDivisionError("integer division or modulo by zero");return Infinity===this.v?Infinity===a.v||-Infinity===a.v?new Sk.builtin.float_(NaN):a.nb$isnegative()?new Sk.builtin.float_(-Infinity):new Sk.builtin.float_(Infinity):-Infinity===this.v?Infinity===a.v||-Infinity===a.v?new Sk.builtin.float_(NaN):a.nb$isnegative()?new Sk.builtin.float_(Infinity):new Sk.builtin.float_(-Infinity):
new Sk.builtin.float_(this.v/a.v)}if(a instanceof Sk.builtin.lng){if(0===a.longCompare(Sk.builtin.biginteger.ZERO))throw new Sk.builtin.ZeroDivisionError("integer division or modulo by zero");return Infinity===this.v?a.nb$isnegative()?new Sk.builtin.float_(-Infinity):new Sk.builtin.float_(Infinity):-Infinity===this.v?a.nb$isnegative()?new Sk.builtin.float_(Infinity):new Sk.builtin.float_(-Infinity):new Sk.builtin.float_(this.v/parseFloat(a.str$(10,!0)))}return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.nb$reflected_divide=function(a){if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng)a=new Sk.builtin.float_(a);return a instanceof Sk.builtin.float_?a.nb$divide(this):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.nb$floor_divide=function(a){if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_){if(Infinity===this.v||-Infinity===this.v)return new Sk.builtin.float_(NaN);if(0===a.v)throw new Sk.builtin.ZeroDivisionError("integer division or modulo by zero");return Infinity===a.v?this.nb$isnegative()?new Sk.builtin.float_(-1):new Sk.builtin.float_(0):-Infinity===a.v?this.nb$isnegative()||!this.nb$nonzero()?new Sk.builtin.float_(0):new Sk.builtin.float_(-1):new Sk.builtin.float_(Math.floor(this.v/
a.v))}if(a instanceof Sk.builtin.lng){if(0===a.longCompare(Sk.builtin.biginteger.ZERO))throw new Sk.builtin.ZeroDivisionError("integer division or modulo by zero");return Infinity===this.v||-Infinity===this.v?new Sk.builtin.float_(NaN):new Sk.builtin.float_(Math.floor(this.v/parseFloat(a.str$(10,!0))))}return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.nb$reflected_floor_divide=function(a){if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng)a=new Sk.builtin.float_(a);return a instanceof Sk.builtin.float_?a.nb$floor_divide(this):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.nb$remainder=function(a){var b,c;if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_){if(0===a.v)throw new Sk.builtin.ZeroDivisionError("integer division or modulo by zero");if(0===this.v)return new Sk.builtin.float_(0);if(Infinity===a.v)return Infinity===this.v||-Infinity===this.v?new Sk.builtin.float_(NaN):this.nb$ispositive()?new Sk.builtin.float_(this.v):new Sk.builtin.float_(Infinity);c=this.v%a.v;0>this.v?0<a.v&&0>c&&(c+=a.v):0>a.v&&0!==c&&(c+=a.v);0>
a.v&&0===c?c=-0:0===c&&-Infinity===Infinity/c&&(c=0);return new Sk.builtin.float_(c)}if(a instanceof Sk.builtin.lng){if(0===a.longCompare(Sk.builtin.biginteger.ZERO))throw new Sk.builtin.ZeroDivisionError("integer division or modulo by zero");if(0===this.v)return new Sk.builtin.float_(0);b=parseFloat(a.str$(10,!0));c=this.v%b;0>c?0<b&&0!==c&&(c+=b):0>b&&0!==c&&(c+=b);a.nb$isnegative()&&0===c?c=-0:0===c&&-Infinity===Infinity/c&&(c=0);return new Sk.builtin.float_(c)}return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.nb$reflected_remainder=function(a){if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng)a=new Sk.builtin.float_(a);return a instanceof Sk.builtin.float_?a.nb$remainder(this):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.float_.prototype.nb$divmod=function(a){if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng)a=new Sk.builtin.float_(a);return a instanceof Sk.builtin.float_?new Sk.builtin.tuple([this.nb$floor_divide(a),this.nb$remainder(a)]):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.nb$reflected_divmod=function(a){if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng)a=new Sk.builtin.float_(a);return a instanceof Sk.builtin.float_?new Sk.builtin.tuple([a.nb$floor_divide(this),a.nb$remainder(this)]):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.nb$power=function(a,b){var c;if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_){if(0>this.v&&0!==a.v%1)throw new Sk.builtin.NegativePowerError("cannot raise a negative number to a fractional power");if(0===this.v&&0>a.v)throw new Sk.builtin.NegativePowerError("cannot raise zero to a negative power");c=new Sk.builtin.float_(Math.pow(this.v,a.v));if(Infinity===Math.abs(c.v)&&Infinity!==Math.abs(this.v)&&Infinity!==Math.abs(a.v))throw new Sk.builtin.OverflowError("Numerical result out of range");
return c}if(a instanceof Sk.builtin.lng){if(0===this.v&&0>a.longCompare(Sk.builtin.biginteger.ZERO))throw new Sk.builtin.NegativePowerError("cannot raise zero to a negative power");return new Sk.builtin.float_(Math.pow(this.v,parseFloat(a.str$(10,!0))))}return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.nb$reflected_power=function(a,b){if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng)a=new Sk.builtin.float_(a);return a instanceof Sk.builtin.float_?a.nb$power(this,b):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.float_.prototype.nb$abs=function(){return new Sk.builtin.float_(Math.abs(this.v))};Sk.builtin.float_.prototype.nb$inplace_add=Sk.builtin.float_.prototype.nb$add;Sk.builtin.float_.prototype.nb$inplace_subtract=Sk.builtin.float_.prototype.nb$subtract;
Sk.builtin.float_.prototype.nb$inplace_multiply=Sk.builtin.float_.prototype.nb$multiply;Sk.builtin.float_.prototype.nb$inplace_divide=Sk.builtin.float_.prototype.nb$divide;Sk.builtin.float_.prototype.nb$inplace_remainder=Sk.builtin.float_.prototype.nb$remainder;Sk.builtin.float_.prototype.nb$inplace_floor_divide=Sk.builtin.float_.prototype.nb$floor_divide;Sk.builtin.float_.prototype.nb$inplace_power=Sk.builtin.float_.prototype.nb$power;Sk.builtin.float_.prototype.nb$negative=function(){return new Sk.builtin.float_(-this.v)};
Sk.builtin.float_.prototype.nb$positive=function(){return this.clone()};Sk.builtin.float_.prototype.nb$nonzero=function(){return 0!==this.v};Sk.builtin.float_.prototype.nb$isnegative=function(){return 0>this.v};Sk.builtin.float_.prototype.nb$ispositive=function(){return 0<=this.v};
Sk.builtin.float_.prototype.numberCompare=function(a){var b;if(a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_)return Infinity==this.v&&Infinity==a.v||-Infinity==this.v&&-Infinity==a.v?0:this.v-a.v;if(a instanceof Sk.builtin.lng){if(0===this.v%1)return b=new Sk.builtin.lng(this.v),a=b.longCompare(a);a=this.nb$subtract(a);if(a instanceof Sk.builtin.float_)return a.v;if(a instanceof Sk.builtin.lng)return a.longCompare(Sk.builtin.biginteger.ZERO)}return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.ob$eq=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0==this.numberCompare(a)):a instanceof Sk.builtin.none?Sk.builtin.bool.false$:Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.ob$ne=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0!=this.numberCompare(a)):a instanceof Sk.builtin.none?Sk.builtin.bool.true$:Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.float_.prototype.ob$lt=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0>this.numberCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.ob$le=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0>=this.numberCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.float_.prototype.ob$gt=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0<this.numberCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.ob$ge=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0<=this.numberCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.float_.prototype.__round__=function(a,b){Sk.builtin.pyCheckArgs("__round__",arguments,1,2);var c,d;if(void 0!==b&&!Sk.misceval.isIndex(b))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(b)+"' object cannot be interpreted as an index");void 0===b&&(b=0);d=Sk.builtin.asnum$(a);b=Sk.misceval.asIndex(b);c=Math.pow(10,b);c=Math.round(d*c)/c;return new Sk.builtin.float_(c)};Sk.builtin.float_.prototype.$r=function(){return new Sk.builtin.str(this.str$(10,!0))};
Sk.builtin.float_.prototype.tp$str=function(){return new Sk.builtin.str(this.str$(10,!0))};
Sk.builtin.float_.prototype.str$=function(a,b){var c,d,e,f;if(isNaN(this.v))return"nan";void 0===b&&(b=!0);if(Infinity==this.v)return"inf";if(-Infinity==this.v&&b)return"-inf";if(-Infinity==this.v&&!b)return"inf";f=b?this.v:Math.abs(this.v);if(void 0===a||10===a){e=f.toPrecision(12);c=e.indexOf(".");d=f.toString().slice(0,c);c=f.toString().slice(c);d.match(/^-?0$/)&&c.slice(1).match(/^0{4,}/)&&(e=12>e.length?f.toExponential():f.toExponential(11));if(0>e.indexOf("e")&&0<=e.indexOf(".")){for(;"0"==
e.charAt(e.length-1);)e=e.substring(0,e.length-1);"."==e.charAt(e.length-1)&&(e+="0")}e=e.replace(/\.0+e/,"e","i");e=e.replace(/(e[-+])([1-9])$/,"$10$2");e=e.replace(/0+(e.*)/,"$1")}else e=f.toString(a);0===this.v&&-Infinity===1/this.v&&(e="-"+e);0>e.indexOf(".")&&(0>e.indexOf("E")&&0>e.indexOf("e"))&&(e+=".0");return e};var deprecatedError=new Sk.builtin.ExternalError("Sk.builtin.nmber is deprecated.");Sk.builtin.nmber=function(a,b){throw new Sk.builtin.ExternalError("Sk.builtin.nmber is deprecated. Please replace with Sk.builtin.int_, Sk.builtin.float_, or Sk.builtin.assk$.");};Sk.builtin.nmber.prototype.tp$index=function(){return this.v};Sk.builtin.nmber.prototype.tp$hash=function(){throw deprecatedError;};Sk.builtin.nmber.fromInt$=function(a){throw deprecatedError;};
Sk.builtin.nmber.prototype.clone=function(){throw deprecatedError;};Sk.builtin.nmber.prototype.toFixed=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$add=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$subtract=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$multiply=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$divide=function(a){throw deprecatedError;};
Sk.builtin.nmber.prototype.nb$floor_divide=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$remainder=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$divmod=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$power=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$and=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$or=function(a){throw deprecatedError;};
Sk.builtin.nmber.prototype.nb$xor=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$lshift=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$rshift=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$inplace_add=Sk.builtin.nmber.prototype.nb$add;Sk.builtin.nmber.prototype.nb$inplace_subtract=Sk.builtin.nmber.prototype.nb$subtract;Sk.builtin.nmber.prototype.nb$inplace_multiply=Sk.builtin.nmber.prototype.nb$multiply;
Sk.builtin.nmber.prototype.nb$inplace_divide=Sk.builtin.nmber.prototype.nb$divide;Sk.builtin.nmber.prototype.nb$inplace_remainder=Sk.builtin.nmber.prototype.nb$remainder;Sk.builtin.nmber.prototype.nb$inplace_floor_divide=Sk.builtin.nmber.prototype.nb$floor_divide;Sk.builtin.nmber.prototype.nb$inplace_power=Sk.builtin.nmber.prototype.nb$power;Sk.builtin.nmber.prototype.nb$inplace_and=Sk.builtin.nmber.prototype.nb$and;Sk.builtin.nmber.prototype.nb$inplace_or=Sk.builtin.nmber.prototype.nb$or;
Sk.builtin.nmber.prototype.nb$inplace_xor=Sk.builtin.nmber.prototype.nb$xor;Sk.builtin.nmber.prototype.nb$inplace_lshift=Sk.builtin.nmber.prototype.nb$lshift;Sk.builtin.nmber.prototype.nb$inplace_rshift=Sk.builtin.nmber.prototype.nb$rshift;Sk.builtin.nmber.prototype.nb$negative=function(){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$positive=function(){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$nonzero=function(){throw deprecatedError;};
Sk.builtin.nmber.prototype.nb$isnegative=function(){throw deprecatedError;};Sk.builtin.nmber.prototype.nb$ispositive=function(){throw deprecatedError;};Sk.builtin.nmber.prototype.numberCompare=function(a){throw deprecatedError;};Sk.builtin.nmber.prototype.__eq__=function(a,b){throw deprecatedError;};Sk.builtin.nmber.prototype.__ne__=function(a,b){throw deprecatedError;};Sk.builtin.nmber.prototype.__lt__=function(a,b){throw deprecatedError;};
Sk.builtin.nmber.prototype.__le__=function(a,b){throw deprecatedError;};Sk.builtin.nmber.prototype.__gt__=function(a,b){throw deprecatedError;};Sk.builtin.nmber.prototype.__ge__=function(a,b){throw deprecatedError;};Sk.builtin.nmber.prototype.__round__=function(a,b){throw deprecatedError;};Sk.builtin.nmber.prototype.$r=function(){throw deprecatedError;};Sk.builtin.nmber.prototype.tp$str=function(){throw deprecatedError;};Sk.builtin.nmber.prototype.str$=function(a,b){throw deprecatedError;};
goog.exportSymbol("Sk.builtin.nmber",Sk.builtin.nmber);Sk.builtin.lng=function(a,b){b=Sk.builtin.asnum$(b);if(!(this instanceof Sk.builtin.lng))return new Sk.builtin.lng(a,b);if(void 0===a)return this.biginteger=new Sk.builtin.biginteger(0),this;if(a instanceof Sk.builtin.lng)return this.biginteger=a.biginteger.clone(),this;if(a instanceof Sk.builtin.biginteger)return this.biginteger=a,this;if(a instanceof String||"string"===typeof a)return Sk.longFromStr(a,b);if(a instanceof Sk.builtin.str)return Sk.longFromStr(a.v,b);if(void 0!==a&&!Sk.builtin.checkString(a)&&
!Sk.builtin.checkNumber(a))if(!0===a)a=1;else if(!1===a)a=0;else throw new Sk.builtin.TypeError("long() argument must be a string or a number, not '"+Sk.abstr.typeName(a)+"'");a=Sk.builtin.asnum$nofloat(a);this.biginteger=new Sk.builtin.biginteger(a);return this};Sk.abstr.setUpInheritance("long",Sk.builtin.lng,Sk.builtin.numtype);Sk.builtin.lng.prototype.tp$index=function(){return parseInt(this.str$(10,!0),10)};Sk.builtin.lng.prototype.tp$hash=function(){return new Sk.builtin.int_(this.tp$index())};
Sk.builtin.lng.prototype.nb$int_=function(){return this.cantBeInt()?new Sk.builtin.lng(this):new Sk.builtin.int_(this.toInt$())};Sk.builtin.lng.prototype.__index__=new Sk.builtin.func(function(a){return a.nb$int_(a)});Sk.builtin.lng.prototype.nb$lng_=function(){return this};Sk.builtin.lng.prototype.nb$float_=function(){return new Sk.builtin.float_(Sk.ffi.remapToJs(this))};Sk.builtin.lng.MAX_INT$=new Sk.builtin.lng(Sk.builtin.int_.threshold$);Sk.builtin.lng.MIN_INT$=new Sk.builtin.lng(-Sk.builtin.int_.threshold$);
Sk.builtin.lng.prototype.cantBeInt=function(){return 0<this.longCompare(Sk.builtin.lng.MAX_INT$)||0>this.longCompare(Sk.builtin.lng.MIN_INT$)};Sk.builtin.lng.fromInt$=function(a){return new Sk.builtin.lng(a)};Sk.longFromStr=function(a,b){var c=Sk.str2number(a,b,function(a,b){return 10===b?new Sk.builtin.biginteger(a):new Sk.builtin.biginteger(a,b)},function(a){return a.negate()},"long");return new Sk.builtin.lng(c)};goog.exportSymbol("Sk.longFromStr",Sk.longFromStr);
Sk.builtin.lng.prototype.toInt$=function(){return this.biginteger.intValue()};Sk.builtin.lng.prototype.clone=function(){return new Sk.builtin.lng(this)};
Sk.builtin.lng.prototype.nb$add=function(a){var b;if(a instanceof Sk.builtin.float_)return b=new Sk.builtin.float_(this.str$(10,!0)),b.nb$add(a);a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?new Sk.builtin.lng(this.biginteger.add(a.biginteger)):a instanceof Sk.builtin.biginteger?new Sk.builtin.lng(this.biginteger.add(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$reflected_add=function(a){return Sk.builtin.lng.prototype.nb$add.call(this,a)};Sk.builtin.lng.prototype.nb$inplace_add=Sk.builtin.lng.prototype.nb$add;
Sk.builtin.lng.prototype.nb$subtract=function(a){var b;if(a instanceof Sk.builtin.float_)return b=new Sk.builtin.float_(this.str$(10,!0)),b.nb$subtract(a);a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?new Sk.builtin.lng(this.biginteger.subtract(a.biginteger)):a instanceof Sk.builtin.biginteger?new Sk.builtin.lng(this.biginteger.subtract(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$reflected_subtract=function(a){var b=this.nb$negative();return Sk.builtin.lng.prototype.nb$add.call(b,a)};Sk.builtin.lng.prototype.nb$inplace_subtract=Sk.builtin.lng.prototype.nb$subtract;
Sk.builtin.lng.prototype.nb$multiply=function(a){var b;if(a instanceof Sk.builtin.float_)return b=new Sk.builtin.float_(this.str$(10,!0)),b.nb$multiply(a);a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?new Sk.builtin.lng(this.biginteger.multiply(a.biginteger)):a instanceof Sk.builtin.biginteger?new Sk.builtin.lng(this.biginteger.multiply(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$reflected_multiply=function(a){return Sk.builtin.lng.prototype.nb$multiply.call(this,a)};Sk.builtin.lng.prototype.nb$inplace_multiply=Sk.builtin.lng.prototype.nb$multiply;
Sk.builtin.lng.prototype.nb$divide=function(a){var b,c;if(a instanceof Sk.builtin.float_)return b=new Sk.builtin.float_(this.str$(10,!0)),b.nb$divide(a);a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));if(a instanceof Sk.builtin.lng){b=this.nb$isnegative();c=a.nb$isnegative();if(b&&!c||c&&!b){a=this.biginteger.divideAndRemainder(a.biginteger);if(0===a[1].trueCompare(Sk.builtin.biginteger.ZERO))return new Sk.builtin.lng(a[0]);a=a[0].subtract(Sk.builtin.biginteger.ONE);return new Sk.builtin.lng(a)}return new Sk.builtin.lng(this.biginteger.divide(a.biginteger))}return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$reflected_divide=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?a.nb$divide(this):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$floor_divide=function(a){var b;if(a instanceof Sk.builtin.float_)return b=new Sk.builtin.float_(this.str$(10,!0)),b.nb$floor_divide(a);a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?a.nb$divide(this):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$divmod=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?new Sk.builtin.tuple([this.nb$floor_divide(a),this.nb$remainder(a)]):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$reflected_divmod=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?new Sk.builtin.tuple([a.nb$floor_divide(this),a.nb$remainder(this)]):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$inplace_divide=Sk.builtin.lng.prototype.nb$divide;Sk.builtin.lng.prototype.nb$floor_divide=Sk.builtin.lng.prototype.nb$divide;Sk.builtin.lng.prototype.nb$reflected_floor_divide=Sk.builtin.lng.prototype.nb$reflected_divide;Sk.builtin.lng.prototype.nb$inplace_floor_divide=Sk.builtin.lng.prototype.nb$floor_divide;
Sk.builtin.lng.prototype.nb$remainder=function(a){var b;if(0===this.biginteger.trueCompare(Sk.builtin.biginteger.ZERO))return a instanceof Sk.builtin.float_?new Sk.builtin.float_(0):new Sk.builtin.lng(0);if(a instanceof Sk.builtin.float_)return b=new Sk.builtin.float_(this.str$(10,!0)),b.nb$remainder(a);a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?(b=new Sk.builtin.lng(this.biginteger.remainder(a.biginteger)),this.nb$isnegative()?a.nb$ispositive()&&
b.nb$nonzero()&&(b=b.nb$add(a).nb$remainder(a)):a.nb$isnegative()&&b.nb$nonzero()&&(b=b.nb$add(a)),b):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$reflected_remainder=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?a.nb$remainder(this):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$inplace_remainder=Sk.builtin.lng.prototype.nb$remainder;
Sk.builtin.lng.prototype.nb$divmod=function(a){var b;a===Sk.builtin.bool.true$&&(a=new Sk.builtin.lng(1));a===Sk.builtin.bool.false$&&(a=new Sk.builtin.lng(0));a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?new Sk.builtin.tuple([this.nb$floor_divide(a),this.nb$remainder(a)]):a instanceof Sk.builtin.float_?(b=new Sk.builtin.float_(this.str$(10,!0)),b.nb$divmod(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$power=function(a,b){var c;if(void 0!==b)return a=new Sk.builtin.biginteger(Sk.builtin.asnum$(a)),b=new Sk.builtin.biginteger(Sk.builtin.asnum$(b)),new Sk.builtin.lng(this.biginteger.modPowInt(a,b));if(a instanceof Sk.builtin.float_||a instanceof Sk.builtin.int_&&0>a.v)return c=new Sk.builtin.float_(this.str$(10,!0)),c.nb$power(a);a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?void 0!==b?(a=new Sk.builtin.biginteger(Sk.builtin.asnum$(a)),
b=new Sk.builtin.biginteger(Sk.builtin.asnum$(b)),new Sk.builtin.lng(this.biginteger.modPowInt(a,b))):a.nb$isnegative()?(c=new Sk.builtin.float_(this.str$(10,!0)),c.nb$power(a)):new Sk.builtin.lng(this.biginteger.pow(a.biginteger)):a instanceof Sk.builtin.biginteger?void 0!==b?(b=new Sk.builtin.biginteger(Sk.builtin.asnum$(b)),new Sk.builtin.lng(this.biginteger.modPowInt(a,b))):a.isnegative()?(c=new Sk.builtin.float_(this.str$(10,!0)),c.nb$power(a)):new Sk.builtin.lng(this.biginteger.pow(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$reflected_power=function(a,b){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?a.nb$power(this,b):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$inplace_power=Sk.builtin.lng.prototype.nb$power;Sk.builtin.lng.prototype.nb$abs=function(){return new Sk.builtin.lng(this.biginteger.bnAbs())};
Sk.builtin.lng.prototype.nb$lshift=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));if(a instanceof Sk.builtin.lng){if(0>a.biginteger.signum())throw new Sk.builtin.ValueError("negative shift count");return new Sk.builtin.lng(this.biginteger.shiftLeft(a.biginteger))}if(a instanceof Sk.builtin.biginteger){if(0>a.signum())throw new Sk.builtin.ValueError("negative shift count");return new Sk.builtin.lng(this.biginteger.shiftLeft(a))}return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$reflected_lshift=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?a.nb$lshift(this):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$inplace_lshift=Sk.builtin.lng.prototype.nb$lshift;
Sk.builtin.lng.prototype.nb$rshift=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));if(a instanceof Sk.builtin.lng){if(0>a.biginteger.signum())throw new Sk.builtin.ValueError("negative shift count");return new Sk.builtin.lng(this.biginteger.shiftRight(a.biginteger))}if(a instanceof Sk.builtin.biginteger){if(0>a.signum())throw new Sk.builtin.ValueError("negative shift count");return new Sk.builtin.lng(this.biginteger.shiftRight(a))}return Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.nb$reflected_rshift=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?a.nb$rshift(this):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$inplace_rshift=Sk.builtin.lng.prototype.nb$rshift;
Sk.builtin.lng.prototype.nb$and=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?new Sk.builtin.lng(this.biginteger.and(a.biginteger)):a instanceof Sk.builtin.biginteger?new Sk.builtin.lng(this.biginteger.and(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$reflected_and=Sk.builtin.lng.prototype.nb$and;Sk.builtin.lng.prototype.nb$inplace_and=Sk.builtin.lng.prototype.nb$and;
Sk.builtin.lng.prototype.nb$or=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?new Sk.builtin.lng(this.biginteger.or(a.biginteger)):a instanceof Sk.builtin.biginteger?new Sk.builtin.lng(this.biginteger.or(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$reflected_or=Sk.builtin.lng.prototype.nb$or;Sk.builtin.lng.prototype.nb$inplace_or=Sk.builtin.lng.prototype.nb$or;
Sk.builtin.lng.prototype.nb$xor=function(a){a instanceof Sk.builtin.int_&&(a=new Sk.builtin.lng(a.v));return a instanceof Sk.builtin.lng?new Sk.builtin.lng(this.biginteger.xor(a.biginteger)):a instanceof Sk.builtin.biginteger?new Sk.builtin.lng(this.biginteger.xor(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.nb$reflected_xor=Sk.builtin.lng.prototype.nb$xor;Sk.builtin.lng.prototype.nb$inplace_xor=Sk.builtin.lng.prototype.nb$xor;Sk.builtin.lng.prototype.nb$negative=function(){return new Sk.builtin.lng(this.biginteger.negate())};
Sk.builtin.lng.prototype.nb$invert=function(){return new Sk.builtin.lng(this.biginteger.not())};Sk.builtin.lng.prototype.nb$positive=function(){return this.clone()};Sk.builtin.lng.prototype.nb$nonzero=function(){return 0!==this.biginteger.trueCompare(Sk.builtin.biginteger.ZERO)};Sk.builtin.lng.prototype.nb$isnegative=function(){return this.biginteger.isnegative()};Sk.builtin.lng.prototype.nb$ispositive=function(){return!this.biginteger.isnegative()};
Sk.builtin.lng.prototype.longCompare=function(a){var b;"number"===typeof a&&(a=new Sk.builtin.lng(a));return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.float_&&0===a.v%1?(a=new Sk.builtin.lng(a.v),this.longCompare(a)):a instanceof Sk.builtin.float_?(b=new Sk.builtin.float_(this),b.numberCompare(a)):a instanceof Sk.builtin.lng?this.biginteger.subtract(a.biginteger):a instanceof Sk.builtin.biginteger?this.biginteger.subtract(a):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.ob$eq=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0==this.longCompare(a)):a instanceof Sk.builtin.none?Sk.builtin.bool.false$:Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.ob$ne=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0!=this.longCompare(a)):a instanceof Sk.builtin.none?Sk.builtin.bool.true$:Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.ob$lt=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0>this.longCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.ob$le=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0>=this.longCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.ob$gt=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0<this.longCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};
Sk.builtin.lng.prototype.ob$ge=function(a){return a instanceof Sk.builtin.int_||a instanceof Sk.builtin.lng||a instanceof Sk.builtin.float_?new Sk.builtin.bool(0<=this.longCompare(a)):Sk.builtin.NotImplemented.NotImplemented$};Sk.builtin.lng.prototype.$r=function(){return new Sk.builtin.str(this.str$(10,!0)+"L")};Sk.builtin.lng.prototype.tp$str=function(){return new Sk.builtin.str(this.str$(10,!0))};
Sk.builtin.lng.prototype.str$=function(a,b){var c;void 0===b&&(b=!0);c=b?this.biginteger:this.biginteger.abs();return void 0===a||10===a?c.toString():c.toString(a)};Math.hypot=Math.hypot||function(){for(var a=0,b=arguments.length,c=0;c<b;c++){if(Infinity===arguments[c]||-Infinity===arguments[c])return Infinity;a+=arguments[c]*arguments[c]}return Math.sqrt(a)};
Sk.builtin.complex=function(a,b){Sk.builtin.pyCheckArgs("complex",arguments,0,2);var c,d,e,f,g,h=!1,k=!1;if(!(this instanceof Sk.builtin.complex))return new Sk.builtin.complex(a,b);c=null==a?Sk.builtin.bool.false$:a;d=b;if(c instanceof Sk.builtin.complex&&null==d)return a;if(null!=c&&Sk.builtin.checkString(c)){if(null!=d)throw new Sk.builtin.TypeError("complex() can't take second arg if first is a string");return Sk.builtin.complex.complex_subtype_from_string(c)}if(null!=d&&Sk.builtin.checkString(d))throw new Sk.builtin.TypeError("complex() second arg can't be a string");
e=Sk.builtin.complex.try_complex_special_method(c);if(null!=e&&e!==Sk.builtin.NotImplemented.NotImplemented$){if(!Sk.builtin.checkComplex(e))throw new Sk.builtin.TypeError("__complex__ should return a complex object");c=e}e=Sk.builtin.asnum$(c);null!=d&&(f=Sk.builtin.asnum$(d));var l=function(a){if(Sk.builtin.checkNumber(a)||void 0!==Sk.builtin.type.typeLookup(a.ob$type,"__float__"))return!0};if(null==e||!l(c)&&!Sk.builtin.checkComplex(c)||null!=d&&(null==f||!l(d)&&!Sk.builtin.checkComplex(d)))throw new Sk.builtin.TypeError("complex() argument must be a string or number");
if(Sk.builtin.complex._complex_check(c))f=c.real.v,c=c.imag.v,h=!0;else{e=Sk.builtin.float_.PyFloat_AsDouble(c);if(null==e)return null;f=e;c=0}if(null==d)e=0;else if(Sk.builtin.complex._complex_check(d))e=d.real.v,g=d.imag.v,k=!0;else{e=Sk.builtin.float_.PyFloat_AsDouble(d);if(null==e)return null;g=0}!0===k&&(f-=g);!0===h&&(e+=c);0===f&&(0>e||Sk.builtin.complex._isNegativeZero(e))&&(f=-0);this.real=new Sk.builtin.float_(f);this.imag=new Sk.builtin.float_(e);this.__class__=Sk.builtin.complex;return this};
Sk.abstr.setUpInheritance("complex",Sk.builtin.complex,Sk.builtin.numtype);Sk.builtin.complex.prototype.nb$int_=function(){throw new Sk.builtin.TypeError("can't convert complex to int");};Sk.builtin.complex.prototype.nb$float_=function(){throw new Sk.builtin.TypeError("can't convert complex to float");};Sk.builtin.complex.prototype.nb$lng=function(){throw new Sk.builtin.TypeError("can't convert complex to long");};Sk.builtin.complex.prototype.__doc__=new Sk.builtin.str("complex(real[, imag]) -> complex number\n\nCreate a complex number from a real part and an optional imaginary part.\nThis is equivalent to (real + imag*1j) where imag defaults to 0.");
Sk.builtin.complex._isNegativeZero=function(a){return 0!==a?!1:-Infinity===1/a};Sk.builtin.complex.try_complex_special_method=function(a){new Sk.builtin.str("__complex__");var b;if(null==a)return null;b=Sk.abstr.lookupSpecial(a,"__complex__");return null!=b?a=Sk.misceval.callsim(b,a):null};
Sk.builtin.complex.check_number_or_complex=function(a){if(!Sk.builtin.checkNumber(a)&&"complex"!==a.tp$name)throw new Sk.builtin.TypeError("unsupported operand type(s) for +: 'complex' and '"+Sk.abstr.typeName(a)+"'");Sk.builtin.checkNumber(a)&&(a=new Sk.builtin.complex(a));return a};
Sk.builtin.complex.complex_subtype_from_string=function(a){var b,c,d=0,e=0,f=!1,g;if(Sk.builtin.checkString(a))a=Sk.ffi.remapToJs(a);else if("string"!==typeof a)throw new TypeError("provided unsupported string-alike argument");if(-1!==a.indexOf("\x00")||0===a.length||""===a)throw new Sk.builtin.ValueError("complex() arg is a malformed string");b=0;a=a.replace(/inf|infinity/gi,"Infinity");for(a=a.replace(/nan/gi,"NaN");" "===a[b];)b++;if("("===a[b])for(f=!0,b++;" "===a[b];)b++;var h=/^(?:[+-]?(?:(?:(?:\d*\.\d+)|(?:\d+\.?))(?:[eE][+-]?\d+)?|NaN|Infinity))/;
c=a.substr(b);g=c.match(h);if(null!==g)if(b+=g[0].length,"j"===a[b]||"J"===a[b])e=parseFloat(g[0]),b++;else if("+"===a[b]||"-"===a[b]){d=parseFloat(g[0]);g=a.substr(b).match(h);null!==g?(e=parseFloat(g[0]),b+=g[0].length):(e="+"===a[b]?1:-1,b++);if("j"!==a[b]&&"J"!==a[b])throw new Sk.builtin.ValueError("complex() arg is malformed string");b++}else d=parseFloat(g[0]);else g=g=c.match(/^([+-]?[jJ])/),null!==g&&(e=1===g[0].length?1:"+"===g[0][0]?1:-1,b+=g[0].length);for(;" "===a[b];)b++;if(f){if(")"!==
a[b])throw new Sk.builtin.ValueError("complex() arg is malformed string");for(b++;" "===a[b];)b++}if(a.length!==b)throw new Sk.builtin.ValueError("complex() arg is malformed string");return new Sk.builtin.complex(new Sk.builtin.float_(d),new Sk.builtin.float_(e))};Sk.builtin.complex.prototype.tp$hash=function(){return new Sk.builtin.int_(1000003*this.tp$getattr("imag").v+this.tp$getattr("real").v)};
Sk.builtin.complex.prototype.nb$add=function(a){var b;a=Sk.builtin.complex.check_number_or_complex(a);b=this.tp$getattr("real").v+a.tp$getattr("real").v;a=this.tp$getattr("imag").v+a.tp$getattr("imag").v;return new Sk.builtin.complex(new Sk.builtin.float_(b),new Sk.builtin.float_(a))};Sk.builtin.complex._c_diff=function(a,b){var c,d;c=a.real.nb$subtract.call(a.real,b.real);d=a.imag.nb$subtract.call(a.imag,b.imag);return new Sk.builtin.complex(c,d)};
Sk.builtin.complex.prototype.nb$subtract=function(a){var b;b=Sk.builtin.complex.check_number_or_complex(this);a=Sk.builtin.complex.check_number_or_complex(a);return Sk.builtin.complex._c_diff(b,a)};Sk.builtin.complex.prototype.nb$multiply=function(a){var b;b=Sk.builtin.complex.check_number_or_complex(a);a=this.real.v*b.real.v-this.imag.v*b.imag.v;b=this.real.v*b.imag.v+this.imag.v*b.real.v;return new Sk.builtin.complex(new Sk.builtin.float_(a),new Sk.builtin.float_(b))};
Sk.builtin.complex.prototype.nb$divide=function(a){var b;a=Sk.builtin.complex.check_number_or_complex(a);var c,d;b=a.real.v;var e=a.imag.v;a=this.real.v;var f=this.imag.v;c=Math.abs(b);d=Math.abs(e);if(c>=d){if(0===c)throw new Sk.builtin.ZeroDivisionError("complex division by zero");c=e/b;d=b+e*c;b=(a+f*c)/d;a=(f-a*c)/d}else d>=c?(c=b/e,d=b*c+e,goog.asserts.assert(0!==e),b=(a*c+f)/d,a=(f*c-a)/d):a=b=NaN;return new Sk.builtin.complex(new Sk.builtin.float_(b),new Sk.builtin.float_(a))};
Sk.builtin.complex.prototype.nb$floor_divide=function(a){throw new Sk.builtin.TypeError("can't take floor of complex number.");};Sk.builtin.complex.prototype.nb$remainder=function(a){throw new Sk.builtin.TypeError("can't mod complex numbers.");};
Sk.builtin.complex.prototype.nb$power=function(a,b){var c,d;if(null!=b&&!Sk.builtin.checkNone(b))throw new Sk.builtin.ValueError("complex modulo");d=Sk.builtin.complex.check_number_or_complex(a);c=d.real.v|0;return 0===d.imag.v&&d.real.v===c?Sk.builtin.complex.c_powi(this,c):Sk.builtin.complex.c_pow(this,d)};
Sk.builtin.complex.c_pow=function(a,b){var c,d,e,f;f=b.real.v;var g=b.imag.v;e=a.real.v;var h=a.imag.v;if(0===f&&0===g)c=1,d=0;else if(0===e&&0===h){if(0!==g||0>f)throw new Sk.builtin.ZeroDivisionError("complex division by zero");d=c=0}else c=Math.hypot(e,h),d=Math.pow(c,f),e=Math.atan2(h,e),f*=e,0!==g&&(d/=Math.exp(e*g),f+=g*Math.log(c)),c=d*Math.cos(f),d*=Math.sin(f);return new Sk.builtin.complex(new Sk.builtin.float_(c),new Sk.builtin.float_(d))};
Sk.builtin.complex.c_powi=function(a,b){var c;return 100<b||-100>b?(c=new Sk.builtin.complex(new Sk.builtin.float_(b),new Sk.builtin.float_(0)),Sk.builtin.complex.c_pow(a,c)):0<b?Sk.builtin.complex.c_powu(a,b):(new Sk.builtin.complex(new Sk.builtin.float_(1),new Sk.builtin.float_(0))).nb$divide(Sk.builtin.complex.c_powu(a,-b))};
Sk.builtin.complex.c_powu=function(a,b){var c,d,e=1;c=new Sk.builtin.complex(new Sk.builtin.float_(1),new Sk.builtin.float_(0));for(d=a;0<e&&b>=e;)b&e&&(c=c.nb$multiply(d)),e<<=1,d=d.nb$multiply(d);return c};Sk.builtin.complex.prototype.nb$inplace_add=Sk.builtin.complex.prototype.nb$add;Sk.builtin.complex.prototype.nb$inplace_subtract=Sk.builtin.complex.prototype.nb$subtract;Sk.builtin.complex.prototype.nb$inplace_multiply=Sk.builtin.complex.prototype.nb$multiply;
Sk.builtin.complex.prototype.nb$inplace_divide=Sk.builtin.complex.prototype.nb$divide;Sk.builtin.complex.prototype.nb$inplace_remainder=Sk.builtin.complex.prototype.nb$remainder;Sk.builtin.complex.prototype.nb$inplace_floor_divide=Sk.builtin.complex.prototype.nb$floor_divide;Sk.builtin.complex.prototype.nb$inplace_power=Sk.builtin.complex.prototype.nb$power;
Sk.builtin.complex.prototype.nb$negative=function(){var a,b;b=this.imag.v;a=-this.real.v;b=-b;return new Sk.builtin.complex(new Sk.builtin.float_(a),new Sk.builtin.float_(b))};Sk.builtin.complex.prototype.nb$positive=function(){return Sk.builtin.complex.check_number_or_complex(this)};Sk.builtin.complex._complex_check=function(a){return void 0===a?!1:a instanceof Sk.builtin.complex||a.tp$name&&"complex"===a.tp$name||Sk.builtin.issubclass(new Sk.builtin.type(a),Sk.builtin.complex)?!0:!1};
Sk.builtin.complex.prototype.tp$richcompare=function(a,b){var c,d;if("Eq"!==b&&"NotEq"!==b){if(Sk.builtin.checkNumber(a)||Sk.builtin.complex._complex_check(a))throw new Sk.builtin.TypeError("no ordering relation is defined for complex numbers");return Sk.builtin.NotImplemented.NotImplemented$}d=Sk.builtin.complex.check_number_or_complex(this);c=d.tp$getattr("real").v;d=d.tp$getattr("imag").v;if(Sk.builtin.checkInt(a)){if(0===d)return c=Sk.misceval.richCompareBool(new Sk.builtin.float_(c),a,b),c=new Sk.builtin.bool(c);
c=!1}else if(Sk.builtin.checkFloat(a))c=c===Sk.builtin.float_.PyFloat_AsDouble(a)&&0===d;else if(Sk.builtin.complex._complex_check(a)){var e=a.tp$getattr("real").v,f=a.tp$getattr("imag").v;c=c===e&&d===f}else return Sk.builtin.NotImplemented.NotImplemented$;"NotEq"===b&&(c=!c);return c=new Sk.builtin.bool(c)};Sk.builtin.complex.prototype.__eq__=function(a,b){return Sk.builtin.complex.prototype.tp$richcompare.call(a,b,"Eq")};
Sk.builtin.complex.prototype.__ne__=function(a,b){return Sk.builtin.complex.prototype.tp$richcompare.call(a,b,"NotEq")};Sk.builtin.complex.prototype.__lt__=function(a,b){throw new Sk.builtin.TypeError("unorderable types: "+Sk.abstr.typeName(a)+" < "+Sk.abstr.typeName(b));};Sk.builtin.complex.prototype.__le__=function(a,b){throw new Sk.builtin.TypeError("unorderable types: "+Sk.abstr.typeName(a)+" <= "+Sk.abstr.typeName(b));};
Sk.builtin.complex.prototype.__gt__=function(a,b){throw new Sk.builtin.TypeError("unorderable types: "+Sk.abstr.typeName(a)+" > "+Sk.abstr.typeName(b));};Sk.builtin.complex.prototype.__ge__=function(a,b){throw new Sk.builtin.TypeError("unorderable types: "+Sk.abstr.typeName(a)+" >= "+Sk.abstr.typeName(b));};Sk.builtin.complex.prototype.__float__=function(a){throw new Sk.builtin.TypeError("can't convert complex to float");};
Sk.builtin.complex.prototype.__int__=function(a){throw new Sk.builtin.TypeError("can't convert complex to int");};Sk.builtin.complex.prototype._internalGenericGetAttr=Sk.builtin.object.prototype.GenericGetAttr;Sk.builtin.complex.prototype.tp$getattr=function(a){if(null!=a&&(Sk.builtin.checkString(a)||"string"===typeof a)){var b=a;Sk.builtin.checkString(a)&&(b=Sk.ffi.remapToJs(a));if("real"===b||"imag"===b)return this[b]}return this._internalGenericGetAttr(a)};
Sk.builtin.complex.prototype.tp$setattr=function(a,b){if(null!=a&&(Sk.builtin.checkString(a)||"string"===typeof a)){var c=a;Sk.builtin.checkString(a)&&(c=Sk.ffi.remapToJs(a));if("real"===c||"imag"===c)throw new Sk.builtin.AttributeError("readonly attribute");}throw new Sk.builtin.AttributeError("'complex' object attribute '"+a+"' is readonly");};
Sk.builtin.complex.complex_format=function(a,b,c){if(null==a||!Sk.builtin.complex._complex_check(a))throw Error("Invalid internal method call: Sk.complex.complex_format() called with invalid value type.");var d="",d="",e=null,f="",g="";0===a.real.v&&1==(0>a.real.v?-Math.abs(1):Math.abs(1))?(e="",d=Sk.builtin.complex.PyOS_double_to_string(a.imag.v,c,b,0,null)):(e=d=Sk.builtin.complex.PyOS_double_to_string(a.real.v,c,b,0,null),d=Sk.builtin.complex.PyOS_double_to_string(a.imag.v,c,b,Sk.builtin.complex.PyOS_double_to_string.Py_DTSF_SIGN,
null),0===a.imag.v&&(-Infinity===1/a.imag.v&&d&&"-"!==d[0])&&(d="-"+d),f="(",g=")");return new Sk.builtin.str(""+f+e+d+"j"+g)};Sk.builtin.complex.prototype.$r=function(){return Sk.builtin.complex.complex_format(this,0,"r")};Sk.builtin.complex.prototype.tp$str=function(){return Sk.builtin.complex.complex_format(this,null,"g")};
Sk.builtin.complex.prototype.__format__=new Sk.builtin.func(function(a,b){var c;if(null==b)return null;if(Sk.builtin.checkString(b))return c=Sk.builtin.complex._PyComplex_FormatAdvanced(a,b);throw new Sk.builtin.TypeError("__format__ requires str or unicode");});Sk.builtin.complex._PyComplex_FormatAdvanced=function(a,b){throw new Sk.builtin.NotImplementedError("__format__ is not implemented for complex type.");};
Sk.builtin.complex._is_finite=function(a){return!isNaN(a)&&Infinity!==a&&-Infinity!==a};Sk.builtin.complex._is_infinity=function(a){return Infinity===a||-Infinity===a};
Sk.builtin.complex.prototype.__abs__=new Sk.builtin.func(function(a){var b;b=a.real.v;a=a.imag.v;if(!Sk.builtin.complex._is_finite(b)||!Sk.builtin.complex._is_finite(a))return Sk.builtin.complex._is_infinity(b)?(b=Math.abs(b),new Sk.builtin.float_(b)):Sk.builtin.complex._is_infinity(a)?(b=Math.abs(a),new Sk.builtin.float_(b)):new Sk.builtin.float_(NaN);b=Math.hypot(b,a);if(!Sk.builtin.complex._is_finite(b))throw new Sk.builtin.OverflowError("absolute value too large");return new Sk.builtin.float_(b)});
Sk.builtin.complex.prototype.__bool__=new Sk.builtin.func(function(a){return new Sk.builtin.bool(a.tp$getattr("real").v||a.tp$getattr("real").v)});Sk.builtin.complex.prototype.__truediv__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__truediv__",arguments,1,1,!0);return a.nb$divide.call(a,b)});Sk.builtin.complex.prototype.__hash__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__hash__",arguments,0,0,!0);return a.tp$hash.call(a)});
Sk.builtin.complex.prototype.__add__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__add__",arguments,1,1,!0);return a.nb$add.call(a,b)});Sk.builtin.complex.prototype.__repr__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__repr__",arguments,0,0,!0);return a.r$.call(a)});Sk.builtin.complex.prototype.__str__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__str__",arguments,0,0,!0);return a.tp$str.call(a)});
Sk.builtin.complex.prototype.__sub__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__sub__",arguments,1,1,!0);return a.nb$subtract.call(a,b)});Sk.builtin.complex.prototype.__mul__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__mul__",arguments,1,1,!0);return a.nb$multiply.call(a,b)});Sk.builtin.complex.prototype.__div__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__div__",arguments,1,1,!0);return a.nb$divide.call(a,b)});
Sk.builtin.complex.prototype.__floordiv__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__floordiv__",arguments,1,1,!0);return a.nb$floor_divide.call(a,b)});Sk.builtin.complex.prototype.__mod__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__mod__",arguments,1,1,!0);return a.nb$remainder.call(a,b)});Sk.builtin.complex.prototype.__pow__=new Sk.builtin.func(function(a,b,c){Sk.builtin.pyCheckArgs("__pow__",arguments,1,2,!0);return a.nb$power.call(a,b,c)});
Sk.builtin.complex.prototype.__neg__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__neg__",arguments,0,0,!0);return a.nb$negative.call(a)});Sk.builtin.complex.prototype.__pos__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__pos__",arguments,0,0,!0);return a.nb$positive.call(a)});Sk.builtin.complex.prototype.conjugate=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("conjugate",arguments,0,0,!0);var b=a.imag.v;return new Sk.builtin.complex(a.real,new Sk.builtin.float_(-b))});
Sk.builtin.complex.prototype.__divmod__=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("__divmod__",arguments,1,1,!0);var c,d,e;d=Sk.builtin.complex.check_number_or_complex(a);e=Sk.builtin.complex.check_number_or_complex(b);c=d.nb$divide.call(d,e);c.real=new Sk.builtin.float_(Math.floor(c.real.v));c.imag=new Sk.builtin.float_(0);d=d.nb$subtract.call(d,e.nb$multiply.call(e,c));return new Sk.builtin.tuple([c,d])});
Sk.builtin.complex.prototype.__getnewargs__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__getnewargs__",arguments,0,0,!0);return new Sk.builtin.tuple([a.real,a.imag])});Sk.builtin.complex.prototype.__nonzero__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__nonzero__",arguments,0,0,!0);return 0!==a.real.v||0!==a.imag.v?Sk.builtin.bool.true$:Sk.builtin.bool.false$});goog.exportSymbol("Sk.builtin.complex",Sk.builtin.complex);
Sk.builtin.complex.PyOS_double_to_string=function(a,b,c,d,e){e=!1;switch(b){case "e":case "f":case "g":break;case "E":e=!0;b="e";break;case "F":e=!0;b="f";break;case "r":if(0!==c)throw Error("Bad internall call");c=17;b="g";break;default:throw Error("Bad internall call");}if(isNaN(a))a="nan";else if(Infinity===a)a="inf";else if(-Infinity===a)a="-inf";else{d&Sk.builtin.complex.PyOS_double_to_string.Py_DTSF_ADD_DOT_0&&(b="g");var f;f="%"+(d&Sk.builtin.complex.PyOS_double_to_string.Py_DTSF_ALT?"#":"");
null!=c&&(f=f+"."+c);f+=b;f=new Sk.builtin.str(f);a=f.nb$remainder(new Sk.builtin.float_(a));a=a.v}d&Sk.builtin.complex.PyOS_double_to_string.Py_DTSF_SIGN&&"-"!==a[0]&&(a="+"+a);e&&(a=a.toUpperCase());return a};Sk.builtin.complex.PyOS_double_to_string.Py_DTSF_SIGN=1;Sk.builtin.complex.PyOS_double_to_string.Py_DTSF_ADD_DOT_0=2;Sk.builtin.complex.PyOS_double_to_string.Py_DTSF_ALT=4;Sk.builtin.complex.PyOS_double_to_string.Py_DTST_FINITE=0;Sk.builtin.complex.PyOS_double_to_string.Py_DTST_INFINITE=1;
Sk.builtin.complex.PyOS_double_to_string.Py_DTST_NAN=2;Sk.builtin.slice=function(a,b,c){Sk.builtin.pyCheckArgs("slice",arguments,1,3,!1,!1);if(void 0!==c&&Sk.misceval.isIndex(c)&&0===Sk.misceval.asIndex(c))throw new Sk.builtin.ValueError("slice step cannot be zero");if(!(this instanceof Sk.builtin.slice))return new Sk.builtin.slice(a,b,c);void 0===b&&void 0===c&&(b=a,a=Sk.builtin.none.none$);void 0===b&&(b=Sk.builtin.none.none$);void 0===c&&(c=Sk.builtin.none.none$);this.start=a;this.stop=b;this.step=c;this.__class__=Sk.builtin.slice;this.$d=new Sk.builtin.dict([Sk.builtin.slice$start,
this.start,Sk.builtin.slice$stop,this.stop,Sk.builtin.slice$step,this.step]);return this};Sk.abstr.setUpInheritance("slice",Sk.builtin.slice,Sk.builtin.object);Sk.builtin.slice.prototype.$r=function(){var a=Sk.builtin.repr(this.start).v,b=Sk.builtin.repr(this.stop).v,c=Sk.builtin.repr(this.step).v;return new Sk.builtin.str("slice("+a+", "+b+", "+c+")")};
Sk.builtin.slice.prototype.tp$richcompare=function(a,b){var c,d;if(!a.__class__||a.__class__!=Sk.builtin.slice)return"Eq"===b?!1:"NotEq"===b?!0:!1;c=new Sk.builtin.tuple([this.start,this.stop,this.step]);d=new Sk.builtin.tuple([a.start,a.stop,a.step]);return c.tp$richcompare(d,b)};
Sk.builtin.slice.prototype.slice_indices_=function(a){var b,c,d;if(Sk.builtin.checkNone(this.start))b=null;else if(Sk.misceval.isIndex(this.start))b=Sk.misceval.asIndex(this.start);else throw new Sk.builtin.TypeError("slice indices must be integers or None");if(Sk.builtin.checkNone(this.stop))c=null;else if(Sk.misceval.isIndex(this.stop))c=Sk.misceval.asIndex(this.stop);else throw new Sk.builtin.TypeError("slice indices must be integers or None");if(Sk.builtin.checkNone(this.step))d=null;else if(Sk.misceval.isIndex(this.step))d=
Sk.misceval.asIndex(this.step);else throw new Sk.builtin.TypeError("slice indices must be integers or None");null===d&&(d=1);0<d?(null===b&&(b=0),null===c&&(c=a),c>a&&(c=a),0>b&&(b=a+b,0>b&&(b=0)),0>c&&(c=a+c)):(null===b&&(b=a-1),b>=a&&(b=a-1),null===c?c=-1:0>c&&(c=a+c,0>c&&(c=-1)),0>b&&(b=a+b));return[b,c,d]};
Sk.builtin.slice.prototype.indices=new Sk.builtin.func(function(a,b){Sk.builtin.pyCheckArgs("indices",arguments,2,2,!1,!1);b=Sk.builtin.asnum$(b);var c=a.slice_indices_(b);return new Sk.builtin.tuple([new Sk.builtin.int_(c[0]),new Sk.builtin.int_(c[1]),new Sk.builtin.int_(c[2])])});
Sk.builtin.slice.prototype.sssiter$=function(a,b){var c,d=Sk.builtin.asnum$(a),e=this.slice_indices_("number"===typeof d?d:a.v.length);if(0<e[2])for(c=e[0];c<e[1]&&!1!==b(c,d);c+=e[2]);else for(c=e[0];c>e[1]&&!1!==b(c,d);c+=e[2]);};Sk.builtin.slice$start=new Sk.builtin.str("start");Sk.builtin.slice$stop=new Sk.builtin.str("stop");Sk.builtin.slice$step=new Sk.builtin.str("step");Sk.builtin.set=function(a){var b;if(!(this instanceof Sk.builtin.set))return new Sk.builtin.set(a);"undefined"===typeof a&&(a=[]);this.set_reset_();a=new Sk.builtin.list(a);a=Sk.abstr.iter(a);for(b=a.tp$iternext();void 0!==b;b=a.tp$iternext())Sk.builtin.set.prototype.add.func_code(this,b);this.__class__=Sk.builtin.set;this.v=this.v;return this};Sk.abstr.setUpInheritance("set",Sk.builtin.set,Sk.builtin.object);Sk.abstr.markUnhashable(Sk.builtin.set);
Sk.builtin.set.prototype.set_iter_=function(){var a=this.v.tp$iter();a.tp$name="set_iterator";return a};Sk.builtin.set.prototype.set_reset_=function(){this.v=new Sk.builtin.dict([])};Sk.builtin.set.prototype.$r=function(){var a,b,c=[];a=Sk.abstr.iter(this);for(b=a.tp$iternext();void 0!==b;b=a.tp$iternext())c.push(Sk.misceval.objectRepr(b).v);return Sk.python3?new Sk.builtin.str("{"+c.join(", ")+"}"):new Sk.builtin.str("set(["+c.join(", ")+"])")};
Sk.builtin.set.prototype.ob$eq=function(a){return this===a?Sk.builtin.bool.true$:a instanceof Sk.builtin.set&&Sk.builtin.set.prototype.sq$length.call(this)===Sk.builtin.set.prototype.sq$length.call(a)?this.issubset.func_code(this,a):Sk.builtin.bool.false$};
Sk.builtin.set.prototype.ob$ne=function(a){return this===a?Sk.builtin.bool.false$:a instanceof Sk.builtin.set&&Sk.builtin.set.prototype.sq$length.call(this)===Sk.builtin.set.prototype.sq$length.call(a)?this.issubset.func_code(this,a).v?Sk.builtin.bool.false$:Sk.builtin.bool.true$:Sk.builtin.bool.true$};
Sk.builtin.set.prototype.ob$lt=function(a){return this===a||Sk.builtin.set.prototype.sq$length.call(this)>=Sk.builtin.set.prototype.sq$length.call(a)?Sk.builtin.bool.false$:this.issubset.func_code(this,a)};Sk.builtin.set.prototype.ob$le=function(a){return this===a?Sk.builtin.bool.true$:Sk.builtin.set.prototype.sq$length.call(this)>Sk.builtin.set.prototype.sq$length.call(a)?Sk.builtin.bool.false$:this.issubset.func_code(this,a)};
Sk.builtin.set.prototype.ob$gt=function(a){return this===a||Sk.builtin.set.prototype.sq$length.call(this)<=Sk.builtin.set.prototype.sq$length.call(a)?Sk.builtin.bool.false$:this.issuperset.func_code(this,a)};Sk.builtin.set.prototype.ob$ge=function(a){return this===a?Sk.builtin.bool.true$:Sk.builtin.set.prototype.sq$length.call(this)<Sk.builtin.set.prototype.sq$length.call(a)?Sk.builtin.bool.false$:this.issuperset.func_code(this,a)};
Sk.builtin.set.prototype.__iter__=new Sk.builtin.func(function(a){Sk.builtin.pyCheckArgs("__iter__",arguments,0,0,!1,!0);return Sk.builtin.set.prototype.tp$iter.call(a)});Sk.builtin.set.prototype.tp$iter=Sk.builtin.set.prototype.set_iter_;Sk.builtin.set.prototype.sq$length=function(){return this.v.mp$length()};Sk.builtin.set.prototype.sq$contains=function(a){return this.v.sq$contains(a)};
Sk.builtin.set.prototype.isdisjoint=new Sk.builtin.func(function(a,b){var c,d;d=Sk.abstr.iter(a);for(c=d.tp$iternext();void 0!==c;c=d.tp$iternext())if(c=Sk.abstr.sequenceContains(b,c))return Sk.builtin.bool.false$;return Sk.builtin.bool.true$});
Sk.builtin.set.prototype.issubset=new Sk.builtin.func(function(a,b){var c,d;d=a.sq$length();c=b.sq$length();if(d>c)return Sk.builtin.bool.false$;d=Sk.abstr.iter(a);for(c=d.tp$iternext();void 0!==c;c=d.tp$iternext())if(c=Sk.abstr.sequenceContains(b,c),!c)return Sk.builtin.bool.false$;return Sk.builtin.bool.true$});Sk.builtin.set.prototype.issuperset=new Sk.builtin.func(function(a,b){return Sk.builtin.set.prototype.issubset.func_code(b,a)});
Sk.builtin.set.prototype.union=new Sk.builtin.func(function(a){var b,c=new Sk.builtin.set(a);for(b=1;b<arguments.length;b++)Sk.builtin.set.prototype.update.func_code(c,arguments[b]);return c});Sk.builtin.set.prototype.intersection=new Sk.builtin.func(function(a){var b=Sk.builtin.set.prototype.copy.func_code(a),c=Array.prototype.slice.call(arguments);c[0]=b;Sk.builtin.set.prototype.intersection_update.func_code.apply(null,c);return b});
Sk.builtin.set.prototype.difference=new Sk.builtin.func(function(a,b){var c=Sk.builtin.set.prototype.copy.func_code(a),d=Array.prototype.slice.call(arguments);d[0]=c;Sk.builtin.set.prototype.difference_update.func_code.apply(null,d);return c});
Sk.builtin.set.prototype.symmetric_difference=new Sk.builtin.func(function(a,b){var c,d,e=Sk.builtin.set.prototype.union.func_code(a,b);c=Sk.abstr.iter(e);for(d=c.tp$iternext();void 0!==d;d=c.tp$iternext())Sk.abstr.sequenceContains(a,d)&&Sk.abstr.sequenceContains(b,d)&&Sk.builtin.set.prototype.discard.func_code(e,d);return e});Sk.builtin.set.prototype.copy=new Sk.builtin.func(function(a){return new Sk.builtin.set(a)});
Sk.builtin.set.prototype.update=new Sk.builtin.func(function(a,b){var c,d;c=Sk.abstr.iter(b);for(d=c.tp$iternext();void 0!==d;d=c.tp$iternext())Sk.builtin.set.prototype.add.func_code(a,d);return Sk.builtin.none.none$});
Sk.builtin.set.prototype.intersection_update=new Sk.builtin.func(function(a,b){var c,d,e;d=Sk.abstr.iter(a);for(e=d.tp$iternext();void 0!==e;e=d.tp$iternext())for(c=1;c<arguments.length;c++)if(!Sk.abstr.sequenceContains(arguments[c],e)){Sk.builtin.set.prototype.discard.func_code(a,e);break}return Sk.builtin.none.none$});
Sk.builtin.set.prototype.difference_update=new Sk.builtin.func(function(a,b){var c,d,e;d=Sk.abstr.iter(a);for(e=d.tp$iternext();void 0!==e;e=d.tp$iternext())for(c=1;c<arguments.length;c++)if(Sk.abstr.sequenceContains(arguments[c],e)){Sk.builtin.set.prototype.discard.func_code(a,e);break}return Sk.builtin.none.none$});
Sk.builtin.set.prototype.symmetric_difference_update=new Sk.builtin.func(function(a,b){var c=Sk.builtin.set.prototype.symmetric_difference.func_code(a,b);a.set_reset_();Sk.builtin.set.prototype.update.func_code(a,c);return Sk.builtin.none.none$});Sk.builtin.set.prototype.add=new Sk.builtin.func(function(a,b){a.v.mp$ass_subscript(b,!0);return Sk.builtin.none.none$});
Sk.builtin.set.prototype.discard=new Sk.builtin.func(function(a,b){Sk.builtin.dict.prototype.pop.func_code(a.v,b,Sk.builtin.none.none$);return Sk.builtin.none.none$});Sk.builtin.set.prototype.pop=new Sk.builtin.func(function(a){var b;if(0===a.sq$length())throw new Sk.builtin.KeyError("pop from an empty set");b=Sk.abstr.iter(a).tp$iternext();Sk.builtin.set.prototype.discard.func_code(a,b);return b});Sk.builtin.set.prototype.remove=new Sk.builtin.func(function(a,b){a.v.mp$del_subscript(b);return Sk.builtin.none.none$});
goog.exportSymbol("Sk.builtin.set",Sk.builtin.set);var print_f=function(a){Sk.builtin.pyCheckArgs("print",arguments,0,Infinity,!0,!1);var b=Array.prototype.slice.call(arguments,1),c=new Sk.builtins.dict(a);Sk.ffi.remapToJs(c);var d={sep:" ",end:"\n",file:null},e,f;e=c.mp$lookup(new Sk.builtin.str("sep"));if(void 0!==e)if(f=Sk.builtin.checkNone(e),Sk.builtin.checkString(e)||f)d.sep=f?d.sep:Sk.ffi.remapToJs(e);else throw new Sk.builtin.TypeError("sep must be None or a string, not "+Sk.abstr.typeName(e));e=c.mp$lookup(new Sk.builtin.str("end"));if(void 0!==
e)if(f=Sk.builtin.checkNone(e),Sk.builtin.checkString(e)||f)d.end=f?d.end:Sk.ffi.remapToJs(e);else throw new Sk.builtin.TypeError("end must be None or a string, not "+Sk.abstr.typeName(e));e=c.mp$lookup(new Sk.builtin.str("file"));if(void 0!==e)if((f=Sk.builtin.checkNone(e))||void 0!==e.tp$getattr("write"))d.file=f?d.file:e;else throw new Sk.builtin.AttributeError("'"+Sk.abstr.typeName(e)+"' object has no attribute 'write'");c="";for(e=0;e<b.length;e++)c+=(new Sk.builtin.str(b[e])).v,c+=d.sep;0<b.length&&
0<d.sep.length&&(c=c.substring(0,c.length-d.sep.length));c+=d.end;null!==d.file?Sk.misceval.callsim(d.file.write,d.file,new Sk.builtin.str(c)):Sk.output(c)};print_f.co_kwargs=!0;Sk.builtin.print=new Sk.builtin.func(print_f);Sk.builtin.print.__doc__=new Sk.builtin.str("print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream.");Sk.builtin.module=function(){};goog.exportSymbol("Sk.builtin.module",Sk.builtin.module);Sk.builtin.module.prototype.ob$type=Sk.builtin.type.makeIntoTypeObj("module",Sk.builtin.module);Sk.builtin.module.prototype.tp$getattr=Sk.builtin.object.prototype.GenericGetAttr;Sk.builtin.module.prototype.tp$setattr=Sk.builtin.object.prototype.GenericSetAttr;Sk.builtin.structseq_types={};
Sk.builtin.make_structseq=function(a,b,c){function d(a){return function(){return this.v[a]}}var e=a+"."+b;a=function(a){Sk.builtin.pyCheckArgs(e,arguments,1,1);var b;if(!(this instanceof Sk.builtin.structseq_types[e]))return b=Object.create(Sk.builtin.structseq_types[e].prototype),b.constructor.apply(b,arguments),b;var d;if("[object Array]"===Object.prototype.toString.apply(a))this.v=a;else if(this.v=[],a.tp$iter){var k=0;b=a.tp$iter();for(d=b.tp$iternext();void 0!==d&&k<c.length;d=b.tp$iternext())this.v.push(d),
k++;if(k<c.length)throw new Sk.builtin.TypeError(e+"() takes a "+c.length+"-sequence ("+k+"-sequence given)");}else if(a.__getitem__)for(b=0;b<=c.length;b++)Sk.misceval.apply(a.__getitem__,void 0,void 0,void 0,[Sk.builtin.asnum$(b)]);else throw new Sk.builtin.TypeError("constructor requires a sequence");Sk.builtin.tuple.apply(this,arguments);this.__class__=Sk.builtin.structseq_types[e]};a.co_kwargs=!0;Sk.builtin.structseq_types[e]=a;goog.inherits(a,Sk.builtin.tuple);a.prototype.tp$name=e;a.prototype.ob$type=
Sk.builtin.type.makeIntoTypeObj(e,Sk.builtin.structseq_types[e]);a.prototype.ob$type.$d=new Sk.builtin.dict([]);a.prototype.ob$type.$d.mp$ass_subscript(Sk.builtin.type.basesStr_,new Sk.builtin.tuple([Sk.builtin.tuple]));a.prototype.__getitem__=new Sk.builtin.func(function(a,b){return Sk.builtin.tuple.prototype.mp$subscript.call(a,b)});for(b=0;b<c.length;b++)a.prototype[c[b]]=d;a.prototype.$r=function(){var a,b;if(0===this.v.length)return new Sk.builtin.str(e+"()");b=[];for(a=0;a<this.v.length;++a)b[a]=
c[a]+"="+Sk.misceval.objectRepr(this.v[a]).v;a=b.join(", ");1===this.v.length&&(a+=",");return new Sk.builtin.str(e+"("+a+")")};a.prototype.tp$setattr=function(a,b){var d=c.indexOf(a);0<=d&&(this.v[d]=b)};return a};goog.exportSymbol("Sk.builtin.make_structseq",Sk.builtin.make_structseq);Sk.builtin.generator=function(a,b,c,d,e){var f;if(a){if(!(this instanceof Sk.builtin.generator))return new Sk.builtin.generator(a,b,c,d,e);this.func_code=a;this.func_globals=b||null;this.gi$running=!1;this.gi$resumeat=0;this.gi$sentvalue=void 0;this.gi$locals={};this.gi$cells={};if(0<c.length)for(b=0;b<a.co_varnames.length;++b)this.gi$locals[a.co_varnames[b]]=c[b];if(void 0!==e)for(f in e)d[f]=e[f];this.func_closure=d;return this}};goog.exportSymbol("Sk.builtin.generator",Sk.builtin.generator);
Sk.abstr.setUpInheritance("generator",Sk.builtin.generator,Sk.builtin.object);Sk.builtin.generator.prototype.tp$iter=function(){return this};
Sk.builtin.generator.prototype.tp$iternext=function(a,b){var c,d=this;this.gi$running=!0;void 0===b&&(b=null);this.gi$sentvalue=b;c=[this];this.func_closure&&c.push(this.func_closure);return function f(b){if(b instanceof Sk.misceval.Suspension){if(a)return new Sk.misceval.Suspension(f,b);b=Sk.misceval.retryOptionalSuspensionOrThrow(b)}d.gi$running=!1;goog.asserts.assert(void 0!==b);if(b!==Sk.builtin.none.none$)return d.gi$resumeat=b[0],b=b[1]}(this.func_code.apply(this.func_globals,c))};
Sk.builtin.generator.prototype.next=new Sk.builtin.func(function(a){return a.tp$iternext(!0)});Sk.builtin.generator.prototype.$r=function(){return new Sk.builtin.str("<generator object "+this.func_code.co_name.v+">")};Sk.builtin.generator.prototype.send=new Sk.builtin.func(function(a,b){return a.tp$iternext(!0,b)});Sk.builtin.makeGenerator=function(a,b){var c,d=new Sk.builtin.generator(null,null,null);d.tp$iternext=a;for(c in b)b.hasOwnProperty(c)&&(d[c]=b[c]);return d};
goog.exportSymbol("Sk.builtin.makeGenerator",Sk.builtin.makeGenerator);Sk.builtin.file=function(a,b,c){var d;if(!(this instanceof Sk.builtin.file))return new Sk.builtin.file(a,b,c);this.mode=b;this.name=a;this.closed=!1;if(Sk.inBrowser){b=document.getElementById(a.v);if(null==b)throw new Sk.builtin.IOError("[Errno 2] No such file or directory: '"+a.v+"'");"textarea"==b.nodeName.toLowerCase()?this.data$=b.value:this.data$=b.textContent}else this.data$=Sk.read(a.v);this.lineList=this.data$.split("\n");this.lineList=this.lineList.slice(0,-1);for(d in this.lineList)this.lineList[d]+=
"\n";this.pos$=this.currentLine=0;this.__class__=Sk.builtin.file;return this};Sk.abstr.setUpInheritance("file",Sk.builtin.file,Sk.builtin.object);Sk.builtin.file.prototype.$r=function(){return new Sk.builtin.str("<"+(this.closed?"closed":"open")+"file '"+this.name+"', mode '"+this.mode+"'>")};
Sk.builtin.file.prototype.tp$iter=function(){var a={tp$iter:function(){return a},$obj:this,$index:0,$lines:this.lineList,tp$iternext:function(){return a.$index>=a.$lines.length?void 0:new Sk.builtin.str(a.$lines[a.$index++])}};return a};Sk.builtin.file.prototype.close=new Sk.builtin.func(function(a){a.closed=!0});Sk.builtin.file.prototype.flush=new Sk.builtin.func(function(a){});Sk.builtin.file.prototype.fileno=new Sk.builtin.func(function(a){return 10});Sk.builtin.file.prototype.isatty=new Sk.builtin.func(function(a){return!1});
Sk.builtin.file.prototype.read=new Sk.builtin.func(function(a,b){var c,d;if(a.closed)throw new Sk.builtin.ValueError("I/O operation on closed file");d=a.data$.length;void 0===b&&(b=d);c=new Sk.builtin.str(a.data$.substr(a.pos$,b));a.pos$+=b;a.pos$>=d&&(a.pos$=d);return c});Sk.builtin.file.prototype.readline=new Sk.builtin.func(function(a,b){var c="";a.currentLine<a.lineList.length&&(c=a.lineList[a.currentLine],a.currentLine++);return new Sk.builtin.str(c)});
Sk.builtin.file.prototype.readlines=new Sk.builtin.func(function(a,b){var c,d=[];for(c=a.currentLine;c<a.lineList.length;c++)d.push(new Sk.builtin.str(a.lineList[c]));return new Sk.builtin.list(d)});Sk.builtin.file.prototype.seek=new Sk.builtin.func(function(a,b,c){void 0===c&&(c=1);a.pos$=1==c?b:a.data$+b});Sk.builtin.file.prototype.tell=new Sk.builtin.func(function(a){return a.pos$});Sk.builtin.file.prototype.truncate=new Sk.builtin.func(function(a,b){goog.asserts.fail()});
Sk.builtin.file.prototype.write=new Sk.builtin.func(function(a,b){goog.asserts.fail()});goog.exportSymbol("Sk.builtin.file",Sk.builtin.file);Sk.ffi=Sk.ffi||{};
Sk.ffi.remapToPy=function(a){var b,c;if("[object Array]"===Object.prototype.toString.call(a)){c=[];for(b=0;b<a.length;++b)c.push(Sk.ffi.remapToPy(a[b]));return new Sk.builtin.list(c)}if("object"===typeof a){c=[];for(b in a)c.push(Sk.ffi.remapToPy(b)),c.push(Sk.ffi.remapToPy(a[b]));return new Sk.builtin.dict(c)}if("string"===typeof a)return new Sk.builtin.str(a);if("number"===typeof a)return Sk.builtin.assk$(a);if("boolean"===typeof a)return a;goog.asserts.fail("unhandled remap type "+typeof a)};
goog.exportSymbol("Sk.ffi.remapToPy",Sk.ffi.remapToPy);
Sk.ffi.remapToJs=function(a){var b,c,d,e;if(a instanceof Sk.builtin.dict){e={};d=a.tp$iter();for(c=d.tp$iternext();void 0!==c;c=d.tp$iternext())b=a.mp$subscript(c),void 0===b&&(b=null),c=Sk.ffi.remapToJs(c),e[c]=Sk.ffi.remapToJs(b);return e}if(a instanceof Sk.builtin.list||a instanceof Sk.builtin.tuple){e=[];for(b=0;b<a.v.length;++b)e.push(Sk.ffi.remapToJs(a.v[b]));return e}return a instanceof Sk.builtin.int_?Sk.builtin.asnum$(a):a instanceof Sk.builtin.float_?Sk.builtin.asnum$(a):a instanceof Sk.builtin.lng?
Sk.builtin.asnum$(a):"number"===typeof a||"boolean"===typeof a?a:a.v};goog.exportSymbol("Sk.ffi.remapToJs",Sk.ffi.remapToJs);Sk.ffi.callback=function(a){return void 0===a?a:function(){return Sk.misceval.apply(a,void 0,void 0,void 0,Array.prototype.slice.call(arguments,0))}};goog.exportSymbol("Sk.ffi.callback",Sk.ffi.callback);Sk.ffi.stdwrap=function(a,b){var c=new a;c.v=b;return c};goog.exportSymbol("Sk.ffi.stdwrap",Sk.ffi.stdwrap);
Sk.ffi.basicwrap=function(a){if(a instanceof Sk.builtin.int_)return Sk.builtin.asnum$(a);if(a instanceof Sk.builtin.float_)return Sk.builtin.asnum$(a);if(a instanceof Sk.builtin.lng)return Sk.builtin.asnum$(a);if("number"===typeof a||"boolean"===typeof a)return a;if("string"===typeof a)return new Sk.builtin.str(a);goog.asserts.fail("unexpected type for basicwrap")};goog.exportSymbol("Sk.ffi.basicwrap",Sk.ffi.basicwrap);Sk.ffi.unwrapo=function(a){return void 0===a?void 0:a.v};
goog.exportSymbol("Sk.ffi.unwrapo",Sk.ffi.unwrapo);Sk.ffi.unwrapn=function(a){return null===a?null:a.v};goog.exportSymbol("Sk.ffi.unwrapn",Sk.ffi.unwrapn);Sk.builtin.enumerate=function(a,b){var c;if(!(this instanceof Sk.builtin.enumerate))return new Sk.builtin.enumerate(a,b);Sk.builtin.pyCheckArgs("enumerate",arguments,1,2);if(!Sk.builtin.checkIterable(a))throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(a)+"' object is not iterable");if(void 0!==b)if(Sk.misceval.isIndex(b))b=Sk.misceval.asIndex(b);else throw new Sk.builtin.TypeError("'"+Sk.abstr.typeName(b)+"' object cannot be interpreted as an index");else b=0;c=a.tp$iter();this.tp$iter=function(){return this};
this.$index=b;this.tp$iternext=function(){var a,b=c.tp$iternext();if(void 0!==b)return a=new Sk.builtin.int_(this.$index++),new Sk.builtin.tuple([a,b])};this.__class__=Sk.builtin.enumerate;return this};Sk.abstr.setUpInheritance("enumerate",Sk.builtin.enumerate,Sk.builtin.object);Sk.builtin.enumerate.prototype.__iter__=new Sk.builtin.func(function(a){return a.tp$iter()});Sk.builtin.enumerate.prototype.next=new Sk.builtin.func(function(a){return a.tp$iternext()});Sk.builtin.enumerate.prototype.$r=function(){return new Sk.builtin.str("<enumerate object>")};Sk.Tokenizer=function(a,b,c){this.filename=a;this.callback=c;this.parenlev=this.lnum=0;this.continued=!1;this.namechars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";this.numchars="0123456789";this.contstr="";this.needcont=!1;this.contline=void 0;this.indents=[0];this.endprog=/.*/;this.strstart=[-1,-1];this.interactive=b;this.doneFunc=function(){var a;for(a=1;a<this.indents.length;++a)if(this.callback(Sk.Tokenizer.Tokens.T_DEDENT,"",[this.lnum,0],[this.lnum,0],""))return"done";return this.callback(Sk.Tokenizer.Tokens.T_ENDMARKER,
"",[this.lnum,0],[this.lnum,0],"")?"done":"failed"}};
Sk.Tokenizer.Tokens={T_ENDMARKER:0,T_NAME:1,T_NUMBER:2,T_STRING:3,T_NEWLINE:4,T_INDENT:5,T_DEDENT:6,T_LPAR:7,T_RPAR:8,T_LSQB:9,T_RSQB:10,T_COLON:11,T_COMMA:12,T_SEMI:13,T_PLUS:14,T_MINUS:15,T_STAR:16,T_SLASH:17,T_VBAR:18,T_AMPER:19,T_LESS:20,T_GREATER:21,T_EQUAL:22,T_DOT:23,T_PERCENT:24,T_BACKQUOTE:25,T_LBRACE:26,T_RBRACE:27,T_EQEQUAL:28,T_NOTEQUAL:29,T_LESSEQUAL:30,T_GREATEREQUAL:31,T_TILDE:32,T_CIRCUMFLEX:33,T_LEFTSHIFT:34,T_RIGHTSHIFT:35,T_DOUBLESTAR:36,T_PLUSEQUAL:37,T_MINEQUAL:38,T_STAREQUAL:39,
T_SLASHEQUAL:40,T_PERCENTEQUAL:41,T_AMPEREQUAL:42,T_VBAREQUAL:43,T_CIRCUMFLEXEQUAL:44,T_LEFTSHIFTEQUAL:45,T_RIGHTSHIFTEQUAL:46,T_DOUBLESTAREQUAL:47,T_DOUBLESLASH:48,T_DOUBLESLASHEQUAL:49,T_AT:50,T_OP:51,T_COMMENT:52,T_NL:53,T_RARROW:54,T_ERRORTOKEN:55,T_N_TOKENS:56,T_NT_OFFSET:256};function group(a){return"("+Array.prototype.slice.call(arguments).join("|")+")"}function any(a){return group.apply(null,arguments)+"*"}function maybe(a){return group.apply(null,arguments)+"?"}
var Whitespace="[ \\f\\t]*",Comment_="#[^\\r\\n]*",Ident="[a-zA-Z_]\\w*",Binnumber="0[bB][01]*",Hexnumber="0[xX][\\da-fA-F]*[lL]?",Octnumber="0[oO]?[0-7]*[lL]?",Decnumber="[1-9]\\d*[lL]?",Intnumber=group(Binnumber,Hexnumber,Octnumber,Decnumber),Exponent="[eE][-+]?\\d+",Pointfloat=group("\\d+\\.\\d*","\\.\\d+")+maybe(Exponent),Expfloat="\\d+"+Exponent,Floatnumber=group(Pointfloat,Expfloat),Imagnumber=group("\\d+[jJ]",Floatnumber+"[jJ]"),Number_=group(Imagnumber,Floatnumber,Intnumber),Single="^[^'\\\\]*(?:\\\\.[^'\\\\]*)*'",
Double_='^[^"\\\\]*(?:\\\\.[^"\\\\]*)*"',Single3="[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''",Double3='[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""',Triple=group("[ubUB]?[rR]?'''",'[ubUB]?[rR]?"""'),String_=group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'",'[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*"'),Operator=group("\\*\\*=?",">>=?","<<=?","<>","!=","//=?","->","[+\\-*/%&|^=<>]=?","~"),Bracket="[\\][(){}]",Special=group("\\r?\\n","[:;.,`@]"),Funny=group(Operator,Bracket,Special),ContStr=
group("[uUbB]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*"+group("'","\\\\\\r?\\n"),'[uUbB]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*'+group('"',"\\\\\\r?\\n")),PseudoExtras=group("\\\\\\r?\\n",Comment_,Triple),PseudoToken="^"+group(PseudoExtras,Number_,Funny,ContStr,Ident),triple_quoted={"'''":!0,'"""':!0,"r'''":!0,'r"""':!0,"R'''":!0,'R"""':!0,"u'''":!0,'u"""':!0,"U'''":!0,'U"""':!0,"b'''":!0,'b"""':!0,"B'''":!0,'B"""':!0,"ur'''":!0,'ur"""':!0,"Ur'''":!0,'Ur"""':!0,"uR'''":!0,'uR"""':!0,"UR'''":!0,
'UR"""':!0,"br'''":!0,'br"""':!0,"Br'''":!0,'Br"""':!0,"bR'''":!0,'bR"""':!0,"BR'''":!0,'BR"""':!0},single_quoted={"'":!0,'"':!0,"r'":!0,'r"':!0,"R'":!0,'R"':!0,"u'":!0,'u"':!0,"U'":!0,'U"':!0,"b'":!0,'b"':!0,"B'":!0,'B"':!0,"ur'":!0,'ur"':!0,"Ur'":!0,'Ur"':!0,"uR'":!0,'uR"':!0,"UR'":!0,'UR"':!0,"br'":!0,'br"':!0,"Br'":!0,'Br"':!0,"bR'":!0,'bR"':!0,"BR'":!0,'BR"':!0};(function(){for(var a in triple_quoted);for(a in single_quoted);})();var tabsize=8;
function contains(a,b){for(var c=a.length;c--;)if(a[c]===b)return!0;return!1}function rstrip(a,b){var c;for(c=a.length;0<c&&-1!==b.indexOf(a.charAt(c-1));--c);return a.substring(0,c)}
Sk.Tokenizer.prototype.generateTokens=function(a){var b,c,d,e,f,g,h,k;b=RegExp(PseudoToken);k=RegExp(Single3,"g");h=RegExp(Double3,"g");var l={"'":RegExp(Single,"g"),'"':RegExp(Double_,"g"),"'''":k,'"""':h,"r'''":k,'r"""':h,"u'''":k,'u"""':h,"b'''":k,'b"""':h,"ur'''":k,'ur"""':h,"br'''":k,'br"""':h,"R'''":k,'R"""':h,"U'''":k,'U"""':h,"B'''":k,'B"""':h,"uR'''":k,'uR"""':h,"Ur'''":k,'Ur"""':h,"UR'''":k,'UR"""':h,"bR'''":k,'bR"""':h,"Br'''":k,'Br"""':h,"BR'''":k,'BR"""':h,r:null,R:null,u:null,U:null,
b:null,B:null};a||(a="");this.lnum+=1;k=0;h=a.length;if(0<this.contstr.length){if(!a)throw new Sk.builtin.TokenError("EOF in multi-line string",this.filename,this.strstart[0],this.strstart[1],this.contline);this.endprog.lastIndex=0;if(f=this.endprog.test(a)){k=e=this.endprog.lastIndex;if(this.callback(Sk.Tokenizer.Tokens.T_STRING,this.contstr+a.substring(0,e),this.strstart,[this.lnum,e],this.contline+a))return"done";this.contstr="";this.needcont=!1;this.contline=void 0}else{if(this.needcont&&"\\\n"!==
a.substring(a.length-2)&&"\\\r\n"!==a.substring(a.length-3)){if(this.callback(Sk.Tokenizer.Tokens.T_ERRORTOKEN,this.contstr+a,this.strstart,[this.lnum,a.length],this.contline))return"done";this.contstr="";this.contline=void 0}else this.contstr+=a,this.contline+=a;return!1}}else if(0!==this.parenlev||this.continued){if(!a)throw new Sk.builtin.TokenError("EOF in multi-line statement",this.filename,this.lnum,0,a);this.continued=!1}else{if(!a)return this.doneFunc();for(g=0;k<h;){if(" "===a.charAt(k))g+=
1;else if("\t"===a.charAt(k))g=(g/tabsize+1)*tabsize;else if("\f"===a.charAt(k))g=0;else break;k+=1}if(k===h)return this.doneFunc();if(-1!=="#\r\n".indexOf(a.charAt(k))){if("#"===a.charAt(k))return h=rstrip(a.substring(k),"\r\n"),b=k+h.length,this.callback(Sk.Tokenizer.Tokens.T_COMMENT,h,[this.lnum,k],[this.lnum,k+h.length],a)||this.callback(Sk.Tokenizer.Tokens.T_NL,a.substring(b),[this.lnum,b],[this.lnum,a.length],a)?"done":!1;if(this.callback(Sk.Tokenizer.Tokens.T_NL,a.substring(k),[this.lnum,k],
[this.lnum,a.length],a))return"done";if(!this.interactive)return!1}if(g>this.indents[this.indents.length-1]&&(this.indents.push(g),this.callback(Sk.Tokenizer.Tokens.T_INDENT,a.substring(0,k),[this.lnum,0],[this.lnum,k],a)))return"done";for(;g<this.indents[this.indents.length-1];){if(!contains(this.indents,g))throw new Sk.builtin.IndentationError("unindent does not match any outer indentation level",this.filename,this.lnum,k,a);this.indents.splice(this.indents.length-1,1);if(this.callback(Sk.Tokenizer.Tokens.T_DEDENT,
"",[this.lnum,k],[this.lnum,k],a))return"done"}}for(;k<h;){for(g=a.charAt(k);" "===g||"\f"===g||"\t"===g;)k+=1,g=a.charAt(k);b.lastIndex=0;if(g=b.exec(a.substring(k)))if(c=k,e=c+g[1].length,g=[this.lnum,c],f=[this.lnum,e],k=e,e=a.substring(c,e),d=a.charAt(c),-1!==this.numchars.indexOf(d)||"."===d&&"."!==e){if(this.callback(Sk.Tokenizer.Tokens.T_NUMBER,e,g,f,a))return"done"}else if("\r"===d||"\n"===d){if(c=Sk.Tokenizer.Tokens.T_NEWLINE,0<this.parenlev&&(c=Sk.Tokenizer.Tokens.T_NL),this.callback(c,
e,g,f,a))return"done"}else if("#"===d){if(this.callback(Sk.Tokenizer.Tokens.T_COMMENT,e,g,f,a))return"done"}else if(triple_quoted.hasOwnProperty(e))if(this.endprog=l[e],this.endprog.lastIndex=0,f=this.endprog.test(a.substring(k))){if(k=this.endprog.lastIndex+k,e=a.substring(c,k),this.callback(Sk.Tokenizer.Tokens.T_STRING,e,g,[this.lnum,k],a))return"done"}else{this.strstart=[this.lnum,c];this.contstr=a.substring(c);this.contline=a;break}else if(single_quoted.hasOwnProperty(d)||single_quoted.hasOwnProperty(e.substring(0,
2))||single_quoted.hasOwnProperty(e.substring(0,3)))if("\n"===e[e.length-1]){this.strstart=[this.lnum,c];this.endprog=l[d]||l[e[1]]||l[e[2]];this.contstr=a.substring(c);this.needcont=!0;this.contline=a;break}else{if(this.callback(Sk.Tokenizer.Tokens.T_STRING,e,g,f,a))return"done"}else if(-1!==this.namechars.indexOf(d)){if(this.callback(Sk.Tokenizer.Tokens.T_NAME,e,g,f,a))return"done"}else if("\\"===d){if(this.callback(Sk.Tokenizer.Tokens.T_NL,e,g,[this.lnum,k],a))return"done";this.continued=!0}else{if(-1!==
"([{".indexOf(d)?this.parenlev+=1:-1!==")]}".indexOf(d)&&(this.parenlev-=1),this.callback(Sk.Tokenizer.Tokens.T_OP,e,g,f,a))return"done"}else{if(this.callback(Sk.Tokenizer.Tokens.T_ERRORTOKEN,a.charAt(k),[this.lnum,k],[this.lnum,k+1],a))return"done";k+=1}}return!1};
Sk.Tokenizer.tokenNames={0:"T_ENDMARKER",1:"T_NAME",2:"T_NUMBER",3:"T_STRING",4:"T_NEWLINE",5:"T_INDENT",6:"T_DEDENT",7:"T_LPAR",8:"T_RPAR",9:"T_LSQB",10:"T_RSQB",11:"T_COLON",12:"T_COMMA",13:"T_SEMI",14:"T_PLUS",15:"T_MINUS",16:"T_STAR",17:"T_SLASH",18:"T_VBAR",19:"T_AMPER",20:"T_LESS",21:"T_GREATER",22:"T_EQUAL",23:"T_DOT",24:"T_PERCENT",25:"T_BACKQUOTE",26:"T_LBRACE",27:"T_RBRACE",28:"T_EQEQUAL",29:"T_NOTEQUAL",30:"T_LESSEQUAL",31:"T_GREATEREQUAL",32:"T_TILDE",33:"T_CIRCUMFLEX",34:"T_LEFTSHIFT",
35:"T_RIGHTSHIFT",36:"T_DOUBLESTAR",37:"T_PLUSEQUAL",38:"T_MINEQUAL",39:"T_STAREQUAL",40:"T_SLASHEQUAL",41:"T_PERCENTEQUAL",42:"T_AMPEREQUAL",43:"T_VBAREQUAL",44:"T_CIRCUMFLEXEQUAL",45:"T_LEFTSHIFTEQUAL",46:"T_RIGHTSHIFTEQUAL",47:"T_DOUBLESTAREQUAL",48:"T_DOUBLESLASH",49:"T_DOUBLESLASHEQUAL",50:"T_AT",51:"T_OP",52:"T_COMMENT",53:"T_NL",54:"T_RARROW",55:"T_ERRORTOKEN",56:"T_N_TOKENS",256:"T_NT_OFFSET"};goog.exportSymbol("Sk.Tokenizer",Sk.Tokenizer);
goog.exportSymbol("Sk.Tokenizer.prototype.generateTokens",Sk.Tokenizer.prototype.generateTokens);goog.exportSymbol("Sk.Tokenizer.tokenNames",Sk.Tokenizer.tokenNames);Sk.OpMap={"(":Sk.Tokenizer.Tokens.T_LPAR,")":Sk.Tokenizer.Tokens.T_RPAR,"[":Sk.Tokenizer.Tokens.T_LSQB,"]":Sk.Tokenizer.Tokens.T_RSQB,":":Sk.Tokenizer.Tokens.T_COLON,",":Sk.Tokenizer.Tokens.T_COMMA,";":Sk.Tokenizer.Tokens.T_SEMI,"+":Sk.Tokenizer.Tokens.T_PLUS,"-":Sk.Tokenizer.Tokens.T_MINUS,"*":Sk.Tokenizer.Tokens.T_STAR,"/":Sk.Tokenizer.Tokens.T_SLASH,"|":Sk.Tokenizer.Tokens.T_VBAR,"&":Sk.Tokenizer.Tokens.T_AMPER,"<":Sk.Tokenizer.Tokens.T_LESS,">":Sk.Tokenizer.Tokens.T_GREATER,"=":Sk.Tokenizer.Tokens.T_EQUAL,
".":Sk.Tokenizer.Tokens.T_DOT,"%":Sk.Tokenizer.Tokens.T_PERCENT,"`":Sk.Tokenizer.Tokens.T_BACKQUOTE,"{":Sk.Tokenizer.Tokens.T_LBRACE,"}":Sk.Tokenizer.Tokens.T_RBRACE,"@":Sk.Tokenizer.Tokens.T_AT,"==":Sk.Tokenizer.Tokens.T_EQEQUAL,"!=":Sk.Tokenizer.Tokens.T_NOTEQUAL,"<>":Sk.Tokenizer.Tokens.T_NOTEQUAL,"<=":Sk.Tokenizer.Tokens.T_LESSEQUAL,">=":Sk.Tokenizer.Tokens.T_GREATEREQUAL,"~":Sk.Tokenizer.Tokens.T_TILDE,"^":Sk.Tokenizer.Tokens.T_CIRCUMFLEX,"<<":Sk.Tokenizer.Tokens.T_LEFTSHIFT,">>":Sk.Tokenizer.Tokens.T_RIGHTSHIFT,
"**":Sk.Tokenizer.Tokens.T_DOUBLESTAR,"+=":Sk.Tokenizer.Tokens.T_PLUSEQUAL,"-=":Sk.Tokenizer.Tokens.T_MINEQUAL,"*=":Sk.Tokenizer.Tokens.T_STAREQUAL,"/=":Sk.Tokenizer.Tokens.T_SLASHEQUAL,"%=":Sk.Tokenizer.Tokens.T_PERCENTEQUAL,"&=":Sk.Tokenizer.Tokens.T_AMPEREQUAL,"|=":Sk.Tokenizer.Tokens.T_VBAREQUAL,"^=":Sk.Tokenizer.Tokens.T_CIRCUMFLEXEQUAL,"<<=":Sk.Tokenizer.Tokens.T_LEFTSHIFTEQUAL,">>=":Sk.Tokenizer.Tokens.T_RIGHTSHIFTEQUAL,"**=":Sk.Tokenizer.Tokens.T_DOUBLESTAREQUAL,"//":Sk.Tokenizer.Tokens.T_DOUBLESLASH,
"//=":Sk.Tokenizer.Tokens.T_DOUBLESLASHEQUAL,"->":Sk.Tokenizer.Tokens.T_RARROW};
Sk.ParseTables={sym:{and_expr:257,and_test:258,arglist:259,argument:260,arith_expr:261,assert_stmt:262,atom:263,augassign:264,break_stmt:265,classdef:266,comp_for:267,comp_if:268,comp_iter:269,comp_op:270,comparison:271,compound_stmt:272,continue_stmt:273,debugger_stmt:274,decorated:275,decorator:276,decorators:277,del_stmt:278,dictorsetmaker:279,dotted_as_name:280,dotted_as_names:281,dotted_name:282,encoding_decl:283,eval_input:284,except_clause:285,exec_stmt:286,expr:287,expr_stmt:288,exprlist:289,
factor:290,file_input:291,flow_stmt:292,for_stmt:293,fpdef:294,fplist:295,funcdef:296,global_stmt:297,if_stmt:298,import_as_name:299,import_as_names:300,import_from:301,import_name:302,import_stmt:303,lambdef:304,list_for:305,list_if:306,list_iter:307,listmaker:308,not_test:309,old_lambdef:310,old_test:311,or_test:312,parameters:313,pass_stmt:314,power:315,print_stmt:316,raise_stmt:317,return_stmt:318,shift_expr:319,simple_stmt:320,single_input:256,sliceop:321,small_stmt:322,stmt:323,subscript:324,
subscriptlist:325,suite:326,term:327,test:328,testlist:329,testlist1:330,testlist_comp:331,testlist_safe:332,trailer:333,try_stmt:334,varargslist:335,while_stmt:336,with_item:337,with_stmt:338,xor_expr:339,yield_expr:340,yield_stmt:341},number2symbol:{256:"single_input",257:"and_expr",258:"and_test",259:"arglist",260:"argument",261:"arith_expr",262:"assert_stmt",263:"atom",264:"augassign",265:"break_stmt",266:"classdef",267:"comp_for",268:"comp_if",269:"comp_iter",270:"comp_op",271:"comparison",272:"compound_stmt",
273:"continue_stmt",274:"debugger_stmt",275:"decorated",276:"decorator",277:"decorators",278:"del_stmt",279:"dictorsetmaker",280:"dotted_as_name",281:"dotted_as_names",282:"dotted_name",283:"encoding_decl",284:"eval_input",285:"except_clause",286:"exec_stmt",287:"expr",288:"expr_stmt",289:"exprlist",290:"factor",291:"file_input",292:"flow_stmt",293:"for_stmt",294:"fpdef",295:"fplist",296:"funcdef",297:"global_stmt",298:"if_stmt",299:"import_as_name",300:"import_as_names",301:"import_from",302:"import_name",
303:"import_stmt",304:"lambdef",305:"list_for",306:"list_if",307:"list_iter",308:"listmaker",309:"not_test",310:"old_lambdef",311:"old_test",312:"or_test",313:"parameters",314:"pass_stmt",315:"power",316:"print_stmt",317:"raise_stmt",318:"return_stmt",319:"shift_expr",320:"simple_stmt",321:"sliceop",322:"small_stmt",323:"stmt",324:"subscript",325:"subscriptlist",326:"suite",327:"term",328:"test",329:"testlist",330:"testlist1",331:"testlist_comp",332:"testlist_safe",333:"trailer",334:"try_stmt",335:"varargslist",
336:"while_stmt",337:"with_item",338:"with_stmt",339:"xor_expr",340:"yield_expr",341:"yield_stmt"},dfas:{256:[[[[1,1],[2,1],[3,2]],[[0,1]],[[2,1]]],{2:1,4:1,5:1,6:1,7:1,8:1,9:1,10:1,11:1,12:1,13:1,14:1,15:1,16:1,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:1,25:1,26:1,27:1,28:1,29:1,30:1,31:1,32:1,33:1,34:1,35:1,36:1,37:1}],257:[[[[38,1]],[[39,0],[0,1]]],{6:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],258:[[[[40,1]],[[41,0],[0,1]]],{6:1,7:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],259:[[[[42,1],[43,
2],[44,3]],[[45,4]],[[46,5],[0,2]],[[45,6]],[[46,7],[0,4]],[[42,1],[43,2],[44,3],[0,5]],[[0,6]],[[43,4],[44,3]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1,42:1,44:1}],260:[[[[45,1]],[[47,2],[48,3],[0,1]],[[45,3]],[[0,3]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],261:[[[[49,1]],[[26,0],[37,0],[0,1]]],{6:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],262:[[[[21,1]],[[45,2]],[[46,3],[0,2]],[[45,4]],[[0,4]]],{21:1}],263:[[[[19,1],[8,2],[9,5],[30,4],[14,3],[15,6],[22,2]],
[[19,1],[0,1]],[[0,2]],[[50,7],[51,2]],[[52,2],[53,8],[54,8]],[[55,2],[56,9]],[[57,10]],[[51,2]],[[52,2]],[[55,2]],[[15,2]]],{8:1,9:1,14:1,15:1,19:1,22:1,30:1}],264:[[[[58,1],[59,1],[60,1],[61,1],[62,1],[63,1],[64,1],[65,1],[66,1],[67,1],[68,1],[69,1]],[[0,1]]],{58:1,59:1,60:1,61:1,62:1,63:1,64:1,65:1,66:1,67:1,68:1,69:1}],265:[[[[33,1]],[[0,1]]],{33:1}],266:[[[[10,1]],[[22,2]],[[70,3],[30,4]],[[71,5]],[[52,6],[72,7]],[[0,5]],[[70,3]],[[52,6]]],{10:1}],267:[[[[29,1]],[[73,2]],[[74,3]],[[75,4]],[[76,
5],[0,4]],[[0,5]]],{29:1}],268:[[[[32,1]],[[77,2]],[[76,3],[0,2]],[[0,3]]],{32:1}],269:[[[[78,1],[48,1]],[[0,1]]],{29:1,32:1}],270:[[[[79,1],[80,1],[7,2],[81,1],[79,1],[74,1],[82,1],[83,3],[84,1],[85,1]],[[0,1]],[[74,1]],[[7,1],[0,3]]],{7:1,74:1,79:1,80:1,81:1,82:1,83:1,84:1,85:1}],271:[[[[86,1]],[[87,0],[0,1]]],{6:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],272:[[[[88,1],[89,1],[90,1],[91,1],[92,1],[93,1],[94,1],[95,1]],[[0,1]]],{4:1,10:1,16:1,18:1,29:1,32:1,35:1,36:1}],273:[[[[34,1]],[[0,1]]],
{34:1}],274:[[[[13,1]],[[0,1]]],{13:1}],275:[[[[96,1]],[[94,2],[91,2]],[[0,2]]],{35:1}],276:[[[[35,1]],[[97,2]],[[2,4],[30,3]],[[52,5],[98,6]],[[0,4]],[[2,4]],[[52,5]]],{35:1}],277:[[[[99,1]],[[99,1],[0,1]]],{35:1}],278:[[[[23,1]],[[73,2]],[[0,2]]],{23:1}],279:[[[[45,1]],[[70,2],[48,3],[46,4],[0,1]],[[45,5]],[[0,3]],[[45,6],[0,4]],[[48,3],[46,7],[0,5]],[[46,4],[0,6]],[[45,8],[0,7]],[[70,9]],[[45,10]],[[46,7],[0,10]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],280:[[[[97,1]],[[100,
2],[0,1]],[[22,3]],[[0,3]]],{22:1}],281:[[[[101,1]],[[46,0],[0,1]]],{22:1}],282:[[[[22,1]],[[102,0],[0,1]]],{22:1}],283:[[[[22,1]],[[0,1]]],{22:1}],284:[[[[72,1]],[[2,1],[103,2]],[[0,2]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],285:[[[[104,1]],[[45,2],[0,1]],[[100,3],[46,3],[0,2]],[[45,4]],[[0,4]]],{104:1}],286:[[[[17,1]],[[86,2]],[[74,3],[0,2]],[[45,4]],[[46,5],[0,4]],[[45,6]],[[0,6]]],{17:1}],287:[[[[105,1]],[[106,0],[0,1]]],{6:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],288:[[[[72,
1]],[[107,2],[47,3],[0,1]],[[72,4],[53,4]],[[72,5],[53,5]],[[0,4]],[[47,3],[0,5]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],289:[[[[86,1]],[[46,2],[0,1]],[[86,1],[0,2]]],{6:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],290:[[[[37,2],[26,2],[6,2],[108,1]],[[0,1]],[[109,1]]],{6:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],291:[[[[2,0],[103,1],[110,0]],[[0,1]]],{2:1,4:1,5:1,6:1,7:1,8:1,9:1,10:1,11:1,12:1,13:1,14:1,15:1,16:1,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:1,25:1,26:1,27:1,
28:1,29:1,30:1,31:1,32:1,33:1,34:1,35:1,36:1,37:1,103:1}],292:[[[[111,1],[112,1],[113,1],[114,1],[115,1]],[[0,1]]],{5:1,20:1,27:1,33:1,34:1}],293:[[[[29,1]],[[73,2]],[[74,3]],[[72,4]],[[70,5]],[[71,6]],[[116,7],[0,6]],[[70,8]],[[71,9]],[[0,9]]],{29:1}],294:[[[[30,1],[22,2]],[[117,3]],[[0,2]],[[52,2]]],{22:1,30:1}],295:[[[[118,1]],[[46,2],[0,1]],[[118,1],[0,2]]],{22:1,30:1}],296:[[[[4,1]],[[22,2]],[[119,3]],[[70,4]],[[71,5]],[[0,5]]],{4:1}],297:[[[[28,1]],[[22,2]],[[46,1],[0,2]]],{28:1}],298:[[[[32,
1]],[[45,2]],[[70,3]],[[71,4]],[[116,5],[120,1],[0,4]],[[70,6]],[[71,7]],[[0,7]]],{32:1}],299:[[[[22,1]],[[100,2],[0,1]],[[22,3]],[[0,3]]],{22:1}],300:[[[[121,1]],[[46,2],[0,1]],[[121,1],[0,2]]],{22:1}],301:[[[[31,1]],[[97,2],[102,3]],[[25,4]],[[97,2],[25,4],[102,3]],[[122,5],[42,5],[30,6]],[[0,5]],[[122,7]],[[52,5]]],{31:1}],302:[[[[25,1]],[[123,2]],[[0,2]]],{25:1}],303:[[[[124,1],[125,1]],[[0,1]]],{25:1,31:1}],304:[[[[11,1]],[[70,2],[126,3]],[[45,4]],[[70,2]],[[0,4]]],{11:1}],305:[[[[29,1]],[[73,
2]],[[74,3]],[[127,4]],[[128,5],[0,4]],[[0,5]]],{29:1}],306:[[[[32,1]],[[77,2]],[[128,3],[0,2]],[[0,3]]],{32:1}],307:[[[[129,1],[130,1]],[[0,1]]],{29:1,32:1}],308:[[[[45,1]],[[129,2],[46,3],[0,1]],[[0,2]],[[45,4],[0,3]],[[46,3],[0,4]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],309:[[[[7,1],[131,2]],[[40,2]],[[0,2]]],{6:1,7:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],310:[[[[11,1]],[[70,2],[126,3]],[[77,4]],[[70,2]],[[0,4]]],{11:1}],311:[[[[132,1],[75,1]],[[0,1]]],{6:1,7:1,8:1,
9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],312:[[[[133,1]],[[134,0],[0,1]]],{6:1,7:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],313:[[[[30,1]],[[52,2],[126,3]],[[0,2]],[[52,2]]],{30:1}],314:[[[[24,1]],[[0,1]]],{24:1}],315:[[[[135,1]],[[44,2],[136,1],[0,1]],[[109,3]],[[0,3]]],{8:1,9:1,14:1,15:1,19:1,22:1,30:1}],316:[[[[12,1]],[[45,2],[137,3],[0,1]],[[46,4],[0,2]],[[45,5]],[[45,2],[0,4]],[[46,6],[0,5]],[[45,7]],[[46,8],[0,7]],[[45,7],[0,8]]],{12:1}],317:[[[[5,1]],[[45,2],[0,1]],[[46,3],[0,2]],
[[45,4]],[[46,5],[0,4]],[[45,6]],[[0,6]]],{5:1}],318:[[[[20,1]],[[72,2],[0,1]],[[0,2]]],{20:1}],319:[[[[138,1]],[[139,0],[137,0],[0,1]]],{6:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],320:[[[[140,1]],[[2,2],[141,3]],[[0,2]],[[140,1],[2,2]]],{5:1,6:1,7:1,8:1,9:1,11:1,12:1,13:1,14:1,15:1,17:1,19:1,20:1,21:1,22:1,23:1,24:1,25:1,26:1,27:1,28:1,30:1,31:1,33:1,34:1,37:1}],321:[[[[70,1]],[[45,2],[0,1]],[[0,2]]],{70:1}],322:[[[[142,1],[143,1],[144,1],[145,1],[146,1],[147,1],[148,1],[149,1],[150,1],[151,
1]],[[0,1]]],{5:1,6:1,7:1,8:1,9:1,11:1,12:1,13:1,14:1,15:1,17:1,19:1,20:1,21:1,22:1,23:1,24:1,25:1,26:1,27:1,28:1,30:1,31:1,33:1,34:1,37:1}],323:[[[[1,1],[3,1]],[[0,1]]],{4:1,5:1,6:1,7:1,8:1,9:1,10:1,11:1,12:1,13:1,14:1,15:1,16:1,17:1,18:1,19:1,20:1,21:1,22:1,23:1,24:1,25:1,26:1,27:1,28:1,29:1,30:1,31:1,32:1,33:1,34:1,35:1,36:1,37:1}],324:[[[[45,1],[70,2],[102,3]],[[70,2],[0,1]],[[45,4],[152,5],[0,2]],[[102,6]],[[152,5],[0,4]],[[0,5]],[[102,5]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,
37:1,70:1,102:1}],325:[[[[153,1]],[[46,2],[0,1]],[[153,1],[0,2]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1,70:1,102:1}],326:[[[[1,1],[2,2]],[[0,1]],[[154,3]],[[110,4]],[[155,1],[110,4]]],{2:1,5:1,6:1,7:1,8:1,9:1,11:1,12:1,13:1,14:1,15:1,17:1,19:1,20:1,21:1,22:1,23:1,24:1,25:1,26:1,27:1,28:1,30:1,31:1,33:1,34:1,37:1}],327:[[[[109,1]],[[156,0],[42,0],[157,0],[158,0],[0,1]]],{6:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],328:[[[[75,1],[159,2]],[[32,3],[0,1]],[[0,2]],[[75,4]],[[116,
5]],[[45,2]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],329:[[[[45,1]],[[46,2],[0,1]],[[45,1],[0,2]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],330:[[[[45,1]],[[46,0],[0,1]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],331:[[[[45,1]],[[48,2],[46,3],[0,1]],[[0,2]],[[45,4],[0,3]],[[46,3],[0,4]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],332:[[[[77,1]],[[46,2],[0,1]],[[77,3]],[[46,4],[0,3]],[[77,3],[0,4]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,
19:1,22:1,26:1,30:1,37:1}],333:[[[[30,1],[102,2],[14,3]],[[52,4],[98,5]],[[22,4]],[[160,6]],[[0,4]],[[52,4]],[[51,4]]],{14:1,30:1,102:1}],334:[[[[16,1]],[[70,2]],[[71,3]],[[161,4],[162,5]],[[70,6]],[[70,7]],[[71,8]],[[71,9]],[[161,4],[116,10],[162,5],[0,8]],[[0,9]],[[70,11]],[[71,12]],[[162,5],[0,12]]],{16:1}],335:[[[[42,1],[118,2],[44,3]],[[22,4]],[[47,5],[46,6],[0,2]],[[22,7]],[[46,8],[0,4]],[[45,9]],[[42,1],[118,2],[44,3],[0,6]],[[0,7]],[[44,3]],[[46,6],[0,9]]],{22:1,30:1,42:1,44:1}],336:[[[[18,
1]],[[45,2]],[[70,3]],[[71,4]],[[116,5],[0,4]],[[70,6]],[[71,7]],[[0,7]]],{18:1}],337:[[[[45,1]],[[100,2],[0,1]],[[86,3]],[[0,3]]],{6:1,7:1,8:1,9:1,11:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],338:[[[[36,1]],[[163,2]],[[70,3],[46,1]],[[71,4]],[[0,4]]],{36:1}],339:[[[[164,1]],[[165,0],[0,1]]],{6:1,8:1,9:1,14:1,15:1,19:1,22:1,26:1,30:1,37:1}],340:[[[[27,1]],[[72,2],[0,1]],[[0,2]]],{27:1}],341:[[[[53,1]],[[0,1]]],{27:1}]},states:[[[[1,1],[2,1],[3,2]],[[0,1]],[[2,1]]],[[[38,1]],[[39,0],[0,1]]],[[[40,1]],
[[41,0],[0,1]]],[[[42,1],[43,2],[44,3]],[[45,4]],[[46,5],[0,2]],[[45,6]],[[46,7],[0,4]],[[42,1],[43,2],[44,3],[0,5]],[[0,6]],[[43,4],[44,3]]],[[[45,1]],[[47,2],[48,3],[0,1]],[[45,3]],[[0,3]]],[[[49,1]],[[26,0],[37,0],[0,1]]],[[[21,1]],[[45,2]],[[46,3],[0,2]],[[45,4]],[[0,4]]],[[[19,1],[8,2],[9,5],[30,4],[14,3],[15,6],[22,2]],[[19,1],[0,1]],[[0,2]],[[50,7],[51,2]],[[52,2],[53,8],[54,8]],[[55,2],[56,9]],[[57,10]],[[51,2]],[[52,2]],[[55,2]],[[15,2]]],[[[58,1],[59,1],[60,1],[61,1],[62,1],[63,1],[64,1],
[65,1],[66,1],[67,1],[68,1],[69,1]],[[0,1]]],[[[33,1]],[[0,1]]],[[[10,1]],[[22,2]],[[70,3],[30,4]],[[71,5]],[[52,6],[72,7]],[[0,5]],[[70,3]],[[52,6]]],[[[29,1]],[[73,2]],[[74,3]],[[75,4]],[[76,5],[0,4]],[[0,5]]],[[[32,1]],[[77,2]],[[76,3],[0,2]],[[0,3]]],[[[78,1],[48,1]],[[0,1]]],[[[79,1],[80,1],[7,2],[81,1],[79,1],[74,1],[82,1],[83,3],[84,1],[85,1]],[[0,1]],[[74,1]],[[7,1],[0,3]]],[[[86,1]],[[87,0],[0,1]]],[[[88,1],[89,1],[90,1],[91,1],[92,1],[93,1],[94,1],[95,1]],[[0,1]]],[[[34,1]],[[0,1]]],[[[13,
1]],[[0,1]]],[[[96,1]],[[94,2],[91,2]],[[0,2]]],[[[35,1]],[[97,2]],[[2,4],[30,3]],[[52,5],[98,6]],[[0,4]],[[2,4]],[[52,5]]],[[[99,1]],[[99,1],[0,1]]],[[[23,1]],[[73,2]],[[0,2]]],[[[45,1]],[[70,2],[48,3],[46,4],[0,1]],[[45,5]],[[0,3]],[[45,6],[0,4]],[[48,3],[46,7],[0,5]],[[46,4],[0,6]],[[45,8],[0,7]],[[70,9]],[[45,10]],[[46,7],[0,10]]],[[[97,1]],[[100,2],[0,1]],[[22,3]],[[0,3]]],[[[101,1]],[[46,0],[0,1]]],[[[22,1]],[[102,0],[0,1]]],[[[22,1]],[[0,1]]],[[[72,1]],[[2,1],[103,2]],[[0,2]]],[[[104,1]],[[45,
2],[0,1]],[[100,3],[46,3],[0,2]],[[45,4]],[[0,4]]],[[[17,1]],[[86,2]],[[74,3],[0,2]],[[45,4]],[[46,5],[0,4]],[[45,6]],[[0,6]]],[[[105,1]],[[106,0],[0,1]]],[[[72,1]],[[107,2],[47,3],[0,1]],[[72,4],[53,4]],[[72,5],[53,5]],[[0,4]],[[47,3],[0,5]]],[[[86,1]],[[46,2],[0,1]],[[86,1],[0,2]]],[[[37,2],[26,2],[6,2],[108,1]],[[0,1]],[[109,1]]],[[[2,0],[103,1],[110,0]],[[0,1]]],[[[111,1],[112,1],[113,1],[114,1],[115,1]],[[0,1]]],[[[29,1]],[[73,2]],[[74,3]],[[72,4]],[[70,5]],[[71,6]],[[116,7],[0,6]],[[70,8]],
[[71,9]],[[0,9]]],[[[30,1],[22,2]],[[117,3]],[[0,2]],[[52,2]]],[[[118,1]],[[46,2],[0,1]],[[118,1],[0,2]]],[[[4,1]],[[22,2]],[[119,3]],[[70,4]],[[71,5]],[[0,5]]],[[[28,1]],[[22,2]],[[46,1],[0,2]]],[[[32,1]],[[45,2]],[[70,3]],[[71,4]],[[116,5],[120,1],[0,4]],[[70,6]],[[71,7]],[[0,7]]],[[[22,1]],[[100,2],[0,1]],[[22,3]],[[0,3]]],[[[121,1]],[[46,2],[0,1]],[[121,1],[0,2]]],[[[31,1]],[[97,2],[102,3]],[[25,4]],[[97,2],[25,4],[102,3]],[[122,5],[42,5],[30,6]],[[0,5]],[[122,7]],[[52,5]]],[[[25,1]],[[123,2]],
[[0,2]]],[[[124,1],[125,1]],[[0,1]]],[[[11,1]],[[70,2],[126,3]],[[45,4]],[[70,2]],[[0,4]]],[[[29,1]],[[73,2]],[[74,3]],[[127,4]],[[128,5],[0,4]],[[0,5]]],[[[32,1]],[[77,2]],[[128,3],[0,2]],[[0,3]]],[[[129,1],[130,1]],[[0,1]]],[[[45,1]],[[129,2],[46,3],[0,1]],[[0,2]],[[45,4],[0,3]],[[46,3],[0,4]]],[[[7,1],[131,2]],[[40,2]],[[0,2]]],[[[11,1]],[[70,2],[126,3]],[[77,4]],[[70,2]],[[0,4]]],[[[132,1],[75,1]],[[0,1]]],[[[133,1]],[[134,0],[0,1]]],[[[30,1]],[[52,2],[126,3]],[[0,2]],[[52,2]]],[[[24,1]],[[0,
1]]],[[[135,1]],[[44,2],[136,1],[0,1]],[[109,3]],[[0,3]]],[[[12,1]],[[45,2],[137,3],[0,1]],[[46,4],[0,2]],[[45,5]],[[45,2],[0,4]],[[46,6],[0,5]],[[45,7]],[[46,8],[0,7]],[[45,7],[0,8]]],[[[5,1]],[[45,2],[0,1]],[[46,3],[0,2]],[[45,4]],[[46,5],[0,4]],[[45,6]],[[0,6]]],[[[20,1]],[[72,2],[0,1]],[[0,2]]],[[[138,1]],[[139,0],[137,0],[0,1]]],[[[140,1]],[[2,2],[141,3]],[[0,2]],[[140,1],[2,2]]],[[[70,1]],[[45,2],[0,1]],[[0,2]]],[[[142,1],[143,1],[144,1],[145,1],[146,1],[147,1],[148,1],[149,1],[150,1],[151,
1]],[[0,1]]],[[[1,1],[3,1]],[[0,1]]],[[[45,1],[70,2],[102,3]],[[70,2],[0,1]],[[45,4],[152,5],[0,2]],[[102,6]],[[152,5],[0,4]],[[0,5]],[[102,5]]],[[[153,1]],[[46,2],[0,1]],[[153,1],[0,2]]],[[[1,1],[2,2]],[[0,1]],[[154,3]],[[110,4]],[[155,1],[110,4]]],[[[109,1]],[[156,0],[42,0],[157,0],[158,0],[0,1]]],[[[75,1],[159,2]],[[32,3],[0,1]],[[0,2]],[[75,4]],[[116,5]],[[45,2]]],[[[45,1]],[[46,2],[0,1]],[[45,1],[0,2]]],[[[45,1]],[[46,0],[0,1]]],[[[45,1]],[[48,2],[46,3],[0,1]],[[0,2]],[[45,4],[0,3]],[[46,3],
[0,4]]],[[[77,1]],[[46,2],[0,1]],[[77,3]],[[46,4],[0,3]],[[77,3],[0,4]]],[[[30,1],[102,2],[14,3]],[[52,4],[98,5]],[[22,4]],[[160,6]],[[0,4]],[[52,4]],[[51,4]]],[[[16,1]],[[70,2]],[[71,3]],[[161,4],[162,5]],[[70,6]],[[70,7]],[[71,8]],[[71,9]],[[161,4],[116,10],[162,5],[0,8]],[[0,9]],[[70,11]],[[71,12]],[[162,5],[0,12]]],[[[42,1],[118,2],[44,3]],[[22,4]],[[47,5],[46,6],[0,2]],[[22,7]],[[46,8],[0,4]],[[45,9]],[[42,1],[118,2],[44,3],[0,6]],[[0,7]],[[44,3]],[[46,6],[0,9]]],[[[18,1]],[[45,2]],[[70,3]],
[[71,4]],[[116,5],[0,4]],[[70,6]],[[71,7]],[[0,7]]],[[[45,1]],[[100,2],[0,1]],[[86,3]],[[0,3]]],[[[36,1]],[[163,2]],[[70,3],[46,1]],[[71,4]],[[0,4]]],[[[164,1]],[[165,0],[0,1]]],[[[27,1]],[[72,2],[0,1]],[[0,2]]],[[[53,1]],[[0,1]]]],labels:[[0,"EMPTY"],[320,null],[4,null],[272,null],[1,"def"],[1,"raise"],[32,null],[1,"not"],[2,null],[26,null],[1,"class"],[1,"lambda"],[1,"print"],[1,"debugger"],[9,null],[25,null],[1,"try"],[1,"exec"],[1,"while"],[3,null],[1,"return"],[1,"assert"],[1,null],[1,"del"],
[1,"pass"],[1,"import"],[15,null],[1,"yield"],[1,"global"],[1,"for"],[7,null],[1,"from"],[1,"if"],[1,"break"],[1,"continue"],[50,null],[1,"with"],[14,null],[319,null],[19,null],[309,null],[1,"and"],[16,null],[260,null],[36,null],[328,null],[12,null],[22,null],[267,null],[327,null],[308,null],[10,null],[8,null],[340,null],[331,null],[27,null],[279,null],[330,null],[46,null],[39,null],[41,null],[47,null],[42,null],[43,null],[37,null],[44,null],[49,null],[45,null],[38,null],[40,null],[11,null],[326,
null],[329,null],[289,null],[1,"in"],[312,null],[269,null],[311,null],[268,null],[29,null],[21,null],[28,null],[30,null],[1,"is"],[31,null],[20,null],[287,null],[270,null],[334,null],[298,null],[293,null],[266,null],[338,null],[336,null],[296,null],[275,null],[277,null],[282,null],[259,null],[276,null],[1,"as"],[280,null],[23,null],[0,null],[1,"except"],[339,null],[18,null],[264,null],[315,null],[290,null],[323,null],[265,null],[273,null],[317,null],[318,null],[341,null],[1,"else"],[295,null],[294,
null],[313,null],[1,"elif"],[299,null],[300,null],[281,null],[302,null],[301,null],[335,null],[332,null],[307,null],[305,null],[306,null],[271,null],[310,null],[258,null],[1,"or"],[263,null],[333,null],[35,null],[261,null],[34,null],[322,null],[13,null],[292,null],[278,null],[288,null],[314,null],[316,null],[262,null],[286,null],[297,null],[303,null],[274,null],[321,null],[324,null],[5,null],[6,null],[48,null],[17,null],[24,null],[304,null],[325,null],[285,null],[1,"finally"],[337,null],[257,null],
[33,null]],keywords:{and:41,as:100,assert:21,"break":33,"class":10,"continue":34,"debugger":13,def:4,del:23,elif:120,"else":116,except:104,exec:17,"finally":162,"for":29,from:31,global:28,"if":32,"import":25,"in":74,is:83,lambda:11,not:7,or:134,pass:24,print:12,raise:5,"return":20,"try":16,"while":18,"with":36,yield:27},tokens:{0:103,1:22,2:8,3:19,4:2,5:154,6:155,7:30,8:52,9:14,10:51,11:70,12:46,13:141,14:37,15:26,16:42,17:157,18:106,19:39,20:85,21:80,22:47,23:102,24:158,25:15,26:9,27:55,28:81,29:79,
30:82,31:84,32:6,33:165,34:139,35:137,36:44,37:64,38:68,39:59,40:69,41:60,42:62,43:63,44:65,45:67,46:58,47:61,48:156,49:66,50:35},start:256};function Parser(a,b){this.filename=a;this.grammar=b;this.p_flags=0;return this}Parser.FUTURE_PRINT_FUNCTION="print_function";Parser.FUTURE_UNICODE_LITERALS="unicode_literals";Parser.FUTURE_DIVISION="division";Parser.FUTURE_ABSOLUTE_IMPORT="absolute_import";Parser.FUTURE_WITH_STATEMENT="with_statement";Parser.FUTURE_NESTED_SCOPES="nested_scopes";Parser.FUTURE_GENERATORS="generators";Parser.CO_FUTURE_PRINT_FUNCTION=65536;Parser.CO_FUTURE_UNICODE_LITERALS=131072;Parser.CO_FUTURE_DIVISON=8192;
Parser.CO_FUTURE_ABSOLUTE_IMPORT=16384;Parser.CO_FUTURE_WITH_STATEMENT=32768;Parser.prototype.setup=function(a){a=a||this.grammar.start;this.stack=[{dfa:this.grammar.dfas[a],state:0,node:{type:a,value:null,context:null,children:[]}}];this.used_names={}};function findInDfa(a,b){for(var c=a.length;c--;)if(a[c][0]===b[0]&&a[c][1]===b[1])return!0;return!1}
Parser.prototype.addtoken=function(a,b,c){var d,e,f,g,h,k,l,m=this.classify(a,b,c);a:for(;;){l=this.stack[this.stack.length-1];d=l.dfa[0];k=d[l.state];for(h=0;h<k.length;++h){e=k[h][0];g=k[h][1];f=this.grammar.labels[e][0];if(m===e){goog.asserts.assert(256>f);this.shift(a,b,g,c);for(c=g;1===d[c].length&&0===d[c][0][0]&&d[c][0][1]===c;){this.pop();if(0===this.stack.length)return!0;l=this.stack[this.stack.length-1];c=l.state;d=l.dfa[0]}return!1}if(256<=f&&(e=this.grammar.dfas[f],e=e[1],e.hasOwnProperty(m))){this.push(f,
this.grammar.dfas[f],g,c);continue a}}if(findInDfa(k,[0,l.state])){if(this.pop(),0===this.stack.length)throw new Sk.builtin.ParseError("too much input",this.filename);}else throw d=c[0][0],new Sk.builtin.ParseError("bad input",this.filename,d,c);}};
Parser.prototype.classify=function(a,b,c){var d;if(a===Sk.Tokenizer.Tokens.T_NAME&&(this.used_names[b]=!0,d=this.grammar.keywords.hasOwnProperty(b)&&this.grammar.keywords[b],"print"===b&&(this.p_flags&Parser.CO_FUTURE_PRINT_FUNCTION||!0===Sk.python3)&&(d=!1),d))return d;d=this.grammar.tokens.hasOwnProperty(a)&&this.grammar.tokens[a];if(!d)throw new Sk.builtin.ParseError("bad token",this.filename,c[0][0],c);return d};
Parser.prototype.shift=function(a,b,c,d){var e=this.stack[this.stack.length-1].dfa,f=this.stack[this.stack.length-1].node;f.children.push({type:a,value:b,lineno:d[0][0],col_offset:d[0][1],children:null});this.stack[this.stack.length-1]={dfa:e,state:c,node:f}};
Parser.prototype.push=function(a,b,c,d){a={type:a,value:null,lineno:d[0][0],col_offset:d[0][1],children:[]};this.stack[this.stack.length-1]={dfa:this.stack[this.stack.length-1].dfa,state:c,node:this.stack[this.stack.length-1].node};this.stack.push({dfa:b,state:0,node:a})};Parser.prototype.pop=function(){var a,b=this.stack.pop().node;b&&(0!==this.stack.length?(a=this.stack[this.stack.length-1].node,a.children.push(b)):(this.rootnode=b,this.rootnode.used_names=this.used_names))};
function makeParser(a,b){var c,d,e,f,g;void 0===b&&(b="file_input");g=new Parser(a,Sk.ParseTables);"file_input"===b?g.setup(Sk.ParseTables.sym.file_input):goog.asserts.fail("todo;");f=Sk.Tokenizer.Tokens.T_COMMENT;e=Sk.Tokenizer.Tokens.T_NL;d=Sk.Tokenizer.Tokens.T_OP;c=new Sk.Tokenizer(a,"single_input"===b,function(a,b,c,h,n){if(a!==f&&a!==e&&(a===d&&(a=Sk.OpMap[b]),g.addtoken(a,b,[c,h,n])))return!0});var h=function(a){if(a=c.generateTokens(a)){if("done"!==a)throw new Sk.builtin.ParseError("incomplete input",
this.filename);return g.rootnode}return!1};h.p_flags=g.p_flags;return h}Sk.parse=function(a,b){var c,d,e,f=makeParser(a);"\n"!==b.substr(b.length-1,1)&&(b+="\n");e=b.split("\n");for(c=0;c<e.length;++c)d=f(e[c]+(c===e.length-1?"":"\n"));return{cst:d,flags:f.p_flags}};
Sk.parseTreeDump=function(a,b){var c,d;b=b||"";d=""+b;if(256<=a.type)for(d+=Sk.ParseTables.number2symbol[a.type]+"\n",c=0;c<a.children.length;++c)d+=Sk.parseTreeDump(a.children[c],b+" ");else d+=Sk.Tokenizer.tokenNames[a.type]+": "+(new Sk.builtin.str(a.value)).$r().v+"\n";return d};goog.exportSymbol("Sk.parse",Sk.parse);goog.exportSymbol("Sk.parseTreeDump",Sk.parseTreeDump);function Load(){}function Store(){}function Del(){}function AugLoad(){}function AugStore(){}function Param(){}function And(){}function Or(){}function Add(){}function Sub(){}function Mult(){}function Div(){}function Mod(){}function Pow(){}function LShift(){}function RShift(){}function BitOr(){}function BitXor(){}function BitAnd(){}function FloorDiv(){}function Invert(){}function Not(){}function UAdd(){}function USub(){}function Eq(){}function NotEq(){}function Lt(){}function LtE(){}
function Gt(){}function GtE(){}function Is(){}function IsNot(){}function In_(){}function NotIn(){}function Module(a){this.body=a;return this}function Interactive(a){this.body=a;return this}function Expression(a){goog.asserts.assert(null!==a&&void 0!==a);this.body=a;return this}function Suite(a){this.body=a;return this}
function FunctionDef(a,b,c,d,e,f){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);this.name=a;this.args=b;this.body=c;this.decorator_list=d;this.lineno=e;this.col_offset=f;return this}function ClassDef(a,b,c,d,e,f){goog.asserts.assert(null!==a&&void 0!==a);this.name=a;this.bases=b;this.body=c;this.decorator_list=d;this.lineno=e;this.col_offset=f;return this}function Return_(a,b,c){this.value=a;this.lineno=b;this.col_offset=c;return this}
function Delete_(a,b,c){this.targets=a;this.lineno=b;this.col_offset=c;return this}function Assign(a,b,c,d){goog.asserts.assert(null!==b&&void 0!==b);this.targets=a;this.value=b;this.lineno=c;this.col_offset=d;return this}function AugAssign(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);goog.asserts.assert(null!==c&&void 0!==c);this.target=a;this.op=b;this.value=c;this.lineno=d;this.col_offset=e;return this}
function Print(a,b,c,d,e){this.dest=a;this.values=b;this.nl=c;this.lineno=d;this.col_offset=e;return this}function For_(a,b,c,d,e,f){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);this.target=a;this.iter=b;this.body=c;this.orelse=d;this.lineno=e;this.col_offset=f;return this}function While_(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);this.test=a;this.body=b;this.orelse=c;this.lineno=d;this.col_offset=e;return this}
function If_(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);this.test=a;this.body=b;this.orelse=c;this.lineno=d;this.col_offset=e;return this}function With_(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);this.context_expr=a;this.optional_vars=b;this.body=c;this.lineno=d;this.col_offset=e;return this}function Raise(a,b,c,d,e){this.type=a;this.inst=b;this.tback=c;this.lineno=d;this.col_offset=e;return this}
function TryExcept(a,b,c,d,e){this.body=a;this.handlers=b;this.orelse=c;this.lineno=d;this.col_offset=e;return this}function TryFinally(a,b,c,d){this.body=a;this.finalbody=b;this.lineno=c;this.col_offset=d;return this}function Assert(a,b,c,d){goog.asserts.assert(null!==a&&void 0!==a);this.test=a;this.msg=b;this.lineno=c;this.col_offset=d;return this}function Import_(a,b,c){this.names=a;this.lineno=b;this.col_offset=c;return this}
function ImportFrom(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);this.module=a;this.names=b;this.level=c;this.lineno=d;this.col_offset=e;return this}function Exec(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);this.body=a;this.globals=b;this.locals=c;this.lineno=d;this.col_offset=e;return this}function Global(a,b,c){this.names=a;this.lineno=b;this.col_offset=c;return this}
function Expr(a,b,c){goog.asserts.assert(null!==a&&void 0!==a);this.value=a;this.lineno=b;this.col_offset=c;return this}function Pass(a,b){this.lineno=a;this.col_offset=b;return this}function Break_(a,b){this.lineno=a;this.col_offset=b;return this}function Continue_(a,b){this.lineno=a;this.col_offset=b;return this}function Debugger_(a,b){this.lineno=a;this.col_offset=b;return this}
function BoolOp(a,b,c,d){goog.asserts.assert(null!==a&&void 0!==a);this.op=a;this.values=b;this.lineno=c;this.col_offset=d;return this}function BinOp(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);goog.asserts.assert(null!==c&&void 0!==c);this.left=a;this.op=b;this.right=c;this.lineno=d;this.col_offset=e;return this}
function UnaryOp(a,b,c,d){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);this.op=a;this.operand=b;this.lineno=c;this.col_offset=d;return this}function Lambda(a,b,c,d){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);this.args=a;this.body=b;this.lineno=c;this.col_offset=d;return this}
function IfExp(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);goog.asserts.assert(null!==c&&void 0!==c);this.test=a;this.body=b;this.orelse=c;this.lineno=d;this.col_offset=e;return this}function Dict(a,b,c,d){this.keys=a;this.values=b;this.lineno=c;this.col_offset=d;return this}function Set(a,b,c){this.elts=a;this.lineno=b;this.col_offset=c;return this}
function ListComp(a,b,c,d){goog.asserts.assert(null!==a&&void 0!==a);this.elt=a;this.generators=b;this.lineno=c;this.col_offset=d;return this}function SetComp(a,b,c,d){goog.asserts.assert(null!==a&&void 0!==a);this.elt=a;this.generators=b;this.lineno=c;this.col_offset=d;return this}function DictComp(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);this.key=a;this.value=b;this.generators=c;this.lineno=d;this.col_offset=e;return this}
function GeneratorExp(a,b,c,d){goog.asserts.assert(null!==a&&void 0!==a);this.elt=a;this.generators=b;this.lineno=c;this.col_offset=d;return this}function Yield(a,b,c){this.value=a;this.lineno=b;this.col_offset=c;return this}function Compare(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);this.left=a;this.ops=b;this.comparators=c;this.lineno=d;this.col_offset=e;return this}
function Call(a,b,c,d,e,f,g){goog.asserts.assert(null!==a&&void 0!==a);this.func=a;this.args=b;this.keywords=c;this.starargs=d;this.kwargs=e;this.lineno=f;this.col_offset=g;return this}function Repr(a,b,c){goog.asserts.assert(null!==a&&void 0!==a);this.value=a;this.lineno=b;this.col_offset=c;return this}function Num(a,b,c){goog.asserts.assert(null!==a&&void 0!==a);this.n=a;this.lineno=b;this.col_offset=c;return this}
function Str(a,b,c){goog.asserts.assert(null!==a&&void 0!==a);this.s=a;this.lineno=b;this.col_offset=c;return this}function Attribute(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);goog.asserts.assert(null!==c&&void 0!==c);this.value=a;this.attr=b;this.ctx=c;this.lineno=d;this.col_offset=e;return this}
function Subscript(a,b,c,d,e){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);goog.asserts.assert(null!==c&&void 0!==c);this.value=a;this.slice=b;this.ctx=c;this.lineno=d;this.col_offset=e;return this}function Name(a,b,c,d){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);this.id=a;this.ctx=b;this.lineno=c;this.col_offset=d;return this}
function List(a,b,c,d){goog.asserts.assert(null!==b&&void 0!==b);this.elts=a;this.ctx=b;this.lineno=c;this.col_offset=d;return this}function Tuple(a,b,c,d){goog.asserts.assert(null!==b&&void 0!==b);this.elts=a;this.ctx=b;this.lineno=c;this.col_offset=d;return this}function Ellipsis(){return this}function Slice(a,b,c){this.lower=a;this.upper=b;this.step=c;return this}function ExtSlice(a){this.dims=a;return this}function Index(a){goog.asserts.assert(null!==a&&void 0!==a);this.value=a;return this}
function comprehension(a,b,c){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);this.target=a;this.iter=b;this.ifs=c;return this}function ExceptHandler(a,b,c,d,e){this.type=a;this.name=b;this.body=c;this.lineno=d;this.col_offset=e;return this}function arguments_(a,b,c,d){this.args=a;this.vararg=b;this.kwarg=c;this.defaults=d;return this}
function keyword(a,b){goog.asserts.assert(null!==a&&void 0!==a);goog.asserts.assert(null!==b&&void 0!==b);this.arg=a;this.value=b;return this}function alias(a,b){goog.asserts.assert(null!==a&&void 0!==a);this.name=a;this.asname=b;return this}Module.prototype._astname="Module";Module.prototype._fields=["body",function(a){return a.body}];Interactive.prototype._astname="Interactive";Interactive.prototype._fields=["body",function(a){return a.body}];Expression.prototype._astname="Expression";
Expression.prototype._fields=["body",function(a){return a.body}];Suite.prototype._astname="Suite";Suite.prototype._fields=["body",function(a){return a.body}];FunctionDef.prototype._astname="FunctionDef";FunctionDef.prototype._fields=["name",function(a){return a.name},"args",function(a){return a.args},"body",function(a){return a.body},"decorator_list",function(a){return a.decorator_list}];ClassDef.prototype._astname="ClassDef";
ClassDef.prototype._fields=["name",function(a){return a.name},"bases",function(a){return a.bases},"body",function(a){return a.body},"decorator_list",function(a){return a.decorator_list}];Return_.prototype._astname="Return";Return_.prototype._fields=["value",function(a){return a.value}];Delete_.prototype._astname="Delete";Delete_.prototype._fields=["targets",function(a){return a.targets}];Assign.prototype._astname="Assign";Assign.prototype._fields=["targets",function(a){return a.targets},"value",function(a){return a.value}];
AugAssign.prototype._astname="AugAssign";AugAssign.prototype._fields=["target",function(a){return a.target},"op",function(a){return a.op},"value",function(a){return a.value}];Print.prototype._astname="Print";Print.prototype._fields=["dest",function(a){return a.dest},"values",function(a){return a.values},"nl",function(a){return a.nl}];For_.prototype._astname="For";
For_.prototype._fields=["target",function(a){return a.target},"iter",function(a){return a.iter},"body",function(a){return a.body},"orelse",function(a){return a.orelse}];While_.prototype._astname="While";While_.prototype._fields=["test",function(a){return a.test},"body",function(a){return a.body},"orelse",function(a){return a.orelse}];If_.prototype._astname="If";If_.prototype._fields=["test",function(a){return a.test},"body",function(a){return a.body},"orelse",function(a){return a.orelse}];
With_.prototype._astname="With";With_.prototype._fields=["context_expr",function(a){return a.context_expr},"optional_vars",function(a){return a.optional_vars},"body",function(a){return a.body}];Raise.prototype._astname="Raise";Raise.prototype._fields=["type",function(a){return a.type},"inst",function(a){return a.inst},"tback",function(a){return a.tback}];TryExcept.prototype._astname="TryExcept";
TryExcept.prototype._fields=["body",function(a){return a.body},"handlers",function(a){return a.handlers},"orelse",function(a){return a.orelse}];TryFinally.prototype._astname="TryFinally";TryFinally.prototype._fields=["body",function(a){return a.body},"finalbody",function(a){return a.finalbody}];Assert.prototype._astname="Assert";Assert.prototype._fields=["test",function(a){return a.test},"msg",function(a){return a.msg}];Import_.prototype._astname="Import";Import_.prototype._fields=["names",function(a){return a.names}];
ImportFrom.prototype._astname="ImportFrom";ImportFrom.prototype._fields=["module",function(a){return a.module},"names",function(a){return a.names},"level",function(a){return a.level}];Exec.prototype._astname="Exec";Exec.prototype._fields=["body",function(a){return a.body},"globals",function(a){return a.globals},"locals",function(a){return a.locals}];Global.prototype._astname="Global";Global.prototype._fields=["names",function(a){return a.names}];Expr.prototype._astname="Expr";
Expr.prototype._fields=["value",function(a){return a.value}];Pass.prototype._astname="Pass";Pass.prototype._fields=[];Break_.prototype._astname="Break";Break_.prototype._fields=[];Continue_.prototype._astname="Continue";Continue_.prototype._fields=[];Debugger_.prototype._astname="Debugger";Debugger_.prototype._fields=[];BoolOp.prototype._astname="BoolOp";BoolOp.prototype._fields=["op",function(a){return a.op},"values",function(a){return a.values}];BinOp.prototype._astname="BinOp";
BinOp.prototype._fields=["left",function(a){return a.left},"op",function(a){return a.op},"right",function(a){return a.right}];UnaryOp.prototype._astname="UnaryOp";UnaryOp.prototype._fields=["op",function(a){return a.op},"operand",function(a){return a.operand}];Lambda.prototype._astname="Lambda";Lambda.prototype._fields=["args",function(a){return a.args},"body",function(a){return a.body}];IfExp.prototype._astname="IfExp";
IfExp.prototype._fields=["test",function(a){return a.test},"body",function(a){return a.body},"orelse",function(a){return a.orelse}];Dict.prototype._astname="Dict";Dict.prototype._fields=["keys",function(a){return a.keys},"values",function(a){return a.values}];Set.prototype._astname="Set";Set.prototype._fields=["elts",function(a){return a.elts}];ListComp.prototype._astname="ListComp";ListComp.prototype._fields=["elt",function(a){return a.elt},"generators",function(a){return a.generators}];
SetComp.prototype._astname="SetComp";SetComp.prototype._fields=["elt",function(a){return a.elt},"generators",function(a){return a.generators}];DictComp.prototype._astname="DictComp";DictComp.prototype._fields=["key",function(a){return a.key},"value",function(a){return a.value},"generators",function(a){return a.generators}];GeneratorExp.prototype._astname="GeneratorExp";GeneratorExp.prototype._fields=["elt",function(a){return a.elt},"generators",function(a){return a.generators}];
Yield.prototype._astname="Yield";Yield.prototype._fields=["value",function(a){return a.value}];Compare.prototype._astname="Compare";Compare.prototype._fields=["left",function(a){return a.left},"ops",function(a){return a.ops},"comparators",function(a){return a.comparators}];Call.prototype._astname="Call";Call.prototype._fields=["func",function(a){return a.func},"args",function(a){return a.args},"keywords",function(a){return a.keywords},"starargs",function(a){return a.starargs},"kwargs",function(a){return a.kwargs}];
Repr.prototype._astname="Repr";Repr.prototype._fields=["value",function(a){return a.value}];Num.prototype._astname="Num";Num.prototype._fields=["n",function(a){return a.n}];Str.prototype._astname="Str";Str.prototype._fields=["s",function(a){return a.s}];Attribute.prototype._astname="Attribute";Attribute.prototype._fields=["value",function(a){return a.value},"attr",function(a){return a.attr},"ctx",function(a){return a.ctx}];Subscript.prototype._astname="Subscript";
Subscript.prototype._fields=["value",function(a){return a.value},"slice",function(a){return a.slice},"ctx",function(a){return a.ctx}];Name.prototype._astname="Name";Name.prototype._fields=["id",function(a){return a.id},"ctx",function(a){return a.ctx}];List.prototype._astname="List";List.prototype._fields=["elts",function(a){return a.elts},"ctx",function(a){return a.ctx}];Tuple.prototype._astname="Tuple";Tuple.prototype._fields=["elts",function(a){return a.elts},"ctx",function(a){return a.ctx}];
Load.prototype._astname="Load";Load.prototype._isenum=!0;Store.prototype._astname="Store";Store.prototype._isenum=!0;Del.prototype._astname="Del";Del.prototype._isenum=!0;AugLoad.prototype._astname="AugLoad";AugLoad.prototype._isenum=!0;AugStore.prototype._astname="AugStore";AugStore.prototype._isenum=!0;Param.prototype._astname="Param";Param.prototype._isenum=!0;Ellipsis.prototype._astname="Ellipsis";Ellipsis.prototype._fields=[];Slice.prototype._astname="Slice";
Slice.prototype._fields=["lower",function(a){return a.lower},"upper",function(a){return a.upper},"step",function(a){return a.step}];ExtSlice.prototype._astname="ExtSlice";ExtSlice.prototype._fields=["dims",function(a){return a.dims}];Index.prototype._astname="Index";Index.prototype._fields=["value",function(a){return a.value}];And.prototype._astname="And";And.prototype._isenum=!0;Or.prototype._astname="Or";Or.prototype._isenum=!0;Add.prototype._astname="Add";Add.prototype._isenum=!0;
Sub.prototype._astname="Sub";Sub.prototype._isenum=!0;Mult.prototype._astname="Mult";Mult.prototype._isenum=!0;Div.prototype._astname="Div";Div.prototype._isenum=!0;Mod.prototype._astname="Mod";Mod.prototype._isenum=!0;Pow.prototype._astname="Pow";Pow.prototype._isenum=!0;LShift.prototype._astname="LShift";LShift.prototype._isenum=!0;RShift.prototype._astname="RShift";RShift.prototype._isenum=!0;BitOr.prototype._astname="BitOr";BitOr.prototype._isenum=!0;BitXor.prototype._astname="BitXor";
BitXor.prototype._isenum=!0;BitAnd.prototype._astname="BitAnd";BitAnd.prototype._isenum=!0;FloorDiv.prototype._astname="FloorDiv";FloorDiv.prototype._isenum=!0;Invert.prototype._astname="Invert";Invert.prototype._isenum=!0;Not.prototype._astname="Not";Not.prototype._isenum=!0;UAdd.prototype._astname="UAdd";UAdd.prototype._isenum=!0;USub.prototype._astname="USub";USub.prototype._isenum=!0;Eq.prototype._astname="Eq";Eq.prototype._isenum=!0;NotEq.prototype._astname="NotEq";NotEq.prototype._isenum=!0;
Lt.prototype._astname="Lt";Lt.prototype._isenum=!0;LtE.prototype._astname="LtE";LtE.prototype._isenum=!0;Gt.prototype._astname="Gt";Gt.prototype._isenum=!0;GtE.prototype._astname="GtE";GtE.prototype._isenum=!0;Is.prototype._astname="Is";Is.prototype._isenum=!0;IsNot.prototype._astname="IsNot";IsNot.prototype._isenum=!0;In_.prototype._astname="In";In_.prototype._isenum=!0;NotIn.prototype._astname="NotIn";NotIn.prototype._isenum=!0;comprehension.prototype._astname="comprehension";
comprehension.prototype._fields=["target",function(a){return a.target},"iter",function(a){return a.iter},"ifs",function(a){return a.ifs}];ExceptHandler.prototype._astname="ExceptHandler";ExceptHandler.prototype._fields=["type",function(a){return a.type},"name",function(a){return a.name},"body",function(a){return a.body}];arguments_.prototype._astname="arguments";
arguments_.prototype._fields=["args",function(a){return a.args},"vararg",function(a){return a.vararg},"kwarg",function(a){return a.kwarg},"defaults",function(a){return a.defaults}];keyword.prototype._astname="keyword";keyword.prototype._fields=["arg",function(a){return a.arg},"value",function(a){return a.value}];alias.prototype._astname="alias";alias.prototype._fields=["name",function(a){return a.name},"asname",function(a){return a.asname}];var SYM=Sk.ParseTables.sym,TOK=Sk.Tokenizer.Tokens,COMP_GENEXP=0,COMP_SETCOMP=1;function Compiling(a,b,c){this.c_encoding=a;this.c_filename=b;this.c_flags=c||0}function NCH(a){goog.asserts.assert(void 0!==a);return null===a.children?0:a.children.length}function CHILD(a,b){goog.asserts.assert(void 0!==a);goog.asserts.assert(void 0!==b);return a.children[b]}function REQ(a,b){goog.asserts.assert(a.type===b,"node wasn't expected type")}
function strobj(a){goog.asserts.assert("string"===typeof a,"expecting string, got "+typeof a);return new Sk.builtin.str(a)}
function numStmts(a){var b,c,d;switch(a.type){case SYM.single_input:if(CHILD(a,0).type===TOK.T_NEWLINE)break;else return numStmts(CHILD(a,0));case SYM.file_input:for(c=d=0;c<NCH(a);++c)b=CHILD(a,c),b.type===SYM.stmt&&(d+=numStmts(b));return d;case SYM.stmt:return numStmts(CHILD(a,0));case SYM.compound_stmt:return 1;case SYM.simple_stmt:return Math.floor(NCH(a)/2);case SYM.suite:if(1===NCH(a))return numStmts(CHILD(a,0));d=0;for(c=2;c<NCH(a)-1;++c)d+=numStmts(CHILD(a,c));return d;default:goog.asserts.fail("Non-statement found")}return 0}
function forbiddenCheck(a,b,c,d){if("None"===c)throw new Sk.builtin.SyntaxError("assignment to None",a.c_filename,d);if("True"===c||"False"===c)throw new Sk.builtin.SyntaxError("assignment to True or False is forbidden",a.c_filename,d);}
function setContext(a,b,c,d){var e,f;goog.asserts.assert(c!==AugStore&&c!==AugLoad);e=f=null;switch(b.constructor){case Attribute:case Name:c===Store&&forbiddenCheck(a,d,b.attr,d.lineno);b.ctx=c;break;case Subscript:b.ctx=c;break;case List:b.ctx=c;f=b.elts;break;case Tuple:if(0===b.elts.length)throw new Sk.builtin.SyntaxError("can't assign to ()",a.c_filename,d.lineno);b.ctx=c;f=b.elts;break;case Lambda:e="lambda";break;case Call:e="function call";break;case BoolOp:case BinOp:case UnaryOp:e="operator";
break;case GeneratorExp:e="generator expression";break;case Yield:e="yield expression";break;case ListComp:e="list comprehension";break;case SetComp:e="set comprehension";break;case DictComp:e="dict comprehension";break;case Dict:case Set:case Num:case Str:e="literal";break;case Compare:e="comparison";break;case Repr:e="repr";break;case IfExp:e="conditional expression";break;default:goog.asserts.fail("unhandled expression in assignment")}if(e)throw new Sk.builtin.SyntaxError("can't "+(c===Store?"assign to":
"delete")+" "+e,a.c_filename,d.lineno);if(f)for(b=0;b<f.length;++b)setContext(a,f[b],c,d)}var operatorMap={};(function(){operatorMap[TOK.T_VBAR]=BitOr;operatorMap[TOK.T_CIRCUMFLEX]=BitXor;operatorMap[TOK.T_AMPER]=BitAnd;operatorMap[TOK.T_LEFTSHIFT]=LShift;operatorMap[TOK.T_RIGHTSHIFT]=RShift;operatorMap[TOK.T_PLUS]=Add;operatorMap[TOK.T_MINUS]=Sub;operatorMap[TOK.T_STAR]=Mult;operatorMap[TOK.T_SLASH]=Div;operatorMap[TOK.T_DOUBLESLASH]=FloorDiv;operatorMap[TOK.T_PERCENT]=Mod})();
function getOperator(a){goog.asserts.assert(void 0!==operatorMap[a.type]);return operatorMap[a.type]}
function astForCompOp(a,b){REQ(b,SYM.comp_op);if(1===NCH(b))switch(b=CHILD(b,0),b.type){case TOK.T_LESS:return Lt;case TOK.T_GREATER:return Gt;case TOK.T_EQEQUAL:return Eq;case TOK.T_LESSEQUAL:return LtE;case TOK.T_GREATEREQUAL:return GtE;case TOK.T_NOTEQUAL:return NotEq;case TOK.T_NAME:if("in"===b.value)return In_;if("is"===b.value)return Is}else if(2===NCH(b)&&CHILD(b,0).type===TOK.T_NAME){if("in"===CHILD(b,1).value)return NotIn;if("is"===CHILD(b,0).value)return IsNot}goog.asserts.fail("invalid comp_op")}
function seqForTestlist(a,b){var c,d=[];goog.asserts.assert(b.type===SYM.testlist||b.type===SYM.listmaker||b.type===SYM.testlist_comp||b.type===SYM.testlist_safe||b.type===SYM.testlist1);for(c=0;c<NCH(b);c+=2)goog.asserts.assert(CHILD(b,c).type===SYM.test||CHILD(b,c).type===SYM.old_test),d[c/2]=astForExpr(a,CHILD(b,c));return d}
function astForSuite(a,b){var c,d,e,f,g;REQ(b,SYM.suite);g=[];f=0;if(CHILD(b,0).type===SYM.simple_stmt)for(b=CHILD(b,0),e=NCH(b)-1,CHILD(b,e-1).type===TOK.T_SEMI&&(e-=1),d=0;d<e;d+=2)g[f++]=astForStmt(a,CHILD(b,d));else for(d=2;d<NCH(b)-1;++d)if(e=CHILD(b,d),REQ(e,SYM.stmt),c=numStmts(e),1===c)g[f++]=astForStmt(a,e);else for(e=CHILD(e,0),REQ(e,SYM.simple_stmt),c=0;c<NCH(e);c+=2){if(0===NCH(CHILD(e,c))){goog.asserts.assert(c+1===NCH(e));break}g[f++]=astForStmt(a,CHILD(e,c))}goog.asserts.assert(f===
numStmts(b));return g}
function astForExceptClause(a,b,c){var d;REQ(b,SYM.except_clause);REQ(c,SYM.suite);if(1===NCH(b))return new ExceptHandler(null,null,astForSuite(a,c),b.lineno,b.col_offset);if(2===NCH(b))return new ExceptHandler(astForExpr(a,CHILD(b,1)),null,astForSuite(a,c),b.lineno,b.col_offset);if(4===NCH(b))return d=astForExpr(a,CHILD(b,3)),setContext(a,d,Store,CHILD(b,3)),new ExceptHandler(astForExpr(a,CHILD(b,1)),d,astForSuite(a,c),b.lineno,b.col_offset);goog.asserts.fail("wrong number of children for except clause")}
function astForTryStmt(a,b){var c,d,e;d=NCH(b);c=(d-3)/3;var f,g=[],h=null;REQ(b,SYM.try_stmt);f=astForSuite(a,CHILD(b,2));if(CHILD(b,d-3).type===TOK.T_NAME)"finally"===CHILD(b,d-3).value?(9<=d&&CHILD(b,d-6).type===TOK.T_NAME&&(g=astForSuite(a,CHILD(b,d-4)),c--),h=astForSuite(a,CHILD(b,d-1))):g=astForSuite(a,CHILD(b,d-1)),c--;else if(CHILD(b,d-3).type!==SYM.except_clause)throw new Sk.builtin.SyntaxError("malformed 'try' statement",a.c_filename,b.lineno);if(0<c){e=[];for(d=0;d<c;++d)e[d]=astForExceptClause(a,
CHILD(b,3+3*d),CHILD(b,5+3*d));c=new TryExcept(f,e,g,b.lineno,b.col_offset);if(!h)return c;f=[c]}goog.asserts.assert(null!==h);return new TryFinally(f,h,b.lineno,b.col_offset)}function astForDottedName(a,b){var c,d,e,f,g;REQ(b,SYM.dotted_name);g=b.lineno;f=b.col_offset;e=strobj(CHILD(b,0).value);d=new Name(e,Load,g,f);for(c=2;c<NCH(b);c+=2)e=strobj(CHILD(b,c).value),d=new Attribute(d,e,Load,g,f);return d}
function astForDecorator(a,b){var c;REQ(b,SYM.decorator);REQ(CHILD(b,0),TOK.T_AT);REQ(CHILD(b,NCH(b)-1),TOK.T_NEWLINE);c=astForDottedName(a,CHILD(b,1));return 3===NCH(b)?c:5===NCH(b)?new Call(c,[],[],null,null,b.lineno,b.col_offset):astForCall(a,CHILD(b,3),c)}function astForDecorators(a,b){var c,d;REQ(b,SYM.decorators);d=[];for(c=0;c<NCH(b);++c)d[c]=astForDecorator(a,CHILD(b,c));return d}
function astForDecorated(a,b){var c,d;REQ(b,SYM.decorated);d=astForDecorators(a,CHILD(b,0));goog.asserts.assert(CHILD(b,1).type===SYM.funcdef||CHILD(b,1).type===SYM.classdef);c=null;CHILD(b,1).type===SYM.funcdef?c=astForFuncdef(a,CHILD(b,1),d):CHILD(b,1)===SYM.classdef&&(c=astForClassdef(a,CHILD(b,1),d));c&&(c.lineno=b.lineno,c.col_offset=b.col_offset);return c}function astForWithVar(a,b){REQ(b,SYM.with_item);return astForExpr(a,CHILD(b,1))}
function astForWithStmt(a,b){var c,d,e=3;goog.asserts.assert(b.type===SYM.with_stmt);d=astForExpr(a,CHILD(b,1));CHILD(b,2).type===SYM.with_item&&(c=astForWithVar(a,CHILD(b,2)),setContext(a,c,Store,b),e=4);return new With_(d,c,astForSuite(a,CHILD(b,e)),b.lineno,b.col_offset)}
function astForExecStmt(a,b){var c,d=null,e=null,f=NCH(b);goog.asserts.assert(2===f||4===f||6===f);REQ(b,SYM.exec_stmt);c=astForExpr(a,CHILD(b,1));4<=f&&(d=astForExpr(a,CHILD(b,3)));6===f&&(e=astForExpr(a,CHILD(b,5)));return new Exec(c,d,e,b.lineno,b.col_offset)}
function astForIfStmt(a,b){var c,d,e,f;REQ(b,SYM.if_stmt);if(4===NCH(b))return new If_(astForExpr(a,CHILD(b,1)),astForSuite(a,CHILD(b,3)),[],b.lineno,b.col_offset);e=CHILD(b,4).value.charAt(2);if("s"===e)return new If_(astForExpr(a,CHILD(b,1)),astForSuite(a,CHILD(b,3)),astForSuite(a,CHILD(b,6)),b.lineno,b.col_offset);if("i"===e){f=NCH(b)-4;c=!1;e=[];CHILD(b,f+1).type===TOK.T_NAME&&"s"===CHILD(b,f+1).value.charAt(2)&&(c=!0,f-=3);f/=4;c&&(e=[new If_(astForExpr(a,CHILD(b,NCH(b)-6)),astForSuite(a,CHILD(b,
NCH(b)-4)),astForSuite(a,CHILD(b,NCH(b)-1)),CHILD(b,NCH(b)-6).lineno,CHILD(b,NCH(b)-6).col_offset)],f--);for(d=0;d<f;++d)c=5+4*(f-d-1),e=[new If_(astForExpr(a,CHILD(b,c)),astForSuite(a,CHILD(b,c+2)),e,CHILD(b,c).lineno,CHILD(b,c).col_offset)];return new If_(astForExpr(a,CHILD(b,1)),astForSuite(a,CHILD(b,3)),e,b.lineno,b.col_offset)}goog.asserts.fail("unexpected token in 'if' statement")}
function astForExprlist(a,b,c){var d,e,f;REQ(b,SYM.exprlist);f=[];for(e=0;e<NCH(b);e+=2)d=astForExpr(a,CHILD(b,e)),f[e/2]=d,c&&setContext(a,d,c,CHILD(b,e));return f}function astForDelStmt(a,b){REQ(b,SYM.del_stmt);return new Delete_(astForExprlist(a,CHILD(b,1),Del),b.lineno,b.col_offset)}function astForGlobalStmt(a,b){var c,d=[];REQ(b,SYM.global_stmt);for(c=1;c<NCH(b);c+=2)d[(c-1)/2]=strobj(CHILD(b,c).value);return new Global(d,b.lineno,b.col_offset)}
function astForAssertStmt(a,b){REQ(b,SYM.assert_stmt);if(2===NCH(b))return new Assert(astForExpr(a,CHILD(b,1)),null,b.lineno,b.col_offset);if(4===NCH(b))return new Assert(astForExpr(a,CHILD(b,1)),astForExpr(a,CHILD(b,3)),b.lineno,b.col_offset);goog.asserts.fail("improper number of parts to assert stmt")}
function aliasForImportName(a,b){var c,d;a:for(;;)switch(b.type){case SYM.import_as_name:return d=null,c=strobj(CHILD(b,0).value),3===NCH(b)&&(d=CHILD(b,2).value),new alias(c,null==d?null:strobj(d));case SYM.dotted_as_name:if(1===NCH(b)){b=CHILD(b,0);continue a}else return d=aliasForImportName(a,CHILD(b,0)),goog.asserts.assert(!d.asname),d.asname=strobj(CHILD(b,2).value),d;case SYM.dotted_name:if(1===NCH(b))return new alias(strobj(CHILD(b,0).value),null);d="";for(c=0;c<NCH(b);c+=2)d+=CHILD(b,c).value+
".";return new alias(strobj(d.substr(0,d.length-1)),null);case TOK.T_STAR:return new alias(strobj("*"),null);default:throw new Sk.builtin.SyntaxError("unexpected import name",a.c_filename,b.lineno);}}
function astForImportStmt(a,b){var c,d,e,f,g,h;REQ(b,SYM.import_stmt);h=b.lineno;g=b.col_offset;b=CHILD(b,0);if(b.type===SYM.import_name){b=CHILD(b,1);REQ(b,SYM.dotted_as_names);d=[];for(f=0;f<NCH(b);f+=2)d[f/2]=aliasForImportName(a,CHILD(b,f));return new Import_(d,h,g)}if(b.type===SYM.import_from){c=null;e=0;for(d=1;d<NCH(b);++d){if(CHILD(b,d).type===SYM.dotted_name){c=aliasForImportName(a,CHILD(b,d));d++;break}else if(CHILD(b,d).type!==TOK.T_DOT)break;e++}++d;switch(CHILD(b,d).type){case TOK.T_STAR:b=
CHILD(b,d);break;case TOK.T_LPAR:b=CHILD(b,d+1);NCH(b);break;case SYM.import_as_names:b=CHILD(b,d);d=NCH(b);if(0===d%2)throw new Sk.builtin.SyntaxError("trailing comma not allowed without surrounding parentheses",a.c_filename,b.lineno);break;default:throw new Sk.builtin.SyntaxError("Unexpected node-type in from-import",a.c_filename,b.lineno);}d=[];if(b.type===TOK.T_STAR)d[0]=aliasForImportName(a,b);else for(f=0;f<NCH(b);f+=2)d[f/2]=aliasForImportName(a,CHILD(b,f));c=c?c.name.v:"";return new ImportFrom(strobj(c),
d,e,h,g)}throw new Sk.builtin.SyntaxError("unknown import statement",a.c_filename,b.lineno);}function astForTestlistComp(a,b){goog.asserts.assert(b.type===SYM.testlist_comp||b.type===SYM.argument);return 1<NCH(b)&&CHILD(b,1).type===SYM.comp_for?astForGenExpr(a,b):astForTestlist(a,b)}
function astForListcomp(a,b){function c(a,b){for(var c=0;;){REQ(b,SYM.list_iter);if(CHILD(b,0).type===SYM.list_for)return c;b=CHILD(b,0);REQ(b,SYM.list_if);c++;if(2==NCH(b))return c;b=CHILD(b,2)}}var d,e,f,g,h,k,l,m,q;REQ(b,SYM.listmaker);goog.asserts.assert(1<NCH(b));q=astForExpr(a,CHILD(b,0));m=function(a,b){var c=0,d=CHILD(b,1);a:for(;;){c++;REQ(d,SYM.list_for);if(5===NCH(d))d=CHILD(d,4);else return c;b:for(;;){REQ(d,SYM.list_iter);d=CHILD(d,0);if(d.type===SYM.list_for)continue a;else if(d.type===
SYM.list_if)if(3===NCH(d)){d=CHILD(d,2);continue b}else return c;break}break}}(a,b);l=[];k=CHILD(b,1);for(h=0;h<m;++h){REQ(k,SYM.list_for);f=CHILD(k,1);e=astForExprlist(a,f,Store);d=astForTestlist(a,CHILD(k,3));g=1===NCH(f)?new comprehension(e[0],d,[]):new comprehension(new Tuple(e,Store,k.lineno,k.col_offset),d,[]);if(5===NCH(k)){k=CHILD(k,4);f=c(a,k);e=[];for(d=0;d<f;++d)REQ(k,SYM.list_iter),k=CHILD(k,0),REQ(k,SYM.list_if),e[d]=astForExpr(a,CHILD(k,1)),3===NCH(k)&&(k=CHILD(k,2));k.type===SYM.list_iter&&
(k=CHILD(k,0));g.ifs=e}l[h]=g}return new ListComp(q,l,b.lineno,b.col_offset)}
function astForFactor(a,b){var c,d;if(CHILD(b,0).type===TOK.T_MINUS&&2===NCH(b)&&(c=CHILD(b,1),c.type===SYM.factor&&1===NCH(c)&&(c=CHILD(c,0),c.type===SYM.power&&1===NCH(c)&&(d=CHILD(c,0),d.type===SYM.atom&&(c=CHILD(d,0),c.type===TOK.T_NUMBER)))))return c.value="-"+c.value,astForAtom(a,d);c=astForExpr(a,CHILD(b,1));switch(CHILD(b,0).type){case TOK.T_PLUS:return new UnaryOp(UAdd,c,b.lineno,b.col_offset);case TOK.T_MINUS:return new UnaryOp(USub,c,b.lineno,b.col_offset);case TOK.T_TILDE:return new UnaryOp(Invert,
c,b.lineno,b.col_offset)}goog.asserts.fail("unhandled factor")}function astForForStmt(a,b){var c,d,e=[];REQ(b,SYM.for_stmt);9===NCH(b)&&(e=astForSuite(a,CHILD(b,8)));d=CHILD(b,1);c=astForExprlist(a,d,Store);c=1===NCH(d)?c[0]:new Tuple(c,Store,b.lineno,b.col_offset);return new For_(c,astForTestlist(a,CHILD(b,3)),astForSuite(a,CHILD(b,5)),e,b.lineno,b.col_offset)}
function astForCall(a,b,c){var d,e,f,g,h,k,l,m,q,n,r;REQ(b,SYM.arglist);for(q=g=n=r=0;q<NCH(b);q++)m=CHILD(b,q),m.type===SYM.argument&&(1===NCH(m)?r++:CHILD(m,1).type===SYM.comp_for?g++:n++);if(1<g||g&&(r||n))throw new Sk.builtin.SyntaxError("Generator expression must be parenthesized if not sole argument",a.c_filename,b.lineno);if(255<r+n+g)throw new Sk.builtin.SyntaxError("more than 255 arguments",a.c_filename,b.lineno);l=[];k=[];n=r=0;g=h=null;for(q=0;q<NCH(b);q++)if(m=CHILD(b,q),m.type===SYM.argument)if(1===
NCH(m)){if(n)throw new Sk.builtin.SyntaxError("non-keyword arg after keyword arg",a.c_filename,b.lineno);if(h)throw new Sk.builtin.SyntaxError("only named arguments may follow *expression",a.c_filename,b.lineno);l[r++]=astForExpr(a,CHILD(m,0))}else if(CHILD(m,1).type===SYM.comp_for)l[r++]=astForGenExpr(a,m);else{d=astForExpr(a,CHILD(m,0));if(d.constructor===Lambda)throw new Sk.builtin.SyntaxError("lambda cannot contain assignment",a.c_filename,b.lineno);if(d.constructor!==Name)throw new Sk.builtin.SyntaxError("keyword can't be an expression",
a.c_filename,b.lineno);f=d.id;forbiddenCheck(a,CHILD(m,0),f,b.lineno);for(e=0;e<n;++e)if(d=k[e].arg,d===f)throw new Sk.builtin.SyntaxError("keyword argument repeated",a.c_filename,b.lineno);k[n++]=new keyword(f,astForExpr(a,CHILD(m,2)))}else m.type===TOK.T_STAR?h=astForExpr(a,CHILD(b,++q)):m.type===TOK.T_DOUBLESTAR&&(g=astForExpr(a,CHILD(b,++q)));return new Call(c,l,k,h,g,c.lineno,c.col_offset)}
function astForTrailer(a,b,c){var d,e,f,g;REQ(b,SYM.trailer);if(CHILD(b,0).type===TOK.T_LPAR)return 2===NCH(b)?new Call(c,[],[],null,null,b.lineno,b.col_offset):astForCall(a,CHILD(b,1),c);if(CHILD(b,0).type===TOK.T_DOT)return new Attribute(c,strobj(CHILD(b,1).value),Load,b.lineno,b.col_offset);REQ(CHILD(b,0),TOK.T_LSQB);REQ(CHILD(b,2),TOK.T_RSQB);b=CHILD(b,1);if(1===NCH(b))return new Subscript(c,astForSlice(a,CHILD(b,0)),Load,b.lineno,b.col_offset);g=!0;f=[];for(e=0;e<NCH(b);e+=2)d=astForSlice(a,
CHILD(b,e)),d.constructor!==Index&&(g=!1),f[e/2]=d;if(!g)return new Subscript(c,new ExtSlice(f),Load,b.lineno,b.col_offset);a=[];for(e=0;e<f.length;++e)d=f[e],goog.asserts.assert(d.constructor===Index&&null!==d.value&&void 0!==d.value),a[e]=d.value;d=new Tuple(a,Load,b.lineno,b.col_offset);return new Subscript(c,new Index(d),Load,b.lineno,b.col_offset)}
function astForFlowStmt(a,b){var c;REQ(b,SYM.flow_stmt);c=CHILD(b,0);switch(c.type){case SYM.break_stmt:return new Break_(b.lineno,b.col_offset);case SYM.continue_stmt:return new Continue_(b.lineno,b.col_offset);case SYM.yield_stmt:return new Expr(astForExpr(a,CHILD(c,0)),b.lineno,b.col_offset);case SYM.return_stmt:return 1===NCH(c)?new Return_(null,b.lineno,b.col_offset):new Return_(astForTestlist(a,CHILD(c,1)),b.lineno,b.col_offset);case SYM.raise_stmt:if(1===NCH(c))return new Raise(null,null,null,
b.lineno,b.col_offset);if(2===NCH(c))return new Raise(astForExpr(a,CHILD(c,1)),null,null,b.lineno,b.col_offset);if(4===NCH(c))return new Raise(astForExpr(a,CHILD(c,1)),astForExpr(a,CHILD(c,3)),null,b.lineno,b.col_offset);if(6===NCH(c))return new Raise(astForExpr(a,CHILD(c,1)),astForExpr(a,CHILD(c,3)),astForExpr(a,CHILD(c,5)),b.lineno,b.col_offset);break;default:goog.asserts.fail("unexpected flow_stmt")}goog.asserts.fail("unhandled flow statement")}
function astForArguments(a,b){var c,d,e,f,g,h,k,l,m,q=null,n=null;if(b.type===SYM.parameters){if(2===NCH(b))return new arguments_([],null,null,[]);b=CHILD(b,1)}REQ(b,SYM.varargslist);l=[];k=[];h=!1;for(e=f=g=0;g<NCH(b);)switch(m=CHILD(b,g),m.type){case SYM.fpdef:c=0;a:for(;;){if(g+1<NCH(b)&&CHILD(b,g+1).type===TOK.T_EQUAL)k[f++]=astForExpr(a,CHILD(b,g+2)),g+=2,h=!0;else if(h){if(c)throw new Sk.builtin.SyntaxError("parenthesized arg with default",a.c_filename,b.lineno);throw new Sk.builtin.SyntaxError("non-default argument follows default argument",
a.c_filename,b.lineno);}if(3===NCH(m)){m=CHILD(m,1);if(1!==NCH(m))throw new Sk.builtin.SyntaxError("tuple parameter unpacking has been removed",a.c_filename,b.lineno);c=!0;m=CHILD(m,0);goog.asserts.assert(m.type===SYM.fpdef);continue a}CHILD(m,0).type===TOK.T_NAME&&(forbiddenCheck(a,b,CHILD(m,0).value,b.lineno),d=strobj(CHILD(m,0).value),l[e++]=new Name(d,Param,m.lineno,m.col_offset));g+=2;if(c)throw new Sk.builtin.SyntaxError("parenthesized argument names are invalid",a.c_filename,b.lineno);break}break;
case TOK.T_STAR:forbiddenCheck(a,CHILD(b,g+1),CHILD(b,g+1).value,b.lineno);q=strobj(CHILD(b,g+1).value);g+=3;break;case TOK.T_DOUBLESTAR:forbiddenCheck(a,CHILD(b,g+1),CHILD(b,g+1).value,b.lineno);n=strobj(CHILD(b,g+1).value);g+=3;break;default:goog.asserts.fail("unexpected node in varargslist")}return new arguments_(l,q,n,k)}
function astForFuncdef(a,b,c){var d,e;REQ(b,SYM.funcdef);e=strobj(CHILD(b,1).value);forbiddenCheck(a,CHILD(b,1),CHILD(b,1).value,b.lineno);d=astForArguments(a,CHILD(b,2));a=astForSuite(a,CHILD(b,4));return new FunctionDef(e,d,a,c,b.lineno,b.col_offset)}function astForClassBases(a,b){goog.asserts.assert(0<NCH(b));REQ(b,SYM.testlist);return 1===NCH(b)?[astForExpr(a,CHILD(b,0))]:seqForTestlist(a,b)}
function astForClassdef(a,b,c){var d,e;REQ(b,SYM.classdef);forbiddenCheck(a,b,CHILD(b,1).value,b.lineno);e=strobj(CHILD(b,1).value);if(4===NCH(b))return new ClassDef(e,[],astForSuite(a,CHILD(b,3)),c,b.lineno,b.col_offset);if(CHILD(b,3).type===TOK.T_RPAR)return new ClassDef(e,[],astForSuite(a,CHILD(b,5)),c,b.lineno,b.col_offset);d=astForClassBases(a,CHILD(b,3));a=astForSuite(a,CHILD(b,6));return new ClassDef(e,d,a,c,b.lineno,b.col_offset)}
function astForLambdef(a,b){var c,d;3===NCH(b)?(c=new arguments_([],null,null,[]),d=astForExpr(a,CHILD(b,2))):(c=astForArguments(a,CHILD(b,1)),d=astForExpr(a,CHILD(b,3)));return new Lambda(c,d,b.lineno,b.col_offset)}
function astForComprehension(a,b){function c(a,b){for(var c=0;;){REQ(b,SYM.comp_iter);if(CHILD(b,0).type===SYM.comp_for)return c;b=CHILD(b,0);REQ(b,SYM.comp_if);c++;if(2==NCH(b))return c;b=CHILD(b,2)}}var d,e,f,g,h,k,l,m;k=function(a,b){var c=0;a:for(;;){c++;REQ(b,SYM.comp_for);if(5===NCH(b))b=CHILD(b,4);else return c;b:for(;;){REQ(b,SYM.comp_iter);b=CHILD(b,0);if(b.type===SYM.comp_for)continue a;else if(b.type===SYM.comp_if)if(3===NCH(b)){b=CHILD(b,2);continue b}else return c;break}break}goog.asserts.fail("logic error in countCompFors")}(a,
b);l=[];for(h=0;h<k;++h){REQ(b,SYM.comp_for);e=CHILD(b,1);d=astForExprlist(a,e,Store);g=astForExpr(a,CHILD(b,3));m=1===NCH(e)?new comprehension(d[0],g,[]):new comprehension(new Tuple(d,Store,b.lineno,b.col_offset),g,[]);if(5===NCH(b)){b=CHILD(b,4);f=c(a,b);e=[];for(d=0;d<f;++d)REQ(b,SYM.comp_iter),b=CHILD(b,0),REQ(b,SYM.comp_if),g=astForExpr(a,CHILD(b,1)),e[d]=g,3===NCH(b)&&(b=CHILD(b,2));b.type===SYM.comp_iter&&(b=CHILD(b,0));m.ifs=e}l[h]=m}return l}
function astForIterComp(a,b,c){var d;goog.asserts.assert(1<NCH(b));d=astForExpr(a,CHILD(b,0));a=astForComprehension(a,CHILD(b,1));if(c===COMP_GENEXP)return new GeneratorExp(d,a,b.lineno,b.col_offset);if(c===COMP_SETCOMP)return new SetComp(d,a,b.lineno,b.col_offset)}
function astForDictComp(a,b){var c,d,e=[];goog.asserts.assert(3<NCH(b));REQ(CHILD(b,1),TOK.T_COLON);c=astForExpr(a,CHILD(b,0));d=astForExpr(a,CHILD(b,2));e=astForComprehension(a,CHILD(b,3));return new DictComp(c,d,e,b.lineno,b.col_offset)}function astForGenExpr(a,b){goog.asserts.assert(b.type===SYM.testlist_comp||b.type===SYM.argument);return astForIterComp(a,b,COMP_GENEXP)}function astForSetComp(a,b){goog.asserts.assert(b.type===SYM.dictorsetmaker);return astForIterComp(a,b,COMP_SETCOMP)}
function astForWhileStmt(a,b){REQ(b,SYM.while_stmt);if(4===NCH(b))return new While_(astForExpr(a,CHILD(b,1)),astForSuite(a,CHILD(b,3)),[],b.lineno,b.col_offset);if(7===NCH(b))return new While_(astForExpr(a,CHILD(b,1)),astForSuite(a,CHILD(b,3)),astForSuite(a,CHILD(b,6)),b.lineno,b.col_offset);goog.asserts.fail("wrong number of tokens for 'while' stmt")}
function astForAugassign(a,b){REQ(b,SYM.augassign);b=CHILD(b,0);switch(b.value.charAt(0)){case "+":return Add;case "-":return Sub;case "/":return"/"===b.value.charAt(1)?FloorDiv:Div;case "%":return Mod;case "<":return LShift;case ">":return RShift;case "&":return BitAnd;case "^":return BitXor;case "|":return BitOr;case "*":return"*"===b.value.charAt(1)?Pow:Mult;default:goog.asserts.fail("invalid augassign")}}
function astForBinop(a,b){var c,d,e,f,g=new BinOp(astForExpr(a,CHILD(b,0)),getOperator(CHILD(b,1)),astForExpr(a,CHILD(b,2)),b.lineno,b.col_offset),h=(NCH(b)-1)/2;for(f=1;f<h;++f)e=CHILD(b,2*f+1),d=getOperator(e),c=astForExpr(a,CHILD(b,2*f+2)),g=new BinOp(g,d,c,e.lineno,e.col_offset);return g}
function astForTestlist(a,b){goog.asserts.assert(0<NCH(b));b.type===SYM.testlist_comp?1<NCH(b)&&goog.asserts.assert(CHILD(b,1).type!==SYM.comp_for):goog.asserts.assert(b.type===SYM.testlist||b.type===SYM.testlist_safe||b.type===SYM.testlist1);return 1===NCH(b)?astForExpr(a,CHILD(b,0)):new Tuple(seqForTestlist(a,b),Load,b.lineno,b.col_offset)}
function astForExprStmt(a,b){var c,d,e;REQ(b,SYM.expr_stmt);if(1===NCH(b))return new Expr(astForTestlist(a,CHILD(b,0)),b.lineno,b.col_offset);if(CHILD(b,1).type===SYM.augassign){c=CHILD(b,0);e=astForTestlist(a,c);switch(e.constructor){case GeneratorExp:throw new Sk.builtin.SyntaxError("augmented assignment to generator expression not possible",a.c_filename,b.lineno);case Yield:throw new Sk.builtin.SyntaxError("augmented assignment to yield expression not possible",a.c_filename,b.lineno);case Name:d=
e.id;forbiddenCheck(a,c,d,b.lineno);break;case Attribute:case Subscript:break;default:throw new Sk.builtin.SyntaxError("illegal expression for augmented assignment",a.c_filename,b.lineno);}setContext(a,e,Store,c);c=CHILD(b,2);c=c.type===SYM.testlist?astForTestlist(a,c):astForExpr(a,c);return new AugAssign(e,astForAugassign(a,CHILD(b,1)),c,b.lineno,b.col_offset)}REQ(CHILD(b,1),TOK.T_EQUAL);e=[];for(d=0;d<NCH(b)-2;d+=2){c=CHILD(b,d);if(c.type===SYM.yield_expr)throw new Sk.builtin.SyntaxError("assignment to yield expression not possible",
a.c_filename,b.lineno);c=astForTestlist(a,c);setContext(a,c,Store,CHILD(b,d));e[d/2]=c}c=CHILD(b,NCH(b)-1);c=c.type===SYM.testlist?astForTestlist(a,c):astForExpr(a,c);return new Assign(e,c,b.lineno,b.col_offset)}function astForIfexpr(a,b){goog.asserts.assert(5===NCH(b));return new IfExp(astForExpr(a,CHILD(b,2)),astForExpr(a,CHILD(b,0)),astForExpr(a,CHILD(b,4)),b.lineno,b.col_offset)}
function parsestr(a,b){var c=b.charAt(0),d=!1,e=!1;if(a.c_flags&Parser.CO_FUTURE_UNICODE_LITERALS||!0===Sk.python3)e=!0;if("u"===c||"U"===c)b=b.substr(1),c=b.charAt(0),e=!0;else if("r"===c||"R"===c)b=b.substr(1),c=b.charAt(0),d=!0;goog.asserts.assert("b"!==c&&"B"!==c,"todo; haven't done b'' strings yet");goog.asserts.assert("'"===c||'"'===c&&b.charAt(b.length-1)===c);b=b.substr(1,b.length-2);e&&(b=unescape(encodeURIComponent(b)));4<=b.length&&(b.charAt(0)===c&&b.charAt(1)===c)&&(goog.asserts.assert(b.charAt(b.length-
1)===c&&b.charAt(b.length-2)===c),b=b.substr(2,b.length-4));if(d||-1===b.indexOf("\\"))c=strobj(decodeURIComponent(escape(b)));else{for(var c=strobj,d=b,f,g,h,k,l=d.length,m="",e=0;e<l;++e)f=d.charAt(e),"\\"===f?(++e,f=d.charAt(e),"n"===f?m+="\n":"\\"===f?m+="\\":"t"===f?m+="\t":"r"===f?m+="\r":"b"===f?m+="\b":"f"===f?m+="\f":"v"===f?m+="\v":"0"===f?m+="\x00":'"'===f?m+='"':"'"===f?m+="'":"\n"!==f&&("x"===f?(k=d.charAt(++e),h=d.charAt(++e),m+=String.fromCharCode(parseInt(k+h,16))):"u"===f||"U"===
f?(k=d.charAt(++e),h=d.charAt(++e),g=d.charAt(++e),f=d.charAt(++e),m+=String.fromCharCode(parseInt(k+h,16),parseInt(g+f,16))):m+="\\"+f)):m+=f;c=c(m)}return c}function parsestrplus(a,b){var c,d;REQ(CHILD(b,0),TOK.T_STRING);d=new Sk.builtin.str("");for(c=0;c<NCH(b);++c)try{d=d.sq$concat(parsestr(a,CHILD(b,c).value))}catch(e){throw new Sk.builtin.SyntaxError("invalid string (possibly contains a unicode character)",a.c_filename,CHILD(b,c).lineno);}return d}
function parsenumber(a,b,c){a=b.charAt(b.length-1);if("j"===a||"J"===a)return Sk.builtin.complex.complex_subtype_from_string(b);if("l"===a||"L"===a)return Sk.longFromStr(b.substr(0,b.length-1),0);if(-1!==b.indexOf("."))return new Sk.builtin.float_(parseFloat(b));c=b;a=!1;"-"===b.charAt(0)&&(c=b.substr(1),a=!0);if("0"!==c.charAt(0)||"x"!==c.charAt(1)&&"X"!==c.charAt(1)){if(-1!==b.indexOf("e")||-1!==b.indexOf("E"))return new Sk.builtin.float_(parseFloat(b));if("0"!==c.charAt(0)||"b"!==c.charAt(1)&&
"B"!==c.charAt(1))if("0"===c.charAt(0))if("0"===c)c=0;else{c=c.substring(1);if("o"===c.charAt(0)||"O"===c.charAt(0))c=c.substring(1);c=parseInt(c,8)}else c=parseInt(c,10);else c=c.substring(2),c=parseInt(c,2)}else c=c.substring(2),c=parseInt(c,16);return c>Sk.builtin.int_.threshold$&&Math.floor(c)===c&&-1===b.indexOf("e")&&-1===b.indexOf("E")?Sk.longFromStr(b,0):a?new Sk.builtin.int_(-c):new Sk.builtin.int_(c)}
function astForSlice(a,b){var c,d,e,f;REQ(b,SYM.subscript);c=CHILD(b,0);d=e=f=null;if(c.type===TOK.T_DOT)return new Ellipsis;if(1===NCH(b)&&c.type===SYM.test)return new Index(astForExpr(a,c));c.type===SYM.test&&(f=astForExpr(a,c));c.type===TOK.T_COLON?1<NCH(b)&&(c=CHILD(b,1),c.type===SYM.test&&(e=astForExpr(a,c))):2<NCH(b)&&(c=CHILD(b,2),c.type===SYM.test&&(e=astForExpr(a,c)));c=CHILD(b,NCH(b)-1);c.type===SYM.sliceop&&(1===NCH(c)?(c=CHILD(c,0),d=new Name(strobj("None"),Load,c.lineno,c.col_offset)):
(c=CHILD(c,1),c.type===SYM.test&&(d=astForExpr(a,c))));return new Slice(f,e,d)}
function astForAtom(a,b){var c,d,e,f=CHILD(b,0);switch(f.type){case TOK.T_NAME:return new Name(strobj(f.value),Load,b.lineno,b.col_offset);case TOK.T_STRING:return new Str(parsestrplus(a,b),b.lineno,b.col_offset);case TOK.T_NUMBER:return new Num(parsenumber(a,f.value,b.lineno),b.lineno,b.col_offset);case TOK.T_LPAR:return f=CHILD(b,1),f.type===TOK.T_RPAR?new Tuple([],Load,b.lineno,b.col_offset):f.type===SYM.yield_expr?astForExpr(a,f):astForTestlistComp(a,f);case TOK.T_LSQB:f=CHILD(b,1);if(f.type===
TOK.T_RSQB)return new List([],Load,b.lineno,b.col_offset);REQ(f,SYM.listmaker);return 1===NCH(f)||CHILD(f,1).type===TOK.T_COMMA?new List(seqForTestlist(a,f),Load,b.lineno,b.col_offset):astForListcomp(a,f);case TOK.T_LBRACE:e=[];d=[];f=CHILD(b,1);if(b.type===TOK.T_RBRACE)return new Dict([],null,b.lineno,b.col_offset);if(1===NCH(f)||0!==NCH(f)&&CHILD(f,1).type===TOK.T_COMMA){d=[];NCH(f);for(c=0;c<NCH(f);c+=2)e=astForExpr(a,CHILD(f,c)),d[c/2]=e;return new Set(d,b.lineno,b.col_offset)}if(0!==NCH(f)&&
CHILD(f,1).type==SYM.comp_for)return astForSetComp(a,f);if(3<NCH(f)&&CHILD(f,3).type===SYM.comp_for)return astForDictComp(a,f);NCH(f);for(c=0;c<NCH(f);c+=4)e[c/4]=astForExpr(a,CHILD(f,c)),d[c/4]=astForExpr(a,CHILD(f,c+2));return new Dict(e,d,b.lineno,b.col_offset);case TOK.T_BACKQUOTE:return new Repr(astForTestlist(a,CHILD(b,1)),b.lineno,b.col_offset);default:goog.asserts.fail("unhandled atom",f.type)}}
function astForPower(a,b){var c,d,e;REQ(b,SYM.power);e=astForAtom(a,CHILD(b,0));if(1===NCH(b))return e;for(c=1;c<NCH(b);++c){d=CHILD(b,c);if(d.type!==SYM.trailer)break;d=astForTrailer(a,d,e);d.lineno=e.lineno;d.col_offset=e.col_offset;e=d}CHILD(b,NCH(b)-1).type===SYM.factor&&(c=astForExpr(a,CHILD(b,NCH(b)-1)),e=new BinOp(e,Pow,c,b.lineno,b.col_offset));return e}
function astForExpr(a,b){var c,d,e;a:for(;;){switch(b.type){case SYM.test:case SYM.old_test:if(CHILD(b,0).type===SYM.lambdef||CHILD(b,0).type===SYM.old_lambdef)return astForLambdef(a,CHILD(b,0));if(1<NCH(b))return astForIfexpr(a,b);case SYM.or_test:case SYM.and_test:if(1===NCH(b)){b=CHILD(b,0);continue a}d=[];for(c=0;c<NCH(b);c+=2)d[c/2]=astForExpr(a,CHILD(b,c));if("and"===CHILD(b,1).value)return new BoolOp(And,d,b.lineno,b.col_offset);goog.asserts.assert("or"===CHILD(b,1).value);return new BoolOp(Or,
d,b.lineno,b.col_offset);case SYM.not_test:if(1===NCH(b)){b=CHILD(b,0);continue a}else return new UnaryOp(Not,astForExpr(a,CHILD(b,1)),b.lineno,b.col_offset);case SYM.comparison:if(1===NCH(b)){b=CHILD(b,0);continue a}else{e=[];d=[];for(c=1;c<NCH(b);c+=2)e[(c-1)/2]=astForCompOp(a,CHILD(b,c)),d[(c-1)/2]=astForExpr(a,CHILD(b,c+1));return new Compare(astForExpr(a,CHILD(b,0)),e,d,b.lineno,b.col_offset)}case SYM.expr:case SYM.xor_expr:case SYM.and_expr:case SYM.shift_expr:case SYM.arith_expr:case SYM.term:if(1===
NCH(b)){b=CHILD(b,0);continue a}return astForBinop(a,b);case SYM.yield_expr:return c=null,2===NCH(b)&&(c=astForTestlist(a,CHILD(b,1))),new Yield(c,b.lineno,b.col_offset);case SYM.factor:if(1===NCH(b)){b=CHILD(b,0);continue a}return astForFactor(a,b);case SYM.power:return astForPower(a,b);default:goog.asserts.fail("unhandled expr","n.type: %d",b.type)}break}}
function astForPrintStmt(a,b){var c,d,e;c=1;var f=null;REQ(b,SYM.print_stmt);2<=NCH(b)&&CHILD(b,1).type===TOK.T_RIGHTSHIFT&&(f=astForExpr(a,CHILD(b,2)),c=4);e=[];for(d=0;c<NCH(b);c+=2,++d)e[d]=astForExpr(a,CHILD(b,c));c=CHILD(b,NCH(b)-1).type===TOK.T_COMMA?!1:!0;return new Print(f,e,c,b.lineno,b.col_offset)}
function astForStmt(a,b){var c;b.type===SYM.stmt&&(goog.asserts.assert(1===NCH(b)),b=CHILD(b,0));b.type===SYM.simple_stmt&&(goog.asserts.assert(1===numStmts(b)),b=CHILD(b,0));if(b.type===SYM.small_stmt)switch(REQ(b,SYM.small_stmt),b=CHILD(b,0),b.type){case SYM.expr_stmt:return astForExprStmt(a,b);case SYM.print_stmt:return astForPrintStmt(a,b);case SYM.del_stmt:return astForDelStmt(a,b);case SYM.pass_stmt:return new Pass(b.lineno,b.col_offset);case SYM.flow_stmt:return astForFlowStmt(a,b);case SYM.import_stmt:return astForImportStmt(a,
b);case SYM.global_stmt:return astForGlobalStmt(a,b);case SYM.exec_stmt:return astForExecStmt(a,b);case SYM.assert_stmt:return astForAssertStmt(a,b);case SYM.debugger_stmt:return new Debugger_(b.lineno,b.col_offset);default:goog.asserts.fail("unhandled small_stmt")}else switch(c=CHILD(b,0),REQ(b,SYM.compound_stmt),c.type){case SYM.if_stmt:return astForIfStmt(a,c);case SYM.while_stmt:return astForWhileStmt(a,c);case SYM.for_stmt:return astForForStmt(a,c);case SYM.try_stmt:return astForTryStmt(a,c);
case SYM.with_stmt:return astForWithStmt(a,c);case SYM.funcdef:return astForFuncdef(a,c,[]);case SYM.classdef:return astForClassdef(a,c,[]);case SYM.decorated:return astForDecorated(a,c);default:goog.asserts.assert("unhandled compound_stmt")}}
Sk.astFromParse=function(a,b,c){var d,e,f=new Compiling("utf-8",b,c),g=[],h=0;switch(a.type){case SYM.file_input:for(e=0;e<NCH(a)-1;++e)if(d=CHILD(a,e),a.type!==TOK.T_NEWLINE)if(REQ(d,SYM.stmt),c=numStmts(d),1===c)g[h++]=astForStmt(f,d);else for(d=CHILD(d,0),REQ(d,SYM.simple_stmt),b=0;b<c;++b)g[h++]=astForStmt(f,CHILD(d,2*b));return new Module(g);case SYM.eval_input:goog.asserts.fail("todo;");case SYM.single_input:goog.asserts.fail("todo;");default:goog.asserts.fail("todo;")}};
Sk.astDump=function(a){var b=function(a){var b,c="";for(b=0;b<a;++b)c+=" ";return c},c=function(a,e){var f,g,h,k,l,m;if(null===a)return e+"None";if(a.prototype&&void 0!==a.prototype._astname&&a.prototype._isenum)return e+a.prototype._astname+"()";if(void 0!==a._astname){h=b(a._astname.length+1);g=[];for(f=0;f<a._fields.length;f+=2)m=a._fields[f],l=a._fields[f+1](a),k=b(m.length+1),g.push([m,c(l,e+h+k)]);l=[];for(f=0;f<g.length;++f)k=g[f],l.push(k[0]+"="+k[1].replace(/^\s+/,""));f=l.join(",\n"+e+h);
return e+a._astname+"("+f+")"}if(goog.isArrayLike(a)){h=[];for(f=0;f<a.length;++f)g=a[f],h.push(c(g,e+" "));f=h.join(",\n");return e+"["+f.replace(/^\s+/,"")+"]"}f=!0===a?"True":!1===a?"False":a instanceof Sk.builtin.lng?a.tp$str().v:a instanceof Sk.builtin.str?a.$r().v:""+a;return e+f};return c(a,"")};goog.exportSymbol("Sk.astFromParse",Sk.astFromParse);goog.exportSymbol("Sk.astDump",Sk.astDump);var DEF_GLOBAL=1,DEF_LOCAL=2,DEF_PARAM=4,USE=8,DEF_STAR=16,DEF_DOUBLESTAR=32,DEF_INTUPLE=64,DEF_FREE=128,DEF_FREE_GLOBAL=256,DEF_FREE_CLASS=512,DEF_IMPORT=1024,DEF_BOUND=DEF_LOCAL|DEF_PARAM|DEF_IMPORT,SCOPE_OFF=11,SCOPE_MASK=7,LOCAL=1,GLOBAL_EXPLICIT=2,GLOBAL_IMPLICIT=3,FREE=4,CELL=5,OPT_IMPORT_STAR=1,OPT_EXEC=2,OPT_BARE_EXEC=4,OPT_TOPLEVEL=8,GENERATOR=2,GENERATOR_EXPRESSION=2,ModuleBlock="module",FunctionBlock="function",ClassBlock="class";
function Symbol(a,b,c){this.__name=a;this.__flags=b;this.__scope=b>>SCOPE_OFF&SCOPE_MASK;this.__namespaces=c||[]}Symbol.prototype.get_name=function(){return this.__name};Symbol.prototype.is_referenced=function(){return!!(this.__flags&USE)};Symbol.prototype.is_parameter=function(){return!!(this.__flags&DEF_PARAM)};Symbol.prototype.is_global=function(){return this.__scope===GLOBAL_IMPLICIT||this.__scope==GLOBAL_EXPLICIT};Symbol.prototype.is_declared_global=function(){return this.__scope==GLOBAL_EXPLICIT};
Symbol.prototype.is_local=function(){return!!(this.__flags&DEF_BOUND)};Symbol.prototype.is_free=function(){return this.__scope==FREE};Symbol.prototype.is_imported=function(){return!!(this.__flags&DEF_IMPORT)};Symbol.prototype.is_assigned=function(){return!!(this.__flags&DEF_LOCAL)};Symbol.prototype.is_namespace=function(){return this.__namespaces&&0<this.__namespaces.length};Symbol.prototype.get_namespaces=function(){return this.__namespaces};var astScopeCounter=0;
function SymbolTableScope(a,b,c,d,e){this.symFlags={};this.name=b;this.varnames=[];this.children=[];this.blockType=c;this.returnsValue=this.varkeywords=this.varargs=this.generator=this.childHasFree=this.hasFree=this.isNested=!1;this.lineno=e;this.table=a;a.cur&&(a.cur.nested||a.cur.blockType===FunctionBlock)&&(this.isNested=!0);d.scopeId=astScopeCounter++;a.stss[d.scopeId]=this;this.symbols={}}SymbolTableScope.prototype.get_type=function(){return this.blockType};
SymbolTableScope.prototype.get_name=function(){return this.name};SymbolTableScope.prototype.get_lineno=function(){return this.lineno};SymbolTableScope.prototype.is_nested=function(){return this.isNested};SymbolTableScope.prototype.has_children=function(){return 0<this.children.length};SymbolTableScope.prototype.get_identifiers=function(){return this._identsMatching(function(){return!0})};
SymbolTableScope.prototype.lookup=function(a){var b,c;this.symbols.hasOwnProperty(a)?a=this.symbols[a]:(c=this.symFlags[a],b=this.__check_children(a),a=this.symbols[a]=new Symbol(a,c,b));return a};SymbolTableScope.prototype.__check_children=function(a){var b,c,d=[];for(c=0;c<this.children.length;++c)b=this.children[c],b.name===a&&d.push(b);return d};
SymbolTableScope.prototype._identsMatching=function(a){var b,c=[];for(b in this.symFlags)this.symFlags.hasOwnProperty(b)&&a(this.symFlags[b])&&c.push(b);c.sort();return c};SymbolTableScope.prototype.get_parameters=function(){goog.asserts.assert("function"==this.get_type(),"get_parameters only valid for function scopes");this._funcParams||(this._funcParams=this._identsMatching(function(a){return a&DEF_PARAM}));return this._funcParams};
SymbolTableScope.prototype.get_locals=function(){goog.asserts.assert("function"==this.get_type(),"get_locals only valid for function scopes");this._funcLocals||(this._funcLocals=this._identsMatching(function(a){return a&DEF_BOUND}));return this._funcLocals};
SymbolTableScope.prototype.get_globals=function(){goog.asserts.assert("function"==this.get_type(),"get_globals only valid for function scopes");this._funcGlobals||(this._funcGlobals=this._identsMatching(function(a){a=a>>SCOPE_OFF&SCOPE_MASK;return a==GLOBAL_IMPLICIT||a==GLOBAL_EXPLICIT}));return this._funcGlobals};
SymbolTableScope.prototype.get_frees=function(){goog.asserts.assert("function"==this.get_type(),"get_frees only valid for function scopes");this._funcFrees||(this._funcFrees=this._identsMatching(function(a){return(a>>SCOPE_OFF&SCOPE_MASK)==FREE}));return this._funcFrees};
SymbolTableScope.prototype.get_methods=function(){var a,b;goog.asserts.assert("class"==this.get_type(),"get_methods only valid for class scopes");if(!this._classMethods){b=[];for(a=0;a<this.children.length;++a)b.push(this.children[a].name);b.sort();this._classMethods=b}return this._classMethods};SymbolTableScope.prototype.getScope=function(a){a=this.symFlags[a];return void 0===a?0:a>>SCOPE_OFF&SCOPE_MASK};
function SymbolTable(a){this.filename=a;this.top=this.cur=null;this.stack=[];this.curClass=this.global=null;this.tmpname=0;this.stss={}}SymbolTable.prototype.getStsForAst=function(a){goog.asserts.assert(void 0!==a.scopeId,"ast wasn't added to st?");a=this.stss[a.scopeId];goog.asserts.assert(void 0!==a,"unknown sym tab entry");return a};
SymbolTable.prototype.SEQStmt=function(a){var b,c,d;goog.asserts.assert(goog.isArrayLike(a),"SEQ: nodes isn't array? got %s",a);d=a.length;for(c=0;c<d;++c)(b=a[c])&&this.visitStmt(b)};SymbolTable.prototype.SEQExpr=function(a){var b,c,d;goog.asserts.assert(goog.isArrayLike(a),"SEQ: nodes isn't array? got %s",a);d=a.length;for(c=0;c<d;++c)(b=a[c])&&this.visitExpr(b)};
SymbolTable.prototype.enterBlock=function(a,b,c,d){var e;a=fixReservedNames(a);e=null;this.cur&&(e=this.cur,this.stack.push(this.cur));this.cur=new SymbolTableScope(this,a,b,c,d);"top"===a&&(this.global=this.cur.symFlags);e&&e.children.push(this.cur)};SymbolTable.prototype.exitBlock=function(){this.cur=null;0<this.stack.length&&(this.cur=this.stack.pop())};
SymbolTable.prototype.visitParams=function(a,b){var c,d;for(d=0;d<a.length;++d)if(c=a[d],c.constructor===Name)goog.asserts.assert(c.ctx===Param||c.ctx===Store&&!b),this.addDef(c.id,DEF_PARAM,c.lineno);else throw new Sk.builtin.SyntaxError("invalid expression in parameter list",this.filename);};
SymbolTable.prototype.visitArguments=function(a,b){a.args&&this.visitParams(a.args,!0);a.vararg&&(this.addDef(a.vararg,DEF_PARAM,b),this.cur.varargs=!0);a.kwarg&&(this.addDef(a.kwarg,DEF_PARAM,b),this.cur.varkeywords=!0)};SymbolTable.prototype.newTmpname=function(a){this.addDef(new Sk.builtin.str("_["+ ++this.tmpname+"]"),DEF_LOCAL,a)};
SymbolTable.prototype.addDef=function(a,b,c){var d,e=mangleName(this.curClass,new Sk.builtin.str(a)).v,e=fixReservedNames(e);d=this.cur.symFlags[e];if(void 0!==d){if(b&DEF_PARAM&&d&DEF_PARAM)throw new Sk.builtin.SyntaxError("duplicate argument '"+a.v+"' in function definition",this.filename,c);d|=b}else d=b;this.cur.symFlags[e]=d;b&DEF_PARAM?this.cur.varnames.push(e):b&DEF_GLOBAL&&(d=b,a=this.global[e],void 0!==a&&(d|=a),this.global[e]=d)};
SymbolTable.prototype.visitSlice=function(a){var b;switch(a.constructor){case Slice:a.lower&&this.visitExpr(a.lower);a.upper&&this.visitExpr(a.upper);a.step&&this.visitExpr(a.step);break;case ExtSlice:for(b=0;b<a.dims.length;++b)this.visitSlice(a.dims[b]);break;case Index:this.visitExpr(a.value)}};
SymbolTable.prototype.visitStmt=function(a){var b,c,d,e;goog.asserts.assert(void 0!==a,"visitStmt called with undefined");switch(a.constructor){case FunctionDef:this.addDef(a.name,DEF_LOCAL,a.lineno);a.args.defaults&&this.SEQExpr(a.args.defaults);a.decorator_list&&this.SEQExpr(a.decorator_list);this.enterBlock(a.name.v,FunctionBlock,a,a.lineno);this.visitArguments(a.args,a.lineno);this.SEQStmt(a.body);this.exitBlock();break;case ClassDef:this.addDef(a.name,DEF_LOCAL,a.lineno);this.SEQExpr(a.bases);
a.decorator_list&&this.SEQExpr(a.decorator_list);this.enterBlock(a.name.v,ClassBlock,a,a.lineno);this.curClass=a.name;this.SEQStmt(a.body);this.exitBlock();break;case Return_:if(a.value&&(this.visitExpr(a.value),this.cur.returnsValue=!0,this.cur.generator))throw new Sk.builtin.SyntaxError("'return' with argument inside generator",this.filename);break;case Delete_:this.SEQExpr(a.targets);break;case Assign:this.SEQExpr(a.targets);this.visitExpr(a.value);break;case AugAssign:this.visitExpr(a.target);
this.visitExpr(a.value);break;case Print:a.dest&&this.visitExpr(a.dest);this.SEQExpr(a.values);break;case For_:this.visitExpr(a.target);this.visitExpr(a.iter);this.SEQStmt(a.body);a.orelse&&this.SEQStmt(a.orelse);break;case While_:this.visitExpr(a.test);this.SEQStmt(a.body);a.orelse&&this.SEQStmt(a.orelse);break;case If_:this.visitExpr(a.test);this.SEQStmt(a.body);a.orelse&&this.SEQStmt(a.orelse);break;case Raise:a.type&&(this.visitExpr(a.type),a.inst&&(this.visitExpr(a.inst),a.tback&&this.visitExpr(a.tback)));
break;case TryExcept:this.SEQStmt(a.body);this.SEQStmt(a.orelse);this.visitExcepthandlers(a.handlers);break;case TryFinally:this.SEQStmt(a.body);this.SEQStmt(a.finalbody);break;case Assert:this.visitExpr(a.test);a.msg&&this.visitExpr(a.msg);break;case Import_:case ImportFrom:this.visitAlias(a.names,a.lineno);break;case Exec:this.visitExpr(a.body);a.globals&&(this.visitExpr(a.globals),a.locals&&this.visitExpr(a.locals));break;case Global:e=a.names.length;for(d=0;d<e;++d){c=mangleName(this.curClass,
a.names[d]).v;c=fixReservedNames(c);b=this.cur.symFlags[c];if(b&(DEF_LOCAL|USE)){if(b&DEF_LOCAL)throw new Sk.builtin.SyntaxError("name '"+c+"' is assigned to before global declaration",this.filename,a.lineno);throw new Sk.builtin.SyntaxError("name '"+c+"' is used prior to global declaration",this.filename,a.lineno);}this.addDef(new Sk.builtin.str(c),DEF_GLOBAL,a.lineno)}break;case Expr:this.visitExpr(a.value);break;case Pass:case Break_:case Debugger_:case Continue_:break;case With_:this.newTmpname(a.lineno);
this.visitExpr(a.context_expr);a.optional_vars&&(this.newTmpname(a.lineno),this.visitExpr(a.optional_vars));this.SEQStmt(a.body);break;default:goog.asserts.fail("Unhandled type "+a.constructor.name+" in visitStmt")}};
SymbolTable.prototype.visitExpr=function(a){var b;goog.asserts.assert(void 0!==a,"visitExpr called with undefined");switch(a.constructor){case BoolOp:this.SEQExpr(a.values);break;case BinOp:this.visitExpr(a.left);this.visitExpr(a.right);break;case UnaryOp:this.visitExpr(a.operand);break;case Lambda:this.addDef(new Sk.builtin.str("lambda"),DEF_LOCAL,a.lineno);a.args.defaults&&this.SEQExpr(a.args.defaults);this.enterBlock("lambda",FunctionBlock,a,a.lineno);this.visitArguments(a.args,a.lineno);this.visitExpr(a.body);
this.exitBlock();break;case IfExp:this.visitExpr(a.test);this.visitExpr(a.body);this.visitExpr(a.orelse);break;case Dict:this.SEQExpr(a.keys);this.SEQExpr(a.values);break;case DictComp:case SetComp:this.visitComprehension(a.generators,0);break;case ListComp:this.newTmpname(a.lineno);this.visitExpr(a.elt);this.visitComprehension(a.generators,0);break;case GeneratorExp:this.visitGenexp(a);break;case Yield:a.value&&this.visitExpr(a.value);this.cur.generator=!0;if(this.cur.returnsValue)throw new Sk.builtin.SyntaxError("'return' with argument inside generator",
this.filename);break;case Compare:this.visitExpr(a.left);this.SEQExpr(a.comparators);break;case Call:this.visitExpr(a.func);this.SEQExpr(a.args);for(b=0;b<a.keywords.length;++b)this.visitExpr(a.keywords[b].value);a.starargs&&this.visitExpr(a.starargs);a.kwargs&&this.visitExpr(a.kwargs);break;case Num:case Str:break;case Attribute:this.visitExpr(a.value);break;case Subscript:this.visitExpr(a.value);this.visitSlice(a.slice);break;case Name:this.addDef(a.id,a.ctx===Load?USE:DEF_LOCAL,a.lineno);break;
case List:case Tuple:case Set:this.SEQExpr(a.elts);break;default:goog.asserts.fail("Unhandled type "+a.constructor.name+" in visitExpr")}};SymbolTable.prototype.visitComprehension=function(a,b){var c,d,e=a.length;for(d=b;d<e;++d)c=a[d],this.visitExpr(c.target),this.visitExpr(c.iter),this.SEQExpr(c.ifs)};
SymbolTable.prototype.visitAlias=function(a,b){var c,d,e,f;for(f=0;f<a.length;++f)if(c=a[f],d=e=null===c.asname?c.name.v:c.asname.v,c=e.indexOf("."),-1!==c&&(d=e.substr(0,c)),"*"!==e)this.addDef(new Sk.builtin.str(d),DEF_IMPORT,b);else if(this.cur.blockType!==ModuleBlock)throw new Sk.builtin.SyntaxError("import * only allowed at module level",this.filename);};
SymbolTable.prototype.visitGenexp=function(a){var b=a.generators[0];this.visitExpr(b.iter);this.enterBlock("genexpr",FunctionBlock,a,a.lineno);this.cur.generator=!0;this.addDef(new Sk.builtin.str(".0"),DEF_PARAM,a.lineno);this.visitExpr(b.target);this.SEQExpr(b.ifs);this.visitComprehension(a.generators,1);this.visitExpr(a.elt);this.exitBlock()};SymbolTable.prototype.visitExcepthandlers=function(a){var b,c;for(b=0;c=a[b];++b)c.type&&this.visitExpr(c.type),c.name&&this.visitExpr(c.name),this.SEQStmt(c.body)};
function _dictUpdate(a,b){for(var c in b)a[c]=b[c]}
SymbolTable.prototype.analyzeBlock=function(a,b,c,d){var e,f,g;g={};var h={},k={},l={},m={};a.blockType==ClassBlock&&(_dictUpdate(k,d),b&&_dictUpdate(l,b));for(f in a.symFlags)e=a.symFlags[f],this.analyzeName(a,h,f,e,b,g,c,d);a.blockType!==ClassBlock&&(a.blockType===FunctionBlock&&_dictUpdate(l,g),b&&_dictUpdate(l,b),_dictUpdate(k,d));g={};f=a.children.length;for(e=0;e<f;++e)if(d=a.children[e],this.analyzeChildBlock(d,l,m,k,g),d.hasFree||d.childHasFree)a.childHasFree=!0;_dictUpdate(m,g);a.blockType===
FunctionBlock&&this.analyzeCells(h,m);this.updateSymbols(a.symFlags,h,b,m,a.blockType===ClassBlock);_dictUpdate(c,m)};SymbolTable.prototype.analyzeChildBlock=function(a,b,c,d,e){var f={};_dictUpdate(f,b);b={};_dictUpdate(b,c);c={};_dictUpdate(c,d);this.analyzeBlock(a,f,b,c);_dictUpdate(e,b)};SymbolTable.prototype.analyzeCells=function(a,b){var c,d;for(d in a)c=a[d],c===LOCAL&&void 0!==b[d]&&(a[d]=CELL,delete b[d])};
SymbolTable.prototype.updateSymbols=function(a,b,c,d,e){var f,g,h;for(h in a)g=a[h],f=b[h],g|=f<<SCOPE_OFF,a[h]=g;b=FREE<<SCOPE_OFF;for(h in d)d=a[h],void 0!==d?e&&d&(DEF_BOUND|DEF_GLOBAL)&&(d|=DEF_FREE_CLASS,a[h]=d):void 0!==c[h]&&(a[h]=b)};
SymbolTable.prototype.analyzeName=function(a,b,c,d,e,f,g,h){if(d&DEF_GLOBAL){if(d&DEF_PARAM)throw new Sk.builtin.SyntaxError("name '"+c+"' is local and global",this.filename,a.lineno);b[c]=GLOBAL_EXPLICIT;h[c]=null;e&&void 0!==e[c]&&delete e[c]}else d&DEF_BOUND?(b[c]=LOCAL,f[c]=null,delete h[c]):e&&void 0!==e[c]?(b[c]=FREE,a.hasFree=!0,g[c]=null):(h&&void 0!==h[c]||!a.isNested||(a.hasFree=!0),b[c]=GLOBAL_IMPLICIT)};SymbolTable.prototype.analyze=function(){this.analyzeBlock(this.top,null,{},{})};
Sk.symboltable=function(a,b){var c,d=new SymbolTable(b);d.enterBlock("top",ModuleBlock,a,0);d.top=d.cur;for(c=0;c<a.body.length;++c)d.visitStmt(a.body[c]);d.exitBlock();d.analyze();return d};
Sk.dumpSymtab=function(a){var b=function(a){return a?"True":"False"},c=function(a){var b,c=[];for(b=0;b<a.length;++b)c.push((new Sk.builtin.str(a[b])).$r().v);return"["+c.join(", ")+"]"},d=function(a,f){var g,h,k,l,m,q,n,r,p;void 0===f&&(f="");p=""+(f+"Sym_type: "+a.get_type()+"\n");p+=f+"Sym_name: "+a.get_name()+"\n";p+=f+"Sym_lineno: "+a.get_lineno()+"\n";p+=f+"Sym_nested: "+b(a.is_nested())+"\n";p+=f+"Sym_haschildren: "+b(a.has_children())+"\n";"class"===a.get_type()?p+=f+"Class_methods: "+c(a.get_methods())+
"\n":"function"===a.get_type()&&(p+=f+"Func_params: "+c(a.get_parameters())+"\n",p+=f+"Func_locals: "+c(a.get_locals())+"\n",p+=f+"Func_globals: "+c(a.get_globals())+"\n",p+=f+"Func_frees: "+c(a.get_frees())+"\n");p+=f+"-- Identifiers --\n";r=a.get_identifiers();n=r.length;for(q=0;q<n;++q){g=a.lookup(r[q]);p+=f+"name: "+g.get_name()+"\n";p+=f+" is_referenced: "+b(g.is_referenced())+"\n";p+=f+" is_imported: "+b(g.is_imported())+"\n";p+=f+" is_parameter: "+b(g.is_parameter())+"\n";p+=f+" is_global: "+
b(g.is_global())+"\n";p+=f+" is_declared_global: "+b(g.is_declared_global())+"\n";p+=f+" is_local: "+b(g.is_local())+"\n";p+=f+" is_free: "+b(g.is_free())+"\n";p+=f+" is_assigned: "+b(g.is_assigned())+"\n";p+=f+" is_namespace: "+b(g.is_namespace())+"\n";m=g.get_namespaces();l=m.length;p+=f+" namespaces: [\n";k=[];for(h=0;h<l;++h)g=m[h],k.push(d(g,f+" "));p+=k.join("\n");p+=f+" ]\n"}return p};return d(a.top,"")};goog.exportSymbol("Sk.symboltable",Sk.symboltable);
goog.exportSymbol("Sk.dumpSymtab",Sk.dumpSymtab);var out;Sk.gensymcount=0;function Compiler(a,b,c,d,e){this.filename=a;this.st=b;this.flags=c;this.canSuspend=d;this.interactive=!1;this.nestlevel=0;this.u=null;this.stack=[];this.result=[];this.allUnits=[];this.source=e?e.split("\n"):!1}
function CompilerUnit(){this.name=this.ste=null;this.doesSuspend=this.canSuspend=!1;this.private_=null;this.lineno=this.firstlineno=0;this.linenoSet=!1;this.localnames=[];this.localtemps=[];this.tempsToSave=[];this.blocknum=0;this.blocks=[];this.curblock=0;this.scopename=null;this.suffixCode=this.switchCode=this.varDeclsCode=this.prefixCode="";this.breakBlocks=[];this.continueBlocks=[];this.exceptBlocks=[];this.finallyBlocks=[]}
CompilerUnit.prototype.activateScope=function(){var a=this;out=function(){var b,c=a.blocks[a.curblock];if(null===c._next)for(b=0;b<arguments.length;++b)c.push(arguments[b])}};Compiler.prototype.getSourceLine=function(a){goog.asserts.assert(this.source);return this.source[a-1]};
Compiler.prototype.annotateSource=function(a){var b,c;if(this.source){c=a.lineno;b=a.col_offset;out("\n//\n// line ",c,":\n// ",this.getSourceLine(c),"\n// ");for(a=0;a<b;++a)out(" ");out("^\n//\n");out("currLineNo = ",c,";\ncurrColNo = ",b,";\n\n")}};Compiler.prototype.gensym=function(a){a="$"+(a||"");return a+=Sk.gensymcount++};Compiler.prototype.niceName=function(a){return this.gensym(a.replace("<","").replace(">","").replace(" ","_"))};
var reservedWords_={"abstract":!0,as:!0,"boolean":!0,"break":!0,"byte":!0,"case":!0,"catch":!0,"char":!0,"class":!0,"continue":!0,"const":!0,"debugger":!0,"default":!0,"delete":!0,"do":!0,"double":!0,"else":!0,"enum":!0,"export":!0,"extends":!0,"false":!0,"final":!0,"finally":!0,"float":!0,"for":!0,"function":!0,"goto":!0,"if":!0,"implements":!0,"import":!0,"in":!0,"instanceof":!0,"int":!0,"interface":!0,is:!0,"long":!0,namespace:!0,"native":!0,"new":!0,"null":!0,"package":!0,"private":!0,"protected":!0,
"public":!0,"return":!0,"short":!0,"static":!0,"super":!1,"switch":!0,"synchronized":!0,"this":!0,"throw":!0,"throws":!0,"transient":!0,"true":!0,"try":!0,"typeof":!0,use:!0,"var":!0,"void":!0,"volatile":!0,"while":!0,"with":!0};function fixReservedWords(a){return!0!==reservedWords_[a]?a:a+"_$rw$"}
var reservedNames_={__defineGetter__:!0,__defineSetter__:!0,apply:!0,call:!0,eval:!0,hasOwnProperty:!0,isPrototypeOf:!0,__lookupGetter__:!0,__lookupSetter__:!0,__noSuchMethod__:!0,propertyIsEnumerable:!0,toSource:!0,toLocaleString:!0,toString:!0,unwatch:!0,valueOf:!0,watch:!0,length:!0};function fixReservedNames(a){return reservedNames_[a]?a+"_$rn$":a}
function mangleName(a,b){var c=b.v,d=null;if(null===a||(null===c||"_"!==c.charAt(0)||"_"!==c.charAt(1))||"_"===c.charAt(c.length-1)&&"_"===c.charAt(c.length-2))return b;d=a.v;d.replace(/_/g,"");if(""===d)return b;d=a.v;d.replace(/^_*/,"");return d=new Sk.builtin.str("_"+d+c)}Compiler.prototype._gr=function(a,b){var c,d=this.gensym(a);this.u.localtemps.push(d);out("var ",d,"=");for(c=1;c<arguments.length;++c)out(arguments[c]);out(";");return d};
Compiler.prototype.outputInterruptTest=function(){var a="";if(null!==Sk.execLimit||null!==Sk.yieldLimit&&this.u.canSuspend)a+="var $dateNow = Date.now();",null!==Sk.execLimit&&(a+="if ($dateNow - Sk.execStart > Sk.execLimit) {throw new Sk.builtin.TimeLimitError(Sk.timeoutMsg())}"),null!==Sk.yieldLimit&&this.u.canSuspend&&(a=a+"if ($dateNow - Sk.lastYield > Sk.yieldLimit) {"+("var $susp = $saveSuspension({data: {type: 'Sk.yield'}, resume: function() {}}, '"+this.filename+"',currLineNo,currColNo);"),
a+="$susp.$blk = $blk;",a+="$susp.optional = true;",a+="return $susp;",a+="}",this.u.doesSuspend=!0);return a};Compiler.prototype._jumpfalse=function(a,b){var c=this._gr("jfalse","(",a,"===false||!Sk.misceval.isTrue(",a,"))");out("if(",c,"){/*test failed */$blk=",b,";continue;}")};Compiler.prototype._jumpundef=function(a,b){out("if(",a,"===undefined){$blk=",b,";continue;}")};
Compiler.prototype._jumptrue=function(a,b){var c=this._gr("jtrue","(",a,"===true||Sk.misceval.isTrue(",a,"))");out("if(",c,"){/*test passed */$blk=",b,";continue;}")};Compiler.prototype._jump=function(a){null===this.u.blocks[this.u.curblock]._next&&(out("$blk=",a,";"),this.u.blocks[this.u.curblock]._next=a)};
Compiler.prototype._checkSuspension=function(a){var b;this.u.canSuspend?(b=this.newBlock("function return or resume suspension"),this._jump(b),this.setBlock(b),a=a||{lineno:"currLineNo",col_offset:"currColNo"},out("if ($ret && $ret.isSuspension) { return $saveSuspension($ret,'"+this.filename+"',"+a.lineno+","+a.col_offset+"); }"),this.u.doesSuspend=!0,this.u.tempsToSave=this.u.tempsToSave.concat(this.u.localtemps)):out("if ($ret && $ret.isSuspension) { $ret = Sk.misceval.retryOptionalSuspensionOrThrow($ret); }")};
Compiler.prototype.ctuplelistorset=function(a,b,c){var d;goog.asserts.assert("tuple"===c||"list"===c||"set"===c);if(a.ctx===Store)for(d=this._gr("items","Sk.abstr.sequenceUnpack("+b+","+a.elts.length+")"),b=0;b<a.elts.length;++b)this.vexpr(a.elts[b],d+"["+b+"]");else if(a.ctx===Load||"set"===c){d=[];for(b=0;b<a.elts.length;++b)d.push(this._gr("elem",this.vexpr(a.elts[b])));return this._gr("load"+c,"new Sk.builtins['",c,"']([",d,"])")}};
Compiler.prototype.cdict=function(a){var b,c,d;goog.asserts.assert(a.values.length===a.keys.length);d=[];for(c=0;c<a.values.length;++c)b=this.vexpr(a.values[c]),d.push(this.vexpr(a.keys[c])),d.push(b);return this._gr("loaddict","new Sk.builtins['dict']([",d,"])")};Compiler.prototype.clistcomp=function(a){goog.asserts.assert(a instanceof ListComp);var b=this._gr("_compr","new Sk.builtins['list']([])");return this.ccompgen("list",b,a.generators,0,a.elt,null,a)};
Compiler.prototype.cdictcomp=function(a){goog.asserts.assert(a instanceof DictComp);var b=this._gr("_dcompr","new Sk.builtins.dict([])");return this.ccompgen("dict",b,a.generators,0,a.value,a.key,a)};Compiler.prototype.csetcomp=function(a){goog.asserts.assert(a instanceof SetComp);var b=this._gr("_setcompr","new Sk.builtins.set([])");return this.ccompgen("set",b,a.generators,0,a.elt,null,a)};
Compiler.prototype.ccompgen=function(a,b,c,d,e,f,g){var h=this.newBlock(a+" comp start"),k=this.newBlock(a+" comp skip"),l=this.newBlock(a+" comp anchor"),m=c[d],q=this.vexpr(m.iter),q=this._gr("iter","Sk.abstr.iter(",q,")"),n,r;this._jump(h);this.setBlock(h);out("$ret = Sk.abstr.iternext(",q,", true);");this._checkSuspension(g);q=this._gr("next","$ret");this._jumpundef(q,l);this.vexpr(m.target,q);r=m.ifs.length;for(n=0;n<r;++n)q=this.vexpr(m.ifs[n]),this._jumpfalse(q,h);++d<c.length&&this.ccompgen(a,
b,c,d,e,f,g);d>=c.length&&(c=this.vexpr(e),"dict"===a?(a=this.vexpr(f),out(b,".mp$ass_subscript(",a,",",c,");")):"list"===a?out(b,".v.push(",c,");"):"set"===a&&out(b,".v.mp$ass_subscript(",c,", true);"),this._jump(k),this.setBlock(k));this._jump(h);this.setBlock(l);return b};
Compiler.prototype.cyield=function(a){if(this.u.ste.blockType!==FunctionBlock)throw new SyntaxError("'yield' outside function");var b="null";a.value&&(b=this.vexpr(a.value));a=this.newBlock("after yield");out("return [/*resume*/",a,",/*ret*/",b,"];");this.setBlock(a);return"$gen.gi$sentvalue"};
Compiler.prototype.ccompare=function(a){var b,c,d,e,f,g;goog.asserts.assert(a.ops.length===a.comparators.length);b=this.vexpr(a.left);g=a.ops.length;f=this.newBlock("done");e=this._gr("compareres","null");for(d=0;d<g;++d)c=this.vexpr(a.comparators[d]),b=this._gr("compare","Sk.builtin.bool(Sk.misceval.richCompareBool(",b,",",c,",'",a.ops[d].prototype._astname,"'))"),out(e,"=",b,";"),this._jumpfalse(b,f),b=c;this._jump(f);this.setBlock(f);return e};
Compiler.prototype.ccall=function(a){var b,c,d,e=this.vexpr(a.func),f=this.vseqexpr(a.args);if(0<a.keywords.length||a.starargs||a.kwargs){c=[];for(b=0;b<a.keywords.length;++b)c.push("'"+a.keywords[b].arg.v+"'"),c.push(this.vexpr(a.keywords[b].value));d="["+c.join(",")+"]";b=c="undefined";a.starargs&&(c=this.vexpr(a.starargs));a.kwargs&&(b=this.vexpr(a.kwargs));out("$ret;");out("$ret = Sk.misceval.callOrSuspend(",e,",",b,",",c,",",d,0<f.length?",":"",f,");")}else out("$ret;"),out("$ret = Sk.misceval.callsimOrSuspend(",
e,0<f.length?",":"",f,");");this._checkSuspension(a);return this._gr("call","$ret")};Compiler.prototype.cslice=function(a){var b,c;goog.asserts.assert(a instanceof Slice);c=a.lower?this.vexpr(a.lower):a.step?"Sk.builtin.none.none$":"new Sk.builtin.int_(0)";b=a.upper?this.vexpr(a.upper):a.step?"Sk.builtin.none.none$":"new Sk.builtin.int_(2147483647)";a=a.step?this.vexpr(a.step):"Sk.builtin.none.none$";return this._gr("slice","new Sk.builtins['slice'](",c,",",b,",",a,")")};
Compiler.prototype.eslice=function(a){var b,c;goog.asserts.assert(a instanceof Array);c=[];for(b=0;b<a.length;b++)c.push(this.vslicesub(a[b]));return this._gr("extslice","new Sk.builtins['tuple']([",c,"])")};Compiler.prototype.vslicesub=function(a){var b;switch(a.constructor){case Index:b=this.vexpr(a.value);break;case Slice:b=this.cslice(a);break;case Ellipsis:goog.asserts.fail("todo compile.js Ellipsis;");break;case ExtSlice:b=this.eslice(a.dims);break;default:goog.asserts.fail("invalid subscript kind")}return b};
Compiler.prototype.vslice=function(a,b,c,d){a=this.vslicesub(a);return this.chandlesubscr(b,c,a,d)};Compiler.prototype.chandlesubscr=function(a,b,c,d){if(a===Load||a===AugLoad)return out("$ret = Sk.abstr.objectGetItem(",b,",",c,", true);"),this._checkSuspension(),this._gr("lsubscr","$ret");a===Store||a===AugStore?(out("$ret = Sk.abstr.objectSetItem(",b,",",c,",",d,", true);"),this._checkSuspension()):a===Del?out("Sk.abstr.objectDelItem(",b,",",c,");"):goog.asserts.fail("handlesubscr fail")};
Compiler.prototype.cboolop=function(a){var b,c,d,e,f,g;goog.asserts.assert(a instanceof BoolOp);g=a.op===And?this._jumpfalse:this._jumptrue;f=this.newBlock("end of boolop");e=a.values;d=e.length;for(b=0;b<d;++b)a=this.vexpr(e[b]),0===b&&(c=this._gr("boolopsucc",a)),out(c,"=",a,";"),g.call(this,a,f);this._jump(f);this.setBlock(f);return c};
Compiler.prototype.vexpr=function(a,b,c,d){var e;a.lineno>this.u.lineno&&(this.u.lineno=a.lineno,this.u.linenoSet=!1);switch(a.constructor){case BoolOp:return this.cboolop(a);case BinOp:return this._gr("binop","Sk.abstr.numberBinOp(",this.vexpr(a.left),",",this.vexpr(a.right),",'",a.op.prototype._astname,"')");case UnaryOp:return this._gr("unaryop","Sk.abstr.numberUnaryOp(",this.vexpr(a.operand),",'",a.op.prototype._astname,"')");case Lambda:return this.clambda(a);case IfExp:return this.cifexp(a);
case Dict:return this.cdict(a);case ListComp:return this.clistcomp(a);case DictComp:return this.cdictcomp(a);case SetComp:return this.csetcomp(a);case GeneratorExp:return this.cgenexp(a);case Yield:return this.cyield(a);case Compare:return this.ccompare(a);case Call:return b=this.ccall(a),this.annotateSource(a),b;case Num:if("number"===typeof a.n)return a.n;if(a.n instanceof Sk.builtin.int_)return"new Sk.builtin.int_("+a.n.v+")";if(a.n instanceof Sk.builtin.float_)return a=0===a.n.v&&-Infinity===
1/a.n.v?"-0":a.n.v,"new Sk.builtin.float_("+a+")";if(a.n instanceof Sk.builtin.lng)return"Sk.longFromStr('"+a.n.tp$str().v+"')";if(a.n instanceof Sk.builtin.complex)return"new Sk.builtin.complex(new Sk.builtin.float_("+(0===a.n.real.v&&-Infinity===1/a.n.real.v?"-0":a.n.real.v)+"), new Sk.builtin.float_("+(0===a.n.imag.v&&-Infinity===1/a.n.imag.v?"-0":a.n.imag.v)+"))";goog.asserts.fail("unhandled Num type");case Str:return this._gr("str","new Sk.builtins['str'](",a.s.$r().v,")");case Attribute:a.ctx!==
AugLoad&&a.ctx!==AugStore&&(e=this.vexpr(a.value));d=a.attr.$r().v;d=d.substring(1,d.length-1);d=mangleName(this.u.private_,new Sk.builtin.str(d)).v;d=fixReservedWords(d);d=fixReservedNames(d);switch(a.ctx){case AugLoad:return out("$ret = Sk.abstr.gattr(",c,",'",d,"', true);"),this._checkSuspension(a),this._gr("lattr","$ret");case Load:return out("$ret = Sk.abstr.gattr(",e,",'",d,"', true);"),this._checkSuspension(a),this._gr("lattr","$ret");case AugStore:out("$ret = undefined;");out("if(",b,"!==undefined){");
out("$ret = Sk.abstr.sattr(",c,",'",d,"',",b,", true);");out("}");this._checkSuspension(a);break;case Store:out("$ret = Sk.abstr.sattr(",e,",'",d,"',",b,", true);");this._checkSuspension(a);break;case Del:goog.asserts.fail("todo Del;");break;default:goog.asserts.fail("invalid attribute expression")}break;case Subscript:switch(a.ctx){case AugLoad:return out("$ret = Sk.abstr.objectGetItem(",c,",",d,", true);"),this._checkSuspension(a),this._gr("gitem","$ret");case Load:case Store:case Del:return this.vslice(a.slice,
a.ctx,this.vexpr(a.value),b);case AugStore:out("$ret=undefined;");out("if(",b,"!==undefined){");out("$ret=Sk.abstr.objectSetItem(",c,",",d,",",b,", true)");out("}");this._checkSuspension(a);break;default:goog.asserts.fail("invalid subscript expression")}break;case Name:return this.nameop(a.id,a.ctx,b);case List:return this.ctuplelistorset(a,b,"list");case Tuple:return this.ctuplelistorset(a,b,"tuple");case Set:return this.ctuplelistorset(a,b,"set");default:goog.asserts.fail("unhandled case in vexpr")}};
Compiler.prototype.vseqexpr=function(a,b){var c,d;goog.asserts.assert(void 0===b||a.length===b.length);d=[];for(c=0;c<a.length;++c)d.push(this.vexpr(a[c],void 0===b?void 0:b[c]));return d};
Compiler.prototype.caugassign=function(a){var b,c,d,e,f;goog.asserts.assert(a instanceof AugAssign);f=a.target;switch(f.constructor){case Attribute:return b=this.vexpr(f.value),f=new Attribute(f.value,f.attr,AugLoad,f.lineno,f.col_offset),e=this.vexpr(f,void 0,b),d=this.vexpr(a.value),a=this._gr("inplbinopattr","Sk.abstr.numberInplaceBinOp(",e,",",d,",'",a.op.prototype._astname,"')"),f.ctx=AugStore,this.vexpr(f,a,b);case Subscript:return b=this.vexpr(f.value),c=this.vslicesub(f.slice),f=new Subscript(f.value,
c,AugLoad,f.lineno,f.col_offset),e=this.vexpr(f,void 0,b,c),d=this.vexpr(a.value),a=this._gr("inplbinopsubscr","Sk.abstr.numberInplaceBinOp(",e,",",d,",'",a.op.prototype._astname,"')"),f.ctx=AugStore,this.vexpr(f,a,b,c);case Name:return b=this.nameop(f.id,Load),d=this.vexpr(a.value),a=this._gr("inplbinop","Sk.abstr.numberInplaceBinOp(",b,",",d,",'",a.op.prototype._astname,"')"),this.nameop(f.id,Store,a);default:goog.asserts.fail("unhandled case in augassign")}};
Compiler.prototype.exprConstant=function(a){switch(a.constructor){case Num:return Sk.misceval.isTrue(a.n)?1:0;case Str:return Sk.misceval.isTrue(a.s)?1:0;default:return-1}};Compiler.prototype.newBlock=function(a){var b=this.u.blocknum++;this.u.blocks[b]=[];this.u.blocks[b]._name=a||"<unnamed>";this.u.blocks[b]._next=null;return b};Compiler.prototype.setBlock=function(a){goog.asserts.assert(0<=a&&a<this.u.blocknum);this.u.curblock=a};
Compiler.prototype.pushBreakBlock=function(a){goog.asserts.assert(0<=a&&a<this.u.blocknum);this.u.breakBlocks.push(a)};Compiler.prototype.popBreakBlock=function(){this.u.breakBlocks.pop()};Compiler.prototype.pushContinueBlock=function(a){goog.asserts.assert(0<=a&&a<this.u.blocknum);this.u.continueBlocks.push(a)};Compiler.prototype.popContinueBlock=function(){this.u.continueBlocks.pop()};Compiler.prototype.pushExceptBlock=function(a){goog.asserts.assert(0<=a&&a<this.u.blocknum);this.u.exceptBlocks.push(a)};
Compiler.prototype.popExceptBlock=function(){this.u.exceptBlocks.pop()};Compiler.prototype.pushFinallyBlock=function(a){goog.asserts.assert(0<=a&&a<this.u.blocknum);this.u.finallyBlocks.push(a)};Compiler.prototype.popFinallyBlock=function(){this.u.finallyBlocks.pop()};Compiler.prototype.setupExcept=function(a){out("$exc.push(",a,");")};Compiler.prototype.endExcept=function(){out("$exc.pop();")};
Compiler.prototype.outputLocals=function(a){var b,c,d,e={};for(d=0;a.argnames&&d<a.argnames.length;++d)e[a.argnames[d]]=!0;a.localnames.sort();c=[];for(d=0;d<a.localnames.length;++d)b=a.localnames[d],void 0===e[b]&&(c.push(b),e[b]=!0);return 0<c.length?"var "+c.join(",")+"; /* locals */":""};
Compiler.prototype.outputSuspensionHelpers=function(a){var b,c,d=[],e=a.localnames.concat(a.tempsToSave),f={},g=a.ste.blockType===FunctionBlock&&a.ste.childHasFree,h="var $wakeFromSuspension = function() {var susp = "+a.scopename+".wakingSuspension; delete "+a.scopename+".wakingSuspension;$blk=susp.$blk; $loc=susp.$loc; $gbl=susp.$gbl; $exc=susp.$exc; $err=susp.$err;currLineNo=susp.lineno; currColNo=susp.colno; Sk.lastYield=Date.now();"+(g?"$cell=susp.$cell;":"");for(b=0;b<e.length;b++)c=e[b],void 0===
f[c]&&(h+=c+"=susp.$tmps."+c+";",f[c]=!0);h+="try { $ret=susp.child.resume(); } catch(err) { if (!(err instanceof Sk.builtin.BaseException)) { err = new Sk.builtin.ExternalError(err); } err.traceback.push({lineno: currLineNo, colno: currColNo, filename: '"+this.filename+"'}); if($exc.length>0) { $err=err; $blk=$exc.pop(); } else { throw err; } }};";h+="var $saveSuspension = function(child, filename, lineno, colno) {var susp = new Sk.misceval.Suspension(); susp.child=child;susp.resume=function(){"+
a.scopename+".wakingSuspension=susp; return "+a.scopename+"("+(a.ste.generator?"$gen":"")+"); };susp.data=susp.child.data;susp.$blk=$blk;susp.$loc=$loc;susp.$gbl=$gbl;susp.$exc=$exc;susp.$err=$err;susp.filename=filename;susp.lineno=lineno;susp.colno=colno;susp.optional=child.optional;"+(g?"susp.$cell=$cell;":"");f={};for(b=0;b<e.length;b++)c=e[b],void 0===f[c]&&(d.push('"'+c+'":'+c),f[c]=!0);return h+="susp.$tmps={"+d.join(",")+"};return susp;};"};
Compiler.prototype.outputAllUnits=function(){var a,b,c,d,e="",f,g;for(d=0;d<this.allUnits.length;++d){c=this.allUnits[d];e+=c.prefixCode;e+=this.outputLocals(c);c.doesSuspend&&(e+=this.outputSuspensionHelpers(c));e+=c.varDeclsCode;e+=c.switchCode;b=c.blocks;g=Object.create(null);for(a=0;a<b.length;++a)if(f=a,!(f in g))for(;;)if(g[f]=!0,e+="case "+f+": /* --- "+b[f]._name+" --- */",e+=b[f].join(""),null!==b[f]._next)if(b[f]._next in g){e+="/* jump */ continue;";break}else e+="/* allowing case fallthrough */",
f=b[f]._next;else{e+="throw new Sk.builtin.SystemError('internal error: unterminated block');";break}e+=c.suffixCode}return e};
Compiler.prototype.cif=function(a){var b,c,d;goog.asserts.assert(a instanceof If_);b=this.exprConstant(a.test);0===b?a.orelse&&0<a.orelse.length&&this.vseqstmt(a.orelse):1===b?this.vseqstmt(a.body):(d=this.newBlock("end of if"),a.orelse&&0<a.orelse.length&&(c=this.newBlock("next branch of if")),b=this.vexpr(a.test),a.orelse&&0<a.orelse.length?(this._jumpfalse(b,c),this.vseqstmt(a.body),this._jump(d),this.setBlock(c),this.vseqstmt(a.orelse)):(this._jumpfalse(b,d),this.vseqstmt(a.body)),this._jump(d),
this.setBlock(d))};
Compiler.prototype.cwhile=function(a){var b,c,d,e;0===this.exprConstant(a.test)?a.orelse&&this.vseqstmt(a.orelse):(e=this.newBlock("while test"),this._jump(e),this.setBlock(e),d=this.newBlock("after while"),c=0<a.orelse.length?this.newBlock("while orelse"):null,b=this.newBlock("while body"),this.annotateSource(a),this._jumpfalse(this.vexpr(a.test),c?c:d),this._jump(b),this.pushBreakBlock(d),this.pushContinueBlock(e),this.setBlock(b),this.vseqstmt(a.body),this._jump(e),this.popContinueBlock(),this.popBreakBlock(),
0<a.orelse.length&&(this.setBlock(c),this.vseqstmt(a.orelse),this._jump(d)),this.setBlock(d))};
Compiler.prototype.cfor=function(a){var b,c,d=this.newBlock("for start"),e=this.newBlock("for cleanup"),f=this.newBlock("for end");this.pushBreakBlock(f);this.pushContinueBlock(d);c=this.vexpr(a.iter);this.u.ste.generator?(b="$loc."+this.gensym("iter"),out(b,"=Sk.abstr.iter(",c,");")):(b=this._gr("iter","Sk.abstr.iter(",c,")"),this.u.tempsToSave.push(b));this._jump(d);this.setBlock(d);out("$ret = Sk.abstr.iternext(",b,this.u.canSuspend?", true":", false",");");this._checkSuspension(a);b=this._gr("next",
"$ret");this._jumpundef(b,e);this.vexpr(a.target,b);this.vseqstmt(a.body);this._jump(d);this.setBlock(e);this.popContinueBlock();this.popBreakBlock();this.vseqstmt(a.orelse);this._jump(f);this.setBlock(f)};
Compiler.prototype.craise=function(a){var b;a&&a.type&&a.type.id&&"StopIteration"===a.type.id.v?out("return undefined;"):a.inst?(b=this.vexpr(a.inst),out("throw ",this.vexpr(a.type),"(",b,");")):a.type?a.type.func?out("throw ",this.vexpr(a.type),";"):(a=this._gr("err",this.vexpr(a.type)),out("if(",a," instanceof Sk.builtin.type) {","throw Sk.misceval.callsim(",a,");","} else if(typeof(",a,") === 'function') {","throw ",a,"();","} else {","throw ",a,";","}")):out("throw $err;")};
Compiler.prototype.ctryexcept=function(a){var b,c,d,e,f,g,h,k=a.handlers.length,l=[];for(h=0;h<k;++h)l.push(this.newBlock("except_"+h+"_"));g=this.newBlock("unhandled");f=this.newBlock("orelse");e=this.newBlock("end");this.setupExcept(l[0]);this.vseqstmt(a.body);this.endExcept();this._jump(f);for(h=0;h<k;++h){this.setBlock(l[h]);d=a.handlers[h];if(!d.type&&h<k-1)throw new SyntaxError("default 'except:' must be last");d.type&&(b=this.vexpr(d.type),c=h==k-1?g:l[h+1],b=this._gr("instance","$err instanceof ",
b),this._jumpfalse(b,c));d.name&&this.vexpr(d.name,"$err");this.vseqstmt(d.body);this._jump(e)}this.setBlock(g);out("throw $err;");this.setBlock(f);this.vseqstmt(a.orelse);this._jump(e);this.setBlock(e)};Compiler.prototype.ctryfinally=function(a){out("/*todo; tryfinally*/");this.ctryexcept(a.body[0])};Compiler.prototype.cassert=function(a){var b=this.vexpr(a.test),c=this.newBlock("end");this._jumptrue(b,c);out("throw new Sk.builtin.AssertionError(",a.msg?this.vexpr(a.msg):"",");");this.setBlock(c)};
Compiler.prototype.cimportas=function(a,b,c){a=a.v;var d=a.indexOf("."),e=c;if(-1!==d)for(a=a.substr(d+1);-1!==d;)d=a.indexOf("."),c=-1!==d?a.substr(0,d):a,e=this._gr("lattr","Sk.abstr.gattr(",e,",'",c,"')"),a=a.substr(d+1);return this.nameop(b,Store,e)};
Compiler.prototype.cimport=function(a){var b,c,d,e,f=a.names.length;for(e=0;e<f;++e)b=a.names[e],out("$ret = Sk.builtin.__import__(",b.name.$r().v,",$gbl,$loc,[]);"),this._checkSuspension(a),d=this._gr("module","$ret"),b.asname?this.cimportas(b.name,b.asname,d):(c=b.name,b=c.v.indexOf("."),-1!==b&&(c=new Sk.builtin.str(c.v.substr(0,b))),this.nameop(c,Store,d))};
Compiler.prototype.cfromimport=function(a){var b,c,d,e,f,g=a.names.length;b=[];for(f=0;f<g;++f)b[f]=a.names[f].name.$r().v;out("$ret = Sk.builtin.__import__(",a.module.$r().v,",$gbl,$loc,[",b,"]);");this._checkSuspension(a);e=this._gr("module","$ret");for(f=0;f<g;++f){d=a.names[f];if(0===f&&"*"===d.name.v){goog.asserts.assert(1===g);out("Sk.importStar(",e,",$loc, $gbl);");break}c=this._gr("item","Sk.abstr.gattr(",e,",",d.name.$r().v,")");b=d.name;d.asname&&(b=d.asname);this.nameop(b,Store,c)}};
Compiler.prototype.buildcodeobj=function(a,b,c,d,e){var f,g,h,k,l,m,q,n,r=[],p=null;f=null;c&&this.vseqexpr(c);d&&d.defaults&&(r=this.vseqexpr(d.defaults));d&&d.vararg&&(p=d.vararg);d&&d.kwarg&&(f=d.kwarg);c=this.enterScope(b,a,a.lineno,this.canSuspend);a=this.u.ste.generator;n=this.u.ste.hasFree;m=this.u.ste.childHasFree;l=this.newBlock("codeobj entry");this.u.prefixCode="var "+c+"=(function "+this.niceName(b.v)+"$(";h=[];if(a){if(f)throw new SyntaxError(b.v+"(): keyword arguments in generators not supported");
if(p)throw new SyntaxError(b.v+"(): variable number of arguments in generators not supported");h.push("$gen")}else for(f&&(h.push("$kwa"),this.u.tempsToSave.push("$kwa")),k=0;d&&k<d.args.length;++k)h.push(this.nameop(d.args[k].id,Param));n&&(h.push("$free"),this.u.tempsToSave.push("$free"));this.u.prefixCode+=h.join(",");this.u.prefixCode+="){";a&&(this.u.prefixCode+="\n// generator\n");n&&(this.u.prefixCode+="\n// has free\n");m&&(this.u.prefixCode+="\n// has cell\n");q="{}";a&&(l="$gen.gi$resumeat",
q="$gen.gi$locals");k="";m&&(k=a?",$cell=$gen.gi$cells":",$cell={}");this.u.varDeclsCode+="var $blk="+l+",$exc=[],$loc="+q+k+",$gbl=this,$err=undefined,$ret=undefined,currLineNo=undefined,currColNo=undefined;";null!==Sk.execLimit&&(this.u.varDeclsCode+="if (typeof Sk.execStart === 'undefined') {Sk.execStart = Date.now()}");null!==Sk.yieldLimit&&this.u.canSuspend&&(this.u.varDeclsCode+="if (typeof Sk.lastYield === 'undefined') {Sk.lastYield = Date.now()}");this.u.varDeclsCode+="if ("+c+".wakingSuspension!==undefined) { $wakeFromSuspension(); } else {";
if(0<r.length)for(m=d.args.length-r.length,k=0;k<r.length;++k)l=this.nameop(d.args[k+m].id,Param),this.u.varDeclsCode+="if("+l+"===undefined)"+l+"="+c+".$defaults["+k+"];";for(k=0;d&&k<d.args.length;++k)l=d.args[k].id,this.isCell(l)&&(this.u.varDeclsCode+="$cell."+l.v+"="+l.v+";");a||(l=d?d.args.length-r.length:0,k=p?Infinity:d?d.args.length:0,this.u.varDeclsCode+='Sk.builtin.pyCheckArgs("'+b.v+'", arguments, '+l+", "+k+", "+(f?!0:!1)+", "+n+");");p&&(h=h.length,this.u.localnames.push(p.v),this.u.varDeclsCode+=
p.v+"=new Sk.builtins['tuple'](Array.prototype.slice.call(arguments,"+h+")); /*vararg*/");f&&(this.u.localnames.push(f.v),this.u.varDeclsCode+=f.v+"=new Sk.builtins['dict']($kwa);");this.u.varDeclsCode+="}";this.u.switchCode="while(true){try{";this.u.switchCode+=this.outputInterruptTest();this.u.switchCode+="switch($blk){";this.u.suffixCode="} }catch(err){ if (!(err instanceof Sk.builtin.BaseException)) { err = new Sk.builtin.ExternalError(err); } err.traceback.push({lineno: currLineNo, colno: currColNo, filename: '"+
this.filename+"'}); if ($exc.length>0) { $err = err; $blk=$exc.pop(); continue; } else { throw err; }} }});";e.call(this,c);if(d&&0<d.args.length){e=[];for(k=0;k<d.args.length;++k)e.push(d.args[k].id.v);g=e.join("', '");this.u.argnames=e}this.exitScope();0<r.length&&out(c,".$defaults=[",r.join(","),"];");g&&out(c,".co_varnames=['",g,"'];");f&&out(c,".co_kwargs=1;");g="";n&&(g=",$cell",(f=this.u.ste.hasFree)&&(g+=",$free"));return a?d&&0<d.args.length?this._gr("gener","new Sk.builtins['function']((function(){var $origargs=Array.prototype.slice.call(arguments);Sk.builtin.pyCheckArgs(\"",
b.v,'",arguments,',d.args.length-r.length,",",d.args.length,");return new Sk.builtins['generator'](",c,",$gbl,$origargs",g,");}))"):this._gr("gener","new Sk.builtins['function']((function(){Sk.builtin.pyCheckArgs(\"",b.v,"\",arguments,0,0);return new Sk.builtins['generator'](",c,",$gbl,[]",g,");}))"):this._gr("funcobj","new Sk.builtins['function'](",c,",$gbl",g,")")};
Compiler.prototype.cfunction=function(a){var b;goog.asserts.assert(a instanceof FunctionDef);b=this.buildcodeobj(a,a.name,a.decorator_list,a.args,function(b){this.vseqstmt(a.body);out("return Sk.builtin.none.none$;")});this.nameop(a.name,Store,b)};Compiler.prototype.clambda=function(a){goog.asserts.assert(a instanceof Lambda);return this.buildcodeobj(a,new Sk.builtin.str("<lambda>"),null,a.args,function(b){b=this.vexpr(a.body);out("return ",b,";")})};
Compiler.prototype.cifexp=function(a){var b=this.newBlock("next of ifexp"),c=this.newBlock("end of ifexp"),d=this._gr("res","null"),e=this.vexpr(a.test);this._jumpfalse(e,b);out(d,"=",this.vexpr(a.body),";");this._jump(c);this.setBlock(b);out(d,"=",this.vexpr(a.orelse),";");this._jump(c);this.setBlock(c);return d};
Compiler.prototype.cgenexpgen=function(a,b,c){var d,e,f,g=this.newBlock("start for "+b),h=this.newBlock("skip for "+b);this.newBlock("if cleanup for "+b);var k=this.newBlock("end for "+b),l=a[b];0===b?e="$loc.$iter0":(d=this.vexpr(l.iter),e="$loc."+this.gensym("iter"),out(e,"=","Sk.abstr.iter(",d,");"));this._jump(g);this.setBlock(g);d=this._gr("next","Sk.abstr.iternext(",e,")");this._jumpundef(d,k);this.vexpr(l.target,d);f=l.ifs.length;for(e=0;e<f;++e)d=this.vexpr(l.ifs[e]),this._jumpfalse(d,g);
++b<a.length&&this.cgenexpgen(a,b,c);b>=a.length&&(a=this.vexpr(c),out("return [",h,"/*resume*/,",a,"/*ret*/];"),this.setBlock(h));this._jump(g);this.setBlock(k);1===b&&out("return Sk.builtin.none.none$;")};Compiler.prototype.cgenexp=function(a){var b=this.buildcodeobj(a,new Sk.builtin.str("<genexpr>"),null,null,function(b){this.cgenexpgen(a.generators,0,a.elt)}),b=this._gr("gener","Sk.misceval.callsim(",b,");");out(b,".gi$locals.$iter0=Sk.abstr.iter(",this.vexpr(a.generators[0].iter),");");return b};
Compiler.prototype.cclass=function(a){var b,c,d;goog.asserts.assert(a instanceof ClassDef);d=this.vseqexpr(a.bases);c=this.enterScope(a.name,a,a.lineno);b=this.newBlock("class entry");this.u.prefixCode="var "+c+"=(function $"+a.name.v+"$class_outer($globals,$locals,$rest){var $gbl=$globals,$loc=$locals;";this.u.switchCode+="return(function $"+a.name.v+"$_closure(){";this.u.switchCode+="var $blk="+b+",$exc=[],$ret=undefined,currLineNo=undefined,currColNo=undefined;";null!==Sk.execLimit&&(this.u.switchCode+=
"if (typeof Sk.execStart === 'undefined') {Sk.execStart = Date.now()}");null!==Sk.yieldLimit&&this.u.canSuspend&&(this.u.switchCode+="if (typeof Sk.lastYield === 'undefined') {Sk.lastYield = Date.now()}");this.u.switchCode+="while(true){";this.u.switchCode+=this.outputInterruptTest();this.u.switchCode+="switch($blk){";this.u.suffixCode="}break;}}).apply(null,$rest);});";this.u.private_=a.name;this.cbody(a.body);out("break;");this.exitScope();b=this._gr("built","Sk.misceval.buildClass($gbl,",c,",",
a.name.$r().v,",[",d,"])");this.nameop(a.name,Store,b)};Compiler.prototype.ccontinue=function(a){if(0===this.u.continueBlocks.length)throw new SyntaxError("'continue' outside loop");this._jump(this.u.continueBlocks[this.u.continueBlocks.length-1])};
Compiler.prototype.vstmt=function(a){var b,c,d;this.u.lineno=a.lineno;this.u.linenoSet=!1;this.u.localtemps=[];Sk.debugging&&this.u.canSuspend&&(b=this.newBlock("debug breakpoint for line "+a.lineno),out("if (Sk.breakpoints('"+this.filename+"',"+a.lineno+","+a.col_offset+")) {","var $susp = $saveSuspension({data: {type: 'Sk.debug'}, resume: function() {}}, '"+this.filename+"',"+a.lineno+","+a.col_offset+");","$susp.$blk = "+b+";","$susp.optional = true;","return $susp;","}"),this._jump(b),this.setBlock(b),
this.u.doesSuspend=!0);this.annotateSource(a);switch(a.constructor){case FunctionDef:this.cfunction(a);break;case ClassDef:this.cclass(a);break;case Return_:if(this.u.ste.blockType!==FunctionBlock)throw new SyntaxError("'return' outside function");a.value?out("return ",this.vexpr(a.value),";"):out("return Sk.builtin.none.none$;");break;case Delete_:this.vseqexpr(a.targets);break;case Assign:d=a.targets.length;c=this.vexpr(a.value);for(b=0;b<d;++b)this.vexpr(a.targets[b],c);break;case AugAssign:return this.caugassign(a);
case Print:this.cprint(a);break;case For_:return this.cfor(a);case While_:return this.cwhile(a);case If_:return this.cif(a);case Raise:return this.craise(a);case TryExcept:return this.ctryexcept(a);case TryFinally:return this.ctryfinally(a);case Assert:return this.cassert(a);case Import_:return this.cimport(a);case ImportFrom:return this.cfromimport(a);case Global:break;case Expr:this.vexpr(a.value);break;case Pass:break;case Break_:if(0===this.u.breakBlocks.length)throw new SyntaxError("'break' outside loop");
this._jump(this.u.breakBlocks[this.u.breakBlocks.length-1]);break;case Continue_:this.ccontinue(a);break;case Debugger_:out("debugger;");break;default:goog.asserts.fail("unhandled case in vstmt")}};Compiler.prototype.vseqstmt=function(a){var b;for(b=0;b<a.length;++b)this.vstmt(a[b])};var OP_FAST=0,OP_GLOBAL=1,OP_DEREF=2,OP_NAME=3,D_NAMES=0,D_FREEVARS=1,D_CELLVARS=2;Compiler.prototype.isCell=function(a){a=mangleName(this.u.private_,a).v;return this.u.ste.getScope(a)===CELL};
Compiler.prototype.nameop=function(a,b,c){var d,e,f,g;if((b===Store||b===AugStore||b===Del)&&"__debug__"===a.v)throw new Sk.builtin.SyntaxError("can not assign to __debug__");if((b===Store||b===AugStore||b===Del)&&"None"===a.v)throw new Sk.builtin.SyntaxError("can not assign to None");if("None"===a.v)return"Sk.builtin.none.none$";if("True"===a.v)return"Sk.builtin.bool.true$";if("False"===a.v)return"Sk.builtin.bool.false$";if("NotImplemented"===a.v)return"Sk.builtin.NotImplemented.NotImplemented$";
g=mangleName(this.u.private_,a).v;g=fixReservedNames(g);f=OP_NAME;e=this.u.ste.getScope(g);d=null;switch(e){case FREE:d="$free";f=OP_DEREF;break;case CELL:d="$cell";f=OP_DEREF;break;case LOCAL:this.u.ste.blockType!==FunctionBlock||this.u.ste.generator||(f=OP_FAST);break;case GLOBAL_IMPLICIT:this.u.ste.blockType===FunctionBlock&&(f=OP_GLOBAL);break;case GLOBAL_EXPLICIT:f=OP_GLOBAL}g=fixReservedWords(g);goog.asserts.assert(e||"_"===a.v.charAt(1));a=g;this.u.ste.generator||this.u.ste.blockType!==FunctionBlock?
g="$loc."+g:f!==OP_FAST&&f!==OP_NAME||this.u.localnames.push(g);switch(f){case OP_FAST:switch(b){case Load:case Param:return out("if (",g," === undefined) { throw new Sk.builtin.UnboundLocalError('local variable \\'",g,"\\' referenced before assignment'); }\n"),g;case Store:out(g,"=",c,";");break;case Del:out("delete ",g,";");break;default:goog.asserts.fail("unhandled")}break;case OP_NAME:switch(b){case Load:return this._gr("loadname",g,"!==undefined?",g,":Sk.misceval.loadname('",a,"',$gbl);");case Store:out(g,
"=",c,";");break;case Del:out("delete ",g,";");break;case Param:return g;default:goog.asserts.fail("unhandled")}break;case OP_GLOBAL:switch(b){case Load:return this._gr("loadgbl","Sk.misceval.loadname('",a,"',$gbl)");case Store:out("$gbl.",a,"=",c,";");break;case Del:out("delete $gbl.",a);break;default:goog.asserts.fail("unhandled case in name op_global")}break;case OP_DEREF:switch(b){case Load:return d+"."+a;case Store:out(d,".",a,"=",c,";");break;case Param:return a;default:goog.asserts.fail("unhandled case in name op_deref")}break;
default:goog.asserts.fail("unhandled case")}};Compiler.prototype.enterScope=function(a,b,c,d){var e=new CompilerUnit;e.ste=this.st.getStsForAst(b);e.name=a;e.firstlineno=c;e.canSuspend=d||!1;this.u&&this.u.private_&&(e.private_=this.u.private_);this.stack.push(this.u);this.allUnits.push(e);a=this.gensym("scope");e.scopename=a;this.u=e;this.u.activateScope();this.nestlevel++;return a};
Compiler.prototype.exitScope=function(){var a,b=this.u;this.nestlevel--;(this.u=0<=this.stack.length-1?this.stack.pop():null)&&this.u.activateScope();"<module>"!==b.name.v&&(a=b.name.$r().v,a=a.substring(1,a.length-1),a=fixReservedWords(a),a=fixReservedNames(a),out(b.scopename,".co_name=new Sk.builtins['str']('",a,"');"))};Compiler.prototype.cbody=function(a){var b;for(b=0;b<a.length;++b)this.vstmt(a[b])};
Compiler.prototype.cprint=function(a){var b,c;goog.asserts.assert(a instanceof Print);a.dest&&this.vexpr(a.dest);c=a.values.length;for(b=0;b<c;++b)out("Sk.misceval.print_(","new Sk.builtins['str'](",this.vexpr(a.values[b]),").v);");a.nl&&out("Sk.misceval.print_(",'"\\n");')};
Compiler.prototype.cmod=function(a){var b=this.enterScope(new Sk.builtin.str("<module>"),a,0,this.canSuspend),c=this.newBlock("module entry");this.u.prefixCode="var "+b+"=(function($modname){";this.u.varDeclsCode="var $gbl = {}, $blk="+c+",$exc=[],$loc=$gbl,$err=undefined;$gbl.__name__=$modname,$ret=undefined,currLineNo=undefined,currColNo=undefined;";null!==Sk.execLimit&&(this.u.varDeclsCode+="if (typeof Sk.execStart === 'undefined') {Sk.execStart = Date.now()}");null!==Sk.yieldLimit&&this.u.canSuspend&&
(this.u.varDeclsCode+="if (typeof Sk.lastYield === 'undefined') {Sk.lastYield = Date.now()}");this.u.varDeclsCode+="if ("+b+".wakingSuspension!==undefined) { $wakeFromSuspension(); }if (Sk.retainGlobals) { if (Sk.globals) { $gbl = Sk.globals; Sk.globals = $gbl; $loc = $gbl; } else { Sk.globals = $gbl; }} else { Sk.globals = $gbl; }";this.u.switchCode="while(true){try{";this.u.switchCode+=this.outputInterruptTest();this.u.switchCode+="switch($blk){";this.u.suffixCode="}";this.u.suffixCode+="}catch(err){ if (!(err instanceof Sk.builtin.BaseException)) { err = new Sk.builtin.ExternalError(err); } err.traceback.push({lineno: currLineNo, colno: currColNo, filename: '"+
this.filename+"'}); if ($exc.length>0) { $err = err; $blk=$exc.pop(); continue; } else { throw err; }} } });";switch(a.constructor){case Module:this.cbody(a.body);out("return $loc;");break;default:goog.asserts.fail("todo; unhandled case in compilerMod")}this.exitScope();this.result.push(this.outputAllUnits());return b};
Sk.compile=function(a,b,c,d){var e=Sk.parse(b,a);c=Sk.astFromParse(e.cst,b,e.flags);var e=e.flags,f=Sk.symboltable(c,b);a=new Compiler(b,f,e,d,a);b=a.cmod(c);a=a.result.join("");return{funcname:b,code:a}};goog.exportSymbol("Sk.compile",Sk.compile);Sk.resetCompiler=function(){Sk.gensymcount=0};goog.exportSymbol("Sk.resetCompiler",Sk.resetCompiler);Sk.sysmodules=new Sk.builtin.dict([]);Sk.realsyspath=void 0;Sk.externalLibraryCache={};Sk.loadExternalLibraryInternal_=function(a,b){var c,d;if(null!=a){if(Sk.externalLibraryCache[a])return Sk.externalLibraryCache[a];c=new XMLHttpRequest;c.open("GET",a,!1);c.send();if(200===c.status)return d=c.responseText,b&&(c=document.createElement("script"),c.type="text/javascript",c.text=d,document.getElementsByTagName("head")[0].appendChild(c)),d}};
Sk.loadExternalLibrary=function(a){var b,c,d,e,f,g;if(Sk.externalLibraryCache[a])return Sk.externalLibraryCache[a];if(b=Sk.externalLibraries&&Sk.externalLibraries[a]){c="string"===typeof b?b:b.path;if("string"!==typeof c)throw new Sk.builtin.ImportError("Invalid path specified for "+a);g=b.type;g||(g=(d=c.match(/\.(js|py)$/))&&d[1]);if(!g)throw new Sk.builtin.ImportError("Invalid file extension specified for "+a);d=Sk.loadExternalLibraryInternal_(c,!1);if(!d)throw new Sk.builtin.ImportError("Failed to load remote module '"+
a+"'");if((e=b.dependencies)&&e.length)for(b=0;b<e.length;b++)if(f=Sk.loadExternalLibraryInternal_(e[b],!0),!f)throw new Sk.builtin.ImportError("Failed to load dependencies required for "+a);c="js"===g?{funcname:"$builtinmodule",code:d}:Sk.compile(d,c,"exec",!0);return Sk.externalLibraryCache[a]=c}};
Sk.importSearchPathForName=function(a,b,c,d){var e,f=[],g=a.replace(/\./g,"/"),h,k;h=Sk.realsyspath.tp$iter();for(k=h.tp$iternext();void 0!==k;k=h.tp$iternext())f.push(k.v+"/"+g+b),f.push(k.v+"/"+g+"/__init__"+b);e=0;return function m(){for(var b=function s(a){var b;return a instanceof Sk.misceval.Suspension?(b=new Sk.misceval.Suspension(void 0,a),b.resume=function(){try{return s(a.resume())}catch(b){return e++,m()}},b):{filename:f[e],code:a}},g;e<f.length;)try{return g=Sk.read(f[e]),d||(g=Sk.misceval.retryOptionalSuspensionOrThrow(g)),
b(g)}catch(h){e++}if(c)return null;throw new Sk.builtin.ImportError("No module named "+a);}()};
Sk.doOneTimeInitialization=function(){var a,b,c;Sk.builtin.type.basesStr_=new Sk.builtin.str("__bases__");Sk.builtin.type.mroStr_=new Sk.builtin.str("__mro__");for(a in Sk.builtin)if(b=Sk.builtin[a],(b.prototype instanceof Sk.builtin.object||b===Sk.builtin.object)&&!b.sk$abstract){c=[];for(var d=void 0,d=b.tp$base;void 0!==d;d=d.tp$base)c.push(d);b.$d=new Sk.builtin.dict([]);b.$d.mp$ass_subscript(Sk.builtin.type.basesStr_,new Sk.builtin.tuple(c));b.$d.mp$ass_subscript(Sk.builtin.type.mroStr_,new Sk.builtin.tuple([b]))}a=
Sk.builtin.object.prototype;for(c=0;c<Sk.builtin.object.pythonFunctions.length;c++){b=Sk.builtin.object.pythonFunctions[c];if(a[b]instanceof Sk.builtin.func)break;a[b]=new Sk.builtin.func(a[b])}};Sk.importSetUpPath=function(){var a,b;if(!Sk.realsyspath){b=[new Sk.builtin.str("src/builtin"),new Sk.builtin.str("src/lib"),new Sk.builtin.str(".")];for(a=0;a<Sk.syspath.length;++a)b.push(new Sk.builtin.str(Sk.syspath[a]));Sk.realsyspath=new Sk.builtin.list(b);Sk.doOneTimeInitialization()}};
if(COMPILED)var js_beautify=function(a){return a};
Sk.importModuleInternal_=function(a,b,c,d,e){var f,g,h,k,l,m,q,n,r,p,s;Sk.importSetUpPath();void 0===c&&(c=a);s=null;p=c.split(".");try{return m=Sk.sysmodules.mp$subscript(c),1<p.length?Sk.sysmodules.mp$subscript(p[0]):m}catch(B){}if(1<p.length&&(r=p.slice(0,p.length-1).join("."),s=Sk.importModuleInternal_(r,b,void 0,void 0,e),s instanceof Sk.misceval.Suspension))return function y(f){return f instanceof Sk.misceval.Suspension?new Sk.misceval.Suspension(y,f):Sk.importModuleInternal_(a,b,c,d,e)}(s);
n=new Sk.builtin.module;Sk.sysmodules.mp$ass_subscript(a,n);if(d)m=Sk.compile(d,a+".py","exec",e);else{if(Sk.onBeforeImport&&"function"===typeof Sk.onBeforeImport){m=Sk.onBeforeImport(a);if(!1===m)throw new Sk.builtin.ImportError("Importing "+a+" is not allowed");if("string"===typeof m)throw new Sk.builtin.ImportError(m);}m=Sk.loadExternalLibrary(a);m||(m=Sk.importSearchPathForName(a,".js",!0,e),m=function C(b){if(b instanceof Sk.misceval.Suspension)return new Sk.misceval.Suspension(C,b);if(b)return q?
Sk.compile(b.code,b.filename,"exec",e):{funcname:"$builtinmodule",code:b.code};goog.asserts.assert(!q,"Sk.importReadFileFromPath did not throw when loading Python file failed");q=!0;return C(Sk.importSearchPathForName(a,".py",!1,e))}(m))}return function v(d){if(d instanceof Sk.misceval.Suspension)return e?new Sk.misceval.Suspension(v,d):Sk.misceval.retryOptionalSuspensionOrThrow(d);l=n.$js=d.code;null!=Sk.dateSet&&Sk.dateSet||(l="Sk.execStart = Sk.lastYield = new Date();\n"+d.code,Sk.dateSet=!0);
b&&(k=function(a){var b,c,d=js_beautify(a).split("\n");for(c=1;c<=d.length;++c){b=(""+c).length;for(a="";5>b;++b)a+=" ";d[c-1]="/* "+a+c+" */ "+d[c-1]}return d.join("\n")},l=k(l),Sk.debugout(l));h="new Sk.builtin.str('"+c+"')";l+="\n"+d.funcname+"("+h+");";g=goog.global.eval(l);return function t(b){if(b instanceof Sk.misceval.Suspension){if(e)return new Sk.misceval.Suspension(t,b);b=Sk.misceval.retryOptionalSuspensionOrThrow(b,'Module "'+c+'" suspended or blocked during load, and it was loaded somewhere that does not permit this')}b.__name__||
(b.__name__=new Sk.builtin.str(c));n.$d=b;b.__doc__||(b.__doc__=Sk.builtin.none.none$);if(Sk.onAfterImport&&"function"===typeof Sk.onAfterImport)try{Sk.onAfterImport(a)}catch(d){}return s?(f=Sk.sysmodules.mp$subscript(r),f.tp$setattr(p[p.length-1],n),s):n}(g)}(m)};Sk.importModule=function(a,b,c){return Sk.importModuleInternal_(a,b,void 0,void 0,c)};
Sk.importMain=function(a,b,c){Sk.dateSet=!1;Sk.filesLoaded=!1;Sk.sysmodules=new Sk.builtin.dict([]);Sk.realsyspath=void 0;Sk.resetCompiler();return Sk.importModuleInternal_(a,b,"__main__",void 0,c)};Sk.importMainWithBody=function(a,b,c,d){Sk.dateSet=!1;Sk.filesLoaded=!1;Sk.sysmodules=new Sk.builtin.dict([]);Sk.realsyspath=void 0;Sk.resetCompiler();return Sk.importModuleInternal_(a,b,"__main__",c,d)};
Sk.builtin.__import__=function(a,b,c,d){var e=Sk.globals;return function g(b){if(b instanceof Sk.misceval.Suspension)return new Sk.misceval.Suspension(g,b);e!==Sk.globals&&(Sk.globals=e);if(!d||0===d.length)return b;b=Sk.sysmodules.mp$subscript(a);goog.asserts.assert(b);return b}(Sk.importModuleInternal_(a,void 0,void 0,void 0,!0))};Sk.importStar=function(a,b,c){var d,e=c.__name__,f=Object.getOwnPropertyNames(a.$d);for(d in f)b[f[d]]=a.$d[f[d]];c.__name__!==e&&(c.__name__=e)};
goog.exportSymbol("Sk.importMain",Sk.importMain);goog.exportSymbol("Sk.importMainWithBody",Sk.importMainWithBody);goog.exportSymbol("Sk.builtin.__import__",Sk.builtin.__import__);goog.exportSymbol("Sk.importStar",Sk.importStar);Sk.builtin.timSort=function(a,b){this.list=new Sk.builtin.list(a.v);this.MIN_GALLOP=7;this.listlength=b?b:a.sq$length()};Sk.builtin.timSort.prototype.lt=function(a,b){return Sk.misceval.richCompareBool(a,b,"Lt")};Sk.builtin.timSort.prototype.le=function(a,b){return!this.lt(b,a)};Sk.builtin.timSort.prototype.setitem=function(a,b){this.list.v[a]=b};
Sk.builtin.timSort.prototype.binary_sort=function(a,b){var c,d,e,f,g;for(g=a.base+b;g<a.base+a.len;g++){f=a.base;e=g;for(c=a.getitem(e);f<e;)d=f+(e-f>>1),this.lt(c,a.getitem(d))?e=d:f=d+1;goog.asserts.assert(f===e);for(d=g;d>f;d--)a.setitem(d,a.getitem(d-1));a.setitem(f,c)}};
Sk.builtin.timSort.prototype.count_run=function(a){var b,c,d;if(1>=a.len)b=a.len,d=!1;else if(b=2,this.lt(a.getitem(a.base+1),a.getitem(a.base)))for(d=!0,c=a.base+2;c<a.base+a.len;c++)if(this.lt(a.getitem(c),a.getitem(c-1)))b++;else break;else for(d=!1,c=a.base+2;c<a.base+a.len&&!this.lt(a.getitem(c),a.getitem(c-1));c++)b++;return{run:new Sk.builtin.listSlice(a.list,a.base,b),descending:d}};
Sk.builtin.timSort.prototype.sort=function(){var a,b,c,d=new Sk.builtin.listSlice(this.list,0,this.listlength);if(!(2>d.len)){this.merge_init();for(a=this.merge_compute_minrun(d.len);0<d.len;)b=this.count_run(d),b.descending&&b.run.reverse(),b.run.len<a&&(c=b.run.len,b.run.len=a<d.len?a:d.len,this.binary_sort(b.run,c)),d.advance(b.run.len),this.pending.push(b.run),this.merge_collapse();goog.asserts.assert(d.base==this.listlength);this.merge_force_collapse();goog.asserts.assert(1==this.pending.length);
goog.asserts.assert(0===this.pending[0].base);goog.asserts.assert(this.pending[0].len==this.listlength)}};
Sk.builtin.timSort.prototype.gallop=function(a,b,c,d){var e,f,g,h,k;goog.asserts.assert(0<=c&&c<b.len);e=this;d=d?function(a,b){return e.le(a,b)}:function(a,b){return e.lt(a,b)};f=b.base+c;g=0;h=1;if(d(b.getitem(f),a)){for(k=b.len-c;h<k;)if(d(b.getitem(f+h),a)){g=h;try{h=(h<<1)+1}catch(l){h=k}}else break;h>k&&(h=k);g+=c;h+=c}else{for(k=c+1;h<k&&!d(b.getitem(f-h),a);){g=h;try{h=(h<<1)+1}catch(m){h=k}}h>k&&(h=k);f=c-g;g=c-h;h=f}goog.asserts.assert(-1<=g<h<=b.len);for(g+=1;g<h;)c=g+(h-g>>1),d(b.getitem(b.base+
c),a)?g=c+1:h=c;goog.asserts.assert(g==h);return h};Sk.builtin.timSort.prototype.merge_init=function(){this.min_gallop=this.MIN_GALLOP;this.pending=[]};
Sk.builtin.timSort.prototype.merge_lo=function(a,b){var c,d,e,f,g;goog.asserts.assert(0<a.len&&0<b.len&&a.base+a.len==b.base);c=this.min_gallop;d=a.base;a=a.copyitems();try{if(this.setitem(d,b.popleft()),d++,1!=a.len&&0!==b.len)for(;;){for(f=e=0;;)if(this.lt(b.getitem(b.base),a.getitem(a.base))){this.setitem(d,b.popleft());d++;if(0===b.len)return;f++;e=0;if(f>=c)break}else{this.setitem(d,a.popleft());d++;if(1==a.len)return;e++;f=0;if(e>=c)break}for(c+=1;;){this.min_gallop=c-=1<c;e=this.gallop(b.getitem(b.base),
a,0,!0);for(g=a.base;g<a.base+e;g++)this.setitem(d,a.getitem(g)),d++;a.advance(e);if(1>=a.len)return;this.setitem(d,b.popleft());d++;if(0===b.len)return;f=this.gallop(a.getitem(a.base),b,0,!1);for(g=b.base;g<b.base+f;g++)this.setitem(d,b.getitem(g)),d++;b.advance(f);if(0===b.len)return;this.setitem(d,a.popleft());d++;if(1==a.len)return;if(e<this.MIN_GALLOP&&f<this.MIN_GALLOP)break;c++;this.min_gallop=c}}}finally{goog.asserts.assert(0<=a.len&&0<=b.len);for(g=b.base;g<b.base+b.len;g++)this.setitem(d,
b.getitem(g)),d++;for(g=a.base;g<a.base+a.len;g++)this.setitem(d,a.getitem(g)),d++}};
Sk.builtin.timSort.prototype.merge_hi=function(a,b){var c,d,e,f,g,h,k,l;goog.asserts.assert(0<a.len&&0<b.len&&a.base+a.len==b.base);c=this.min_gallop;d=b.base+b.len;b=b.copyitems();try{if(d--,this.setitem(d,a.popright()),0!==a.len&&1!=b.len)for(;;){for(f=e=0;;)if(g=a.getitem(a.base+a.len-1),h=b.getitem(b.base+b.len-1),this.lt(h,g)){d--;this.setitem(d,g);a.len--;if(0===a.len)return;e++;f=0;if(e>=c)break}else{d--;this.setitem(d,h);b.len--;if(1==b.len)return;f++;e=0;if(f>=c)break}for(c+=1;;){this.min_gallop=
c-=1<c;h=b.getitem(b.base+b.len-1);k=this.gallop(h,a,a.len-1,!0);e=a.len-k;for(l=a.base+a.len-1;l>a.base+k-1;l--)d--,this.setitem(d,a.getitem(l));a.len-=e;if(0===a.len)return;d--;this.setitem(d,b.popright());if(1==b.len)return;g=a.getitem(a.base+a.len-1);k=this.gallop(g,b,b.len-1,!1);f=b.len-k;for(l=b.base+b.len-1;l>b.base+k-1;l--)d--,this.setitem(d,b.getitem(l));b.len-=f;if(1>=b.len)return;d--;this.setitem(d,a.popright());if(0===a.len)return;if(e<this.MIN_GALLOP&&f<this.MIN_GALLOP)break;c++;this.min_gallop=
c}}}finally{goog.asserts.assert(0<=a.len&&0<=b.len);for(l=a.base+a.len-1;l>a.base-1;l--)d--,this.setitem(d,a.getitem(l));for(l=b.base+b.len-1;l>b.base-1;l--)d--,this.setitem(d,b.getitem(l))}};
Sk.builtin.timSort.prototype.merge_at=function(a){var b,c;0>a&&(a=this.pending.length+a);b=this.pending[a];c=this.pending[a+1];goog.asserts.assert(0<b.len&&0<c.len);goog.asserts.assert(b.base+b.len==c.base);this.pending[a]=new Sk.builtin.listSlice(this.list,b.base,b.len+c.len);this.pending.splice(a+1,1);a=this.gallop(c.getitem(c.base),b,0,!0);b.advance(a);0!==b.len&&(c.len=this.gallop(b.getitem(b.base+b.len-1),c,c.len-1,!1),0!==c.len&&(b.len<=c.len?this.merge_lo(b,c):this.merge_hi(b,c)))};
Sk.builtin.timSort.prototype.merge_collapse=function(){for(var a=this.pending;1<a.length;)if(3<=a.length&&a[a.length-3].len<=a[a.length-2].len+a[a.length-1].len)a[a.length-3].len<a[a.length-1].len?this.merge_at(-3):this.merge_at(-2);else if(a[a.length-2].len<=a[a.length-1].len)this.merge_at(-2);else break};Sk.builtin.timSort.prototype.merge_force_collapse=function(){for(var a=this.pending;1<a.length;)3<=a.length&&a[a.length-3].len<a[a.length-1].len?this.merge_at(-3):this.merge_at(-2)};
Sk.builtin.timSort.prototype.merge_compute_minrun=function(a){for(var b=0;64<=a;)b|=a&1,a>>=1;return a+b};Sk.builtin.listSlice=function(a,b,c){this.list=a;this.base=b;this.len=c};Sk.builtin.listSlice.prototype.copyitems=function(){var a=this.base,b=this.base+this.len;goog.asserts.assert(0<=a<=b);return new Sk.builtin.listSlice(new Sk.builtin.list(this.list.v.slice(a,b)),0,this.len)};Sk.builtin.listSlice.prototype.advance=function(a){this.base+=a;this.len-=a;goog.asserts.assert(this.base<=this.list.sq$length())};
Sk.builtin.listSlice.prototype.getitem=function(a){return this.list.v[a]};Sk.builtin.listSlice.prototype.setitem=function(a,b){this.list.v[a]=b};Sk.builtin.listSlice.prototype.popleft=function(){var a=this.list.v[this.base];this.base++;this.len--;return a};Sk.builtin.listSlice.prototype.popright=function(){this.len--;return this.list.v[this.base+this.len]};
Sk.builtin.listSlice.prototype.reverse=function(){for(var a,b,c=this.list,d=this.base,e=d+this.len-1;d<e;)a=c.v[e],b=c.v[d],c.v[d]=a,c.v[e]=b,d++,e--};goog.exportSymbol("Sk.builtin.listSlice",Sk.builtin.listSlice);goog.exportSymbol("Sk.builtin.timSort",Sk.builtin.timSort);Sk.builtin.sorted=function(a,b,c,d){var e,f,g;if(void 0===c||c instanceof Sk.builtin.none)b instanceof Sk.builtin.none||void 0===b||(g=b);else for(g=b instanceof Sk.builtin.none||void 0===b?function(a,b){return Sk.misceval.richCompareBool(a[0],b[0],"Lt")?new Sk.builtin.int_(-1):new Sk.builtin.int_(0)}:function(a,c){return Sk.misceval.callsim(b,a[0],c[0])},f=a.tp$iter(),e=f.tp$iternext(),a=[];void 0!==e;)a.push([Sk.misceval.callsim(c,e),e]),e=f.tp$iternext();a=new Sk.builtin.list(a);void 0!==g?a.list_sort_(a,
g):a.list_sort_(a);d&&a.list_reverse_(a);if(void 0!==c&&!(c instanceof Sk.builtin.none)){f=a.tp$iter();e=f.tp$iternext();for(a=[];void 0!==e;)a.push(e[1]),e=f.tp$iternext();a=new Sk.builtin.list(a)}return a};Sk.builtins={range:Sk.builtin.range,round:Sk.builtin.round,len:Sk.builtin.len,min:Sk.builtin.min,max:Sk.builtin.max,sum:Sk.builtin.sum,zip:Sk.builtin.zip,abs:Sk.builtin.abs,fabs:Sk.builtin.abs,ord:Sk.builtin.ord,chr:Sk.builtin.chr,hex:Sk.builtin.hex,oct:Sk.builtin.oct,bin:Sk.builtin.bin,dir:Sk.builtin.dir,repr:Sk.builtin.repr,open:Sk.builtin.open,isinstance:Sk.builtin.isinstance,hash:Sk.builtin.hash,getattr:Sk.builtin.getattr,float_$rw$:Sk.builtin.float_,int_$rw$:Sk.builtin.int_,hasattr:Sk.builtin.hasattr,
map:Sk.builtin.map,filter:Sk.builtin.filter,reduce:Sk.builtin.reduce,sorted:Sk.builtin.sorted,bool:Sk.builtin.bool,any:Sk.builtin.any,all:Sk.builtin.all,enumerate:Sk.builtin.enumerate,AttributeError:Sk.builtin.AttributeError,ValueError:Sk.builtin.ValueError,Exception:Sk.builtin.Exception,ZeroDivisionError:Sk.builtin.ZeroDivisionError,AssertionError:Sk.builtin.AssertionError,ImportError:Sk.builtin.ImportError,IndentationError:Sk.builtin.IndentationError,IndexError:Sk.builtin.IndexError,KeyError:Sk.builtin.KeyError,
TypeError:Sk.builtin.TypeError,NameError:Sk.builtin.NameError,IOError:Sk.builtin.IOError,NotImplementedError:Sk.builtin.NotImplementedError,StandardError:Sk.builtin.StandardError,SystemExit:Sk.builtin.SystemExit,OverflowError:Sk.builtin.OverflowError,OperationError:Sk.builtin.OperationError,RuntimeError:Sk.builtin.RuntimeError,dict:Sk.builtin.dict,file:Sk.builtin.file,"function":Sk.builtin.func,generator:Sk.builtin.generator,list:Sk.builtin.list,long_$rw$:Sk.builtin.lng,method:Sk.builtin.method,object:Sk.builtin.object,
slice:Sk.builtin.slice,str:Sk.builtin.str,set:Sk.builtin.set,tuple:Sk.builtin.tuple,type:Sk.builtin.type,input:Sk.builtin.input,raw_input:Sk.builtin.raw_input,setattr:Sk.builtin.setattr,jseval:Sk.builtin.jseval,jsmillis:Sk.builtin.jsmillis,quit:Sk.builtin.quit,exit:Sk.builtin.quit,print:Sk.builtin.print,divmod:Sk.builtin.divmod,format:Sk.builtin.format,globals:Sk.builtin.globals,issubclass:Sk.builtin.issubclass,iter:Sk.builtin.iter,complex:Sk.builtin.complex,bytearray:Sk.builtin.bytearray,callable:Sk.builtin.callable,
delattr:Sk.builtin.delattr,eval_$rn$:Sk.builtin.eval_,execfile:Sk.builtin.execfile,frozenset:Sk.builtin.frozenset,help:Sk.builtin.help,locals:Sk.builtin.locals,memoryview:Sk.builtin.memoryview,next:Sk.builtin.next_,pow:Sk.builtin.pow,property:Sk.builtin.property,reload:Sk.builtin.reload,reversed:Sk.builtin.reversed,"super":Sk.builtin.superbi,unichr:Sk.builtin.unichr,vars:Sk.builtin.vars,xrange:Sk.builtin.xrange,apply_$rn$:Sk.builtin.apply_,buffer:Sk.builtin.buffer,coerce:Sk.builtin.coerce,intern:Sk.builtin.intern};
goog.exportSymbol("Sk.builtins",Sk.builtins);Sk.builtin.str.$emptystr=new Sk.builtin.str("");Sk.builtin.bool.true$=Object.create(Sk.builtin.bool.prototype,{v:{value:1,enumerable:!0}});Sk.builtin.bool.false$=Object.create(Sk.builtin.bool.prototype,{v:{value:0,enumerable:!0}});Sk.builtin.int_.co_varnames=["base"];Sk.builtin.int_.co_numargs=2;Sk.builtin.int_.$defaults=[new Sk.builtin.int_(10)];Sk.builtin.lng.co_varnames=["base"];Sk.builtin.lng.co_numargs=2;Sk.builtin.lng.$defaults=[new Sk.builtin.int_(10)];
Sk.builtin.sorted.co_varnames=["cmp","key","reverse"];Sk.builtin.sorted.co_numargs=4;Sk.builtin.sorted.$defaults=[Sk.builtin.none.none$,Sk.builtin.none.none$,!1];}());
</script>
{
"parserrules": {
"sandbox": "allow-same-origin allow-scripts allow-popups allow-forms"
},
"baserules": "",
"preparser": "text/vnd.tiddlywiki"
}